【问题标题】:Encrypt AES in PHP, decrypt in C#在 PHP 中加密 AES,在 C# 中解密
【发布时间】:2011-08-09 19:54:10
【问题描述】:

我尝试在 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();    


    }

【问题讨论】:

    标签: c# php cryptography


    【解决方案1】:

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

    【讨论】:

    • 但我不想将向量 IV 保存在数据库中
    • CTR模式不需要IV,只需要一个nonce,可以更小。
    【解决方案2】:

    快速浏览一下,您并没有向 C# 解密器提供 IV:

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

    我不熟悉 php,但看起来您在加密内容时创建了一个 IV。您需要使用相同的 IV 才能在 C# 代码中对其进行解密(即使您通过 php 进行解密,也需要相同的 IV 来解密)。

    【讨论】:

    • rijndaeld.Padding=Padding.zero;
    • ECB模式不使用任何IV。
    • 这不是一个有效的答案,因为欧洲央行不使用任何 IV。
    • @AlexMaker - 嗯....如果可以的话,我会删除它,但它不会让我删除已接受的答案。
    猜你喜欢
    • 2020-12-23
    • 1970-01-01
    • 1970-01-01
    • 2016-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多