rijndael 128 cfb C#和php

时间:2014-01-31 09:38:00

标签: c# php cryptography rijndael

我有问题。我有一种方法来加密PHP和C#中的密码,但我不能用这两种算法得到相同的结果。有人可以帮帮我吗?

比索

<?php

$password = 'MySecretPass';
$secret = '65rgt85k89xrDAr3';
$iv = 'AAAAAAAAAAAAAAAA';


$td = mcrypt_module_open('rijndael-128', '', 'cfb','');
mcrypt_generic_init($td, $secret, $iv);

$password = mcrypt_generic($td, $password);

mcrypt_generic_deinit($td);
mcrypt_module_close($td);

$password=base64_encode($password);

echo $password;

?>

C#

var password = padString("MySecretPass");
txtEncrypt.Text = Convert.ToBase64String(EncryptStringToBytes(password,
    Encoding.UTF8.GetBytes("65rgt85k89xrDAr3"), 
    Encoding.UTF8.GetBytes("AAAAAAAAAAAAAAAA"), PaddingMode.None));
txtEncrypt.Text = txtEncrypt.Text;


static byte[] EncryptStringToBytes(string plainText, byte[] key, byte[] iv, PaddingMode mode)
{
    byte[] encrypted;

    using (var rijAlg = new RijndaelManaged { Mode = CipherMode.CFB, BlockSize = 128, Padding = mode })
    {
        rijAlg.Key = key;
                rijAlg.IV = iv;

                var 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;
}

     private static String padString(String source)
     {
         char paddingChar = ' ';
        int size = 16;
         int x = source.Length % size;
         int padLength = size - x;

         for (int i = 0; i < padLength; i++)
         {
             source += paddingChar;
         }

         return source;
     }

PhP的结果是“/ KNlzi / fZOERWL79”,但对于c#是/ J643dvAR4 / Gh0aYHdshNw ==。我不知道为什么我的结果不同。另外,我用Java编写代码,得到的结果与C#相同。

提前致谢。

1 个答案:

答案 0 :(得分:1)

可能Encoding.GetBytes(string)返回“Unicode编码”。这是一种实际上不存在的编码,但它返回UTF-16。另一方面,您将密钥和IV视为ASCII字符。

因此,当时PHP正在使用哪种编码,将会出现不匹配。您应该显式定义在将文本字符串转换为字节时应使用哪种编码,这两种编码都在PHP代码中,就像在C#代码中一样。