如何解密C#中的加密MCRYPT_RIJNDAEL_256值,该值是由PHP中的mcrypt加密的?

时间:2011-08-16 18:50:58

标签: c# php cryptography aes

我正在尝试从Linux端管理的数据库表中读取Base64编码值。在那里面 table有一个名为first_name的列。在Linux方面,我可以使用PHP中的以下命令轻松解密:

$data = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, "patient_fn_salt",
                       base64_decode("H6XmkH+VWvdD88THCliKJjLisGZIBk3CTNvyQMLnhpo="),
                       MCRYPT_MODE_ECB);

但是我尽可能多地尝试在C#端复制这个逻辑,而我得到的只是胡言乱语。

我的C#代码如下,我希望你有一些建议,因为我没有想法:(

byte [] cipherText =
         Convert.FromBase64String("H6XmkH+VWvdD88THCliKJjLisGZIBk3CTNvyQMLnhpo=");
byte [] key = Encoding.UTF8.GetBytes("patient_fn_salt");
Array.Resize(ref key, 32);
byte [] iv = new byte[32];

string fname = Utilities.Decrypt(cipherText, key, iv);


public static string Decrypt(byte[] cipherText, byte[] Key, byte[] IV)
  {
   // Check arguments.
   if (cipherText == null || cipherText.Length <= 0)
    throw new ArgumentNullException("cipherText");
   if (Key == null || Key.Length <= 0)
    throw new ArgumentNullException("Key");
   if (IV == null || IV.Length <= 0)
    throw new ArgumentNullException("Key");

   // TDeclare the streams used
   // to decrypt to an in memory
   // array of bytes.
   MemoryStream msDecrypt = null;
   CryptoStream csDecrypt = null;
   StreamReader srDecrypt = null;

   // Declare the AesManaged object
   // used to decrypt the data.
   RijndaelManaged rj = new RijndaelManaged();

   // Declare the string used to hold
   // the decrypted text.
   string plaintext = null;

   try
   {
    // Create an AesManaged object
    // with the specified key and IV.

    rj.Mode = CipherMode.ECB;
    rj.BlockSize = 256;
    rj.KeySize = 256;
    rj.Padding = PaddingMode.Zeros;

    rj.Key = Key;
    rj.GenerateIV();
    //rj.IV = IV;


    // Create a decrytor to perform the stream transform.
    ICryptoTransform decryptor = rj.CreateDecryptor(rj.Key, rj.IV);

    // Create the streams used for decryption.
    msDecrypt = new MemoryStream(cipherText);
    csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read);
    srDecrypt = new StreamReader(csDecrypt);

    // Read the decrypted bytes from the decrypting stream
    // and place them in a string.
    plaintext = srDecrypt.ReadToEnd();
   }
   finally
   {
    // Clean things up.

    // Close the streams.
    if (srDecrypt != null)
     srDecrypt.Close();
    if (csDecrypt != null)
     csDecrypt.Close();
    if (msDecrypt != null)
     msDecrypt.Close();

    // Clear the AesManaged object.
    if (rj != null)
     rj.Clear();
   }
   return plaintext;
  }
 }

3 个答案:

答案 0 :(得分:5)

正如Paŭlo所说,ECB模式不使用IV。如果C#坚持使用,则使用所有零字节。

键“patient_fn_salt”是15个字符,120位。您的解密功能需要256位密钥。您需要非常确保两个系统中的额外位相同,并且在两个系统中的相同位置添加。即使一位错误也会导致垃圾解密。请仔细阅读PHP文档,以确定“patient_fn_salt”如何扩展为256位密钥。特别检查实际密钥是否为SHA256("patient_fn_salt")

另外,ECB模式是不安全的。优先使用CTR模式或CBC模式。 CTR模式不需要填充,因此可能意味着存储更少的密文。

ETA:在另一个阅读中,我注意到C#端用零填充。 PHP方面使用什么填充?零填充不是一个好主意,因为它无法识别错误的解密。 PKCS7填充具有更好的识别输出错误的机会。最好明确指定两端的填充,而不是依赖默认值。

答案 1 :(得分:5)

邮政已经过时了,但未来可能对某人有所帮助。此函数的加密方式与mcrypt_encrypt完全相同,参数为MCRYPT_RIJNDAEL_256和MCRYPT_MODE_ECB

    static byte[] EncryptStringToBytes(string plainText, byte[] key)
    {
        if (plainText == null || plainText.Length <= 0)
            throw new ArgumentNullException("plainText");
        if (key == null || key.Length <= 0)
            throw new ArgumentNullException("key");

        byte[] encrypted;
        using (var rijAlg = new RijndaelManaged())
        {
            rijAlg.BlockSize = 256;
            rijAlg.Key = key;
            rijAlg.Mode = CipherMode.ECB;
            rijAlg.Padding = PaddingMode.Zeros;
            rijAlg.IV = new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };

            ICryptoTransform encryptor = rijAlg.CreateEncryptor(rijAlg.Key, rijAlg.IV);
            using (var msEncrypt = new MemoryStream())
                using (var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                {
                    using (var swEncrypt = new StreamWriter(csEncrypt))
                        swEncrypt.Write(plainText);
                    encrypted = msEncrypt.ToArray();
                }
        }
        return encrypted;
    }

这是解密它的功能

     static string DecryptStringFromBytes(byte[] cipherText, byte[] key)
     {
        if (cipherText == null || cipherText.Length <= 0)
            throw new ArgumentNullException("cipherText");
        if (key == null || key.Length <= 0)
            throw new ArgumentNullException("key");

        string plaintext;
        using (var rijAlg = new RijndaelManaged())
        {
            rijAlg.BlockSize = 256;
            rijAlg.Key = key;
            rijAlg.Mode = CipherMode.ECB;
            rijAlg.Padding = PaddingMode.Zeros;
            rijAlg.IV = new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };

            ICryptoTransform decryptor = rijAlg.CreateDecryptor(rijAlg.Key, rijAlg.IV);
            using (var msDecrypt = new MemoryStream(cipherText))
                using (var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                    using (var srDecrypt = new StreamReader(csDecrypt))
                        plaintext = srDecrypt.ReadToEnd();
        }
        return plaintext;
    }

答案 2 :(得分:0)

与旧版系统通信时,我遇到了同样的问题。我不得不想出自己的解决方案,因为dotnet内核似乎不支持Blocksize为256的Rijndael。

这是我使用充气城堡库的解决方案:

    public static byte[] Rijandael256Decrypt(byte[] inputBytes, byte[] keyBytes)
    {
        // set up
        IBufferedCipher cipher = new PaddedBufferedBlockCipher(new RijndaelEngine(256), new ZeroBytePadding());
        KeyParameter keyParam = new KeyParameter(keyBytes);
        cipher.Init(false, keyParam);
        int sizeAtLeastRequired = cipher.GetOutputSize(inputBytes.Length);
        byte[] outputBytes = new byte[sizeAtLeastRequired];

        // decrypt            
        int length = cipher.ProcessBytes(inputBytes, outputBytes, 0);
        length += cipher.DoFinal(outputBytes, length);

        // resize output
        Array.Resize(ref outputBytes, length);
        return outputBytes;
    }