我目前在解密由 php mcrypt 加密的消息时遇到了一些问题。php代码如下:
<?php
//$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_CBC);
$iv = "45287112549354892144548565456541";
$key = "anjueolkdiwpoida";
$text = "This is my encrypted message";
$crypttext = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $text, MCRYPT_MODE_CBC, $iv);
$crypttext = urlencode($crypttext);
$crypttext64=base64_encode($crypttext);
print($crypttext64) . "\n<br/>";
?>
然后将加密的消息发送到 ASP.NET 平台 (C#)。但是,我在保留解密顺序(base64 解码到 urldecode)时遇到问题。我在 ASP.NET 中的代码如下(iv 和 key 与 php 中的相同):
public string Decode(string str)
{
byte[] decbuff = Convert.FromBase64String(str);
return System.Text.Encoding.UTF8.GetString(decbuff);
}
static public String DecryptRJ256(string cypher, string KeyString, string IVString)
{
string sRet = "";
RijndaelManaged rj = new RijndaelManaged();
UTF8Encoding encoding = new UTF8Encoding();
try
{
//byte[] message = Convert.FromBase64String(cypher);
byte[] message = encoding.GetBytes(cypher);
byte[] Key = encoding.GetBytes(KeyString);
byte[] IV = encoding.GetBytes(IVString);
rj.Padding = PaddingMode.Zeros;
rj.Mode = CipherMode.CBC;
rj.KeySize = 256;
rj.BlockSize = 256;
rj.Key = Key;
rj.IV = IV;
MemoryStream ms = new MemoryStream(message);
using (CryptoStream cs = new CryptoStream(ms, rj.CreateDecryptor(Key, IV), CryptoStreamMode.Read))
{
using (StreamReader sr = new StreamReader(cs))
{
sRet = sr.ReadToEnd();
}
}
}
finally
{
rj.Clear();
}
return sRet;
}
string temp = DecryptRJ256(Server.UrlDecode(Decode(cypher)), keyString, ivString);
我遇到的问题是,从 php 收到加密消息后,我将其转换为 byte[],然后转换回 UTF8 编码的字符串,这样我就可以对其进行 urldecode。然后我将结果输入到函数中,在该函数中我将字符串转换回 byte[] 并通过解密过程运行它。但是,我无法得到想要的结果......有什么想法吗?
提前致谢。