更新
我已经更改了C#代码,使其使用块大小为256。但现在,你好世界看起来像这样http://pastebin.com/5sXhMV11,我无法弄清楚应该使用什么来与rtrim()配合以去除末尾的混乱。
另外,当您说IV应该是随机的时候,您是否意味着不要多次使用相同的IV,或者我编写的方法是错误的?
再次感谢!
嗨,
我正在尝试使用PHP解密由C#加密的字符串。我似乎无法使用mcrypt解密它,所以需要一些帮助。我得到以下错误,因此我猜测我没有正确设置IV。
错误:IV参数必须与块大小一样长
两个函数都使用相同的密码,密钥,IV并设置为CBC模式:
C#中的加密文本= UmzUCnAzThH0nMkIuMisqg==
32位长的密钥= qwertyuiopasdfghjklzxcvbnmqwerty
16位长的iv = 1234567890123456
C#
public static string EncryptString(string message, string KeyString, string IVString)
{
byte[] Key = ASCIIEncoding.UTF8.GetBytes(KeyString);
byte[] IV = ASCIIEncoding.UTF8.GetBytes(IVString);
string encrypted = null;
RijndaelManaged rj = new RijndaelManaged();
rj.Key = Key;
rj.IV = IV;
rj.Mode = CipherMode.CBC;
try
{
MemoryStream ms = new MemoryStream();
using (CryptoStream cs = new CryptoStream(ms, rj.CreateEncryptor(Key, IV), CryptoStreamMode.Write))
{
using (StreamWriter sw = new StreamWriter(cs))
{
sw.Write(message);
sw.Close();
}
cs.Close();
}
byte[] encoded = ms.ToArray();
encrypted = Convert.ToBase64String(encoded);
ms.Close();
}
catch (CryptographicException e)
{
Console.WriteLine("A Cryptographic error occurred: {0}", e.Message);
return null;
}
catch (UnauthorizedAccessException e)
{
Console.WriteLine("A file error occurred: {0}", e.Message);
return null;
}
catch (Exception e)
{
Console.WriteLine("An error occurred: {0}", e.Message);
}
finally
{
rj.Clear();
}
return encrypted;
}
PHP
var $mcrypt_cipher = MCRYPT_RIJNDAEL_256;
var $mcrypt_mode = MCRYPT_MODE_CBC;
function decrypt($key, $iv, $encrypted)
{
$encrypted = base64_decode($encrypted);
$decrypted = rtrim(mcrypt_decrypt($this->mcrypt_cipher, $key, $encrypted, $this->mcrypt_mode, $iv), "\0");;
return $decrypted;
}
谢谢