我正在尝试使用AesCryptoServiceProvider
来实现与Aes
. 这是我的AesCryptoServiceProvider
版本:
public string version1(string plainText, string encryptionKey, string initializationVector)
{
AesCryptoServiceProvider provider = new AesCryptoServiceProvider
{
BlockSize = 128,
Padding = PaddingMode.PKCS7,
Key = Convert.FromBase64String(encryptionKey),
IV = Encoding.UTF8.GetBytes(initializationVector)
};
byte[] buffer = Encoding.ASCII.GetBytes(plainText);
byte[] encrypted = provider.CreateEncryptor().TransformFinalBlock(buffer, 0, buffer.Length);
return Convert.ToBase64String(encrypted);
}
这是Aes
它的版本:
public string version2(string plainText, string encryptionKey, string initializationVector)
{
byte[] clearBytes = Encoding.UTF8.GetBytes(plainText);
byte[] encryptedBytes;
byte[] iv = Encoding.UTF8.GetBytes(initializationVector);
using (Aes aes = Aes.Create())
{
aes.BlockSize = 128;
aes.Padding = PaddingMode.PKCS7;
aes.Key = Convert.FromBase64String(encryptionKey);
aes.IV = iv;
using (MemoryStream ms = new MemoryStream())
using (CryptoStream cs = new CryptoStream(ms, aes.CreateEncryptor(), CryptoStreamMode.Write))
{
cs.Write(clearBytes, 0, clearBytes.Length);
cs.Close();
encryptedBytes = ms.ToArray();
}
}
byte[] ivEncryptedBytes = new byte[iv.Length + encryptedBytes.Length];
Buffer.BlockCopy(iv, 0, ivEncryptedBytes, 0, iv.Length);
Buffer.BlockCopy(encryptedBytes, 0, ivEncryptedBytes, iv.Length, encryptedBytes.Length);
return Convert.ToBase64String(ivEncryptedBytes);
}
当我使用 version1 和 version2 加密相同的字符串时,它们就不同了。关于这两种方法有何不同以及如何使 version1 产生与 version2 相同的加密字符串的任何想法?(ps我对加密很陌生,如果答案很明显,我很抱歉)谢谢!