Rijndael 256在C#和PHP之间进行加密/解密?
我已经对C#代码进行了更改,因此它使用的块大小为256。但是现在,您好世界看起来像这样http://pastebin.com/5sXhMV11,我无法弄清楚应该使用rtrim()获得什么一团糟的最后。
另外,当您说IV应该是随机的时,您的意思是不要再使用一次相同的IV,否则我编码的方式错误吗?
再次感谢!
你好
我正在尝试使用在C#中加密的PHP解密字符串。我似乎无法让PHP使用mcrypt对其进行解密,请提供一些帮助。我在php中收到以下错误,所以我猜我没有正确设置IV。
两种功能使用相同的密码,密钥,IV并设置为CBC模式:
来自c#的加密文本= UmzUCnAzThH0nMkIuMisqg ==
密钥32长= qwertyuiopasdfghjklzxcvbnmqwerty
iv 16长= 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;
}
谢谢
回答:
如果要在C#应用程序中使用Rijndael256,则必须将BlockSize设置为256。
RijndaelManaged rj = new RijndaelManaged();rj.BlockSize = 256;
然后,您的iv也必须为256位长。
请参见SymmetricAlgorithm.BlockSize属性
或相反:当前,您的C#应用程序使用Rijndael128,因此您的php脚本也必须使用。
<?phpclass Foo {
protected $mcrypt_cipher = MCRYPT_RIJNDAEL_128;
protected $mcrypt_mode = MCRYPT_MODE_CBC;
public function decrypt($key, $iv, $encrypted)
{
$iv_utf = mb_convert_encoding($iv, 'UTF-8');
return mcrypt_decrypt($this->mcrypt_cipher, $key, base64_decode($encrypted), $this->mcrypt_mode, $iv_utf);
}
}
$encrypted = "UmzUCnAzThH0nMkIuMisqg==";
$key = "qwertyuiopasdfghjklzxcvbnmqwerty";
$iv = "1234567890123456";
$foo = new Foo;
echo $foo->decrypt($key, $iv, $encrypted);
版画 hello world
以上是 Rijndael 256在C#和PHP之间进行加密/解密? 的全部内容, 来源链接: utcz.com/qa/415424.html