我正在尝试解密此数据,给定密钥和 IV,但 c# 和 openssl 之间的结果不同
Openssl操作:
### client key
$ hexkey=f656d037b173ef3e11169f27231a84b6
### IV for this record
$ hexiv=404142434445464748494a4b4c4d4e4f
### encrypted data
$ echo '22 7b c9 ba 81 ef 30 f2 a8 a7 8f f1 df 50 84 4d' > /tmp/msg1
$ echo '58 04 b7 ee b2 e2 14 c3 2b 68 92 ac a3 db 7b 78' >> /tmp/msg1
$ echo '07 7f dd 90 06 7c 51 6b ac b3 ba 90 de df 72 0f' >> /tmp/msg1
$ xxd -r -p /tmp/msg1 \
| openssl enc -d -nopad -aes-128-cbc -K $hexkey -iv $hexiv | hexdump
C#操作:
public static string DecryptWithOpenSSL(byte[] base64CipherText, byte[] key, byte[] iv)
{
try
{
using (Aes aesAlg = Aes.Create())
{
aesAlg.Key = key;
aesAlg.IV = iv;
aesAlg.Mode = CipherMode.CBC;
aesAlg.Padding = PaddingMode.None;
ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
using (MemoryStream msDecrypt = new MemoryStream(base64CipherText))
using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
using (StreamReader srDecrypt = new StreamReader(csDecrypt))
{
return srDecrypt.ReadToEnd();
}
}
}
catch (Exception ex)
{
Console.WriteLine("Error decrypting data: " + ex.Message);
return null;
}
}
Openssl 结果:
14 00 00 0c cf 91 96 26 f1 36 0c 53 6a aa d7 3a .......
C# 结果:
14 00 00 0C CF 91 EFBFBD26EFBFBD360C536AEFBFBDEFBFBD3AEFBFBD
密钥和 IV 的格式正确。 如您所见,只有前 6 个字节看起来相同。 如果有人可以帮忙:)
因为您使用的是
StreamReader
,我很惊讶它没有抛出任何异常... StreamReader
用于读取文本而不是二进制数据。要读取二进制文件,您可以将 CryptoStream
复制到 MemoryStream
(或任何其他流,例如 FileStream
)
var ms = new MemoryStream();
csDecrypt.CopyTo(ms);
var bytes = ms.ToArray();