我正在尝试在 ASP.NET Core Web API 项目中使用加密/解密。我发现这篇文章展示了加密和解密的工作示例:
https://mikaelkoskinen.net/post/encrypt-decrypt-string-asp-net-core
复制并运行,它有效,非常棒——到目前为止。
然后我更改了要加密/解密的字符串,如果因填充问题而失败,则不允许。
EncryptString
和 DecryptString
方法逐字记录到网站源代码。
// THIS IS ORIGINAL and works (without Console.WriteLine)
var content = "Example test";
var key = "E546C8DF278CD5931069B522E695D4F2";
var encrypted = EncryptString(content, key);
var decrypted = DecryptString(encrypted, key);
// Then I changed to encrypt a simple string and fails
content = "testing16charsX1";
encrypted = EncryptString(content, key);
decrypted = DecryptString(encrypted, key);
将函数的原始代码保留在此处的单一源位置。
public static string EncryptString(string text, string keyString)
{
var key = Encoding.UTF8.GetBytes(keyString);
using (var aesAlg = Aes.Create())
{
using (var encryptor = aesAlg.CreateEncryptor(key, aesAlg.IV))
{
using (var msEncrypt = new MemoryStream())
{
using (var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
using (var swEncrypt = new StreamWriter(csEncrypt))
{
swEncrypt.Write(text);
}
var iv = aesAlg.IV;
var decryptedContent = msEncrypt.ToArray();
var result = new byte[iv.Length + decryptedContent.Length];
Buffer.BlockCopy(iv, 0, result, 0, iv.Length);
Buffer.BlockCopy(decryptedContent, 0, result, iv.Length, decryptedContent.Length);
return Convert.ToBase64String(result);
}
}
}
}
public static string DecryptString(string cipherText, string keyString)
{
var fullCipher = Convert.FromBase64String(cipherText);
var iv = new byte[16];
var cipher = new byte[16];
Buffer.BlockCopy(fullCipher, 0, iv, 0, iv.Length);
Buffer.BlockCopy(fullCipher, iv.Length, cipher, 0, iv.Length);
var key = Encoding.UTF8.GetBytes(keyString);
using (var aesAlg = Aes.Create())
{
using (var decryptor = aesAlg.CreateDecryptor(key, iv))
{
string result;
using (var msDecrypt = new MemoryStream(cipher))
{
using (var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
{
using (var srDecrypt = new StreamReader(csDecrypt))
{
result = srDecrypt.ReadToEnd();
}
}
}
return result;
}
}
}
感谢帮助。此外,想要强制加密/解密为 AES256,这里没有关于 KeySize 设置为 256 的内容,但想要在不破坏的情况下进行测试,但似乎也被破坏了?
错误就在这里。在
EncryptString
方法中,它依次复制IV和加密内容:
var result = new byte[iv.Length + decryptedContent.Length];
Buffer.BlockCopy(iv, 0, result, 0, iv.Length);
Buffer.BlockCopy(decryptedContent, 0, result, iv.Length, decryptedContent.Length);
但是在
DecryptString
方法中,它只复制了16字节的加密内容:
var iv = new byte[16];
var cipher = new byte[16];
Buffer.BlockCopy(fullCipher, 0, iv, 0, iv.Length);
Buffer.BlockCopy(fullCipher, iv.Length, cipher, 0, iv.Length);
它应该复制所有剩余的内容:
var cipher = new byte[fullCipher.Length - iv.Length];
Buffer.BlockCopy(fullCipher, iv.Length, cipher, 0, cipher.Length);
AES默认的填充模式是pkcs7,如果你的输入数据长度正好是BlockSize,则会追加一个额外的块。如果您想强制加密内容长度为16,则需要将填充模式更改为None并手动填充输入数据。