【发布时间】:2020-02-19 17:45:47
【问题描述】:
我正在尝试使用 aes-128-gcm 进行加密和解密。 但是当我运行测试时出现错误:
System.Security.Cryptography.CryptographicException : 计算出的身份验证标签与输入身份验证标签不匹配。
我不明白为什么会出现这个错误,因为当我在加密方法中打印标签并在解密方法中打印它时,它们是一样的?我已经读到相关数据可能会改变一些东西,但我没有找到任何东西。
这是测试
[TestCase("ABC", "ABC")]
public void TestEncrypDecrypt(string message, string expected)
{
string cle = "FnUoIZvBUzC1Q/rn5WMi7Q==";
var aes = new AESEncryption(cle);
var crypted = aes.Encrypt(message);
Assert.That(aes.Decrypt(crypted), Is.EqualTo(expected));
}
这是我的课:
public class AESEncryption : IEncryption
{
private byte[] KEY { get; set; }
private byte[] TAG { get; set; }
public AESEncryption(string key)
{
KEY = Convert.FromBase64String(key);
TAG = new byte[16];
}
public string Encrypt(string message)
{
byte[] plainText = Encoding.UTF8.GetBytes(message);
byte[] ciphertext = new byte[plainText.Length];
using (AesGcm aesGcm = new AesGcm(KEY))
{
aesGcm.Encrypt(
new byte[]{ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B },
plainText,
ciphertext,
TAG);
}
return Convert.ToBase64String(ciphertext);
}
public string Decrypt(string message)
{
byte[] cipherText = Encoding.UTF8.GetBytes(message);
byte[] plainText = new byte[cipherText.Length];
using (AesGcm aesGcm = new AesGcm(KEY))
{
aesGcm.Decrypt(new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B },
cipherText,
TAG,
plainText);
Console.WriteLine("d1 " + Convert.ToBase64String(TAG));
}
return Convert.ToBase64String(plainText);
}
}
非常感谢!
【问题讨论】: