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

2022-08-31 01:16:11

我正在尝试从Linux端管理的数据库表中读取Base64编码的值。在该表中,有一个名为 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;
  }
 }

答案 1

帖子很旧,但这可能会在将来帮助某人。此函数使用参数 MCRYPT_RIJNDAEL_256 和 MCRYPT_MODE_ECB 进行与mcrypt_encrypt完全相同的加密

    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

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

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

顺便说一句,欧洲央行模式是不安全的。请优先使用点击率模式或全血细胞计数模式。CTR 模式不需要填充,因此可能意味着要存储的密码文本更少。

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


推荐