我需要解密通过CakePHP的Security::rijndael
库加密的C#字符串。
使用如下方式在PHP中加密字符串:
base64_encode(Security::rijndael($pw, Configure::read('SecretKey'), 'encrypt'))
最终的编码长度为88个字符,并存储在数据库中。
这是我尝试在C#中解密的方式:
public static string Decrypt(string encode, string secretKey)
{
var sha = SHA256Managed.Create();
var saltBytes = sha.ComputeHash(Encoding.ASCII.GetBytes(secretKey));
var key = new Rfc2898DeriveBytes(secretKey, saltBytes);
var rm = new RijndaelManaged();
rm.Mode = CipherMode.CBC;
rm.KeySize = 256;
rm.BlockSize = 256;
rm.Key = key.GetBytes(rm.KeySize / 8);
rm.IV = key.GetBytes(rm.BlockSize / 8);
var decryptor = rm.CreateDecryptor(rm.Key, rm.IV);
var cipher = Convert.FromBase64String(encode);
string decrypted;
using (var msDescrypt = new MemoryStream(cipher))
{
using (var csDescrypt = new CryptoStream(msDescrypt, decryptor, CryptoStreamMode.Read))
{
using (var srDescrypt = new StreamReader(csDescrypt))
{
decrypted = srDescrypt.ReadToEnd();
}
}
}
return decrypted;
}
当读取流时,出现一个异常“要解密的数据长度无效”。我是否需要操纵传入的编码字符串来使其工作?