繁体   English   中英

用PHP加密AES,用C#解密

[英]Encrypt AES in PHP, decrypt in C#

我试图在PHP中使用此函数对数据进行加密,然后在C#中使用其他函数对其进行解密。 但是我没有得到相同的字符串。

//php function
    public function onCrypt($text)
    {   
    $key=md5('DFDFDFDFDFDFDFDFDFDFDFDF',true);

    $crypttext = urldecode(trim(mcrypt_encrypt(MCRYPT_RIJNDAEL_128,$key, $text, MCRYPT_MODE_ECB, mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB), MCRYPT_RAND))));

    $text_crp =base64_encode($crypttext);


    return $text_crp;
            }

// c#函数

// public static void DecryptFile参数:strKey:解密中选择的密钥。 PathPlainTextFile:加密文件的路径PathPlainTextFile:解密的原始文件。

public static void DecryptFile(string strKey, string pathPlainTextFile, string pathCypheredTextFile)     
  {  

//crypt key with md5 function           
System.Security.Cryptography.MD5 alg = System.Security.Cryptography.MD5.Create();
System.Text.UTF8Encoding enc = new System.Text.UTF8Encoding();
byte[] md5val = alg.ComputeHash(enc.GetBytes(strKey));


StreamReader fsPlainTextFile = File.OpenText(pathPlainTextFile);    
FileInfo t = new FileInfo(pathCypheredTextFile);
StreamWriter Tex =t.CreateText();
string input = null;
while ((input = fsPlainTextFile.ReadLine()) != null)
{


        byte[] cipheredData = Convert.FromBase64String(input);

           RijndaelManaged rijndaeld = new RijndaelManaged();

            // define the used mode
            rijndaeld.Mode = CipherMode.ECB;

            // create the cipher AES - Rijndael
            ICryptoTransform decryptor = rijndaeld.CreateDecryptor(md5val,null);

             // Write the ciphered data in  MemoryStream
            MemoryStream ms= new MemoryStream(cipheredData);
            CryptoStream cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read);

                 // Insert  the ciphered data in a byte array
               byte[] plainTextData = new byte[cipheredData.Length];

            int decryptedByteCount = cs.Read(plainTextData, 0, plainTextData.Length);

            ms.Close();
            cs.Close();


   // Insert  the ciphered data in string encoded on Base64         
Tex.WriteLine (Encoding.UTF8.GetString(plainTextData, 0, decryptedByteCount));





}

Tex.Close();    


    }

ECB模式不安全。 您应该使用CTR模式或CBC模式。 最好也明确指定要在两端使用的填充。

乍一看,您没有向C#解密器提供IV:

ICryptoTransform decryptor = rijndaeld.CreateDecryptor(md5val, null);

我对php不熟悉,但是好像您在加密内容时创建了IV。 您需要具有相同的IV才能在C#代码中对其进行解密(即使您通过php进行解密,也需要相同的IV才能对其进行解密)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM