我正在研究一种基础的加密方法,使用RijndaelManaged算法。代码来自很久以前的某个地方,但我现在记不起来了。
之前我的代码是可以工作的,但是最近出了些问题,我无法确定原因。
当我运行代码时,会得到以下错误:
指定的初始化向量(IV)与此算法的块大小不匹配。
这是我的代码:
string textToEncrypt = "TEST STRING";
int keySize = 256;
string hashAlgorithm = "SHA1";
string passPhrase = "AH!PSB0%FGHR$";
string saltValue = "LRT%YUR#VBNL@1";
string initVector = "HR$2pIjHR$2pIj";
byte[] initVectorBytes = Encoding.ASCII.GetBytes(initVector);
byte[] saltValueBytes = Encoding.ASCII.GetBytes(saltValue);
byte[] plainTextBytes = Encoding.UTF8.GetBytes(textToEncrypt);
var password = new PasswordDeriveBytes(passPhrase, saltValueBytes, hashAlgorithm, 2);
byte[] keyBytes = password.GetBytes(keySize / 8);
RijndaelManaged symmetricKey = new RijndaelManaged();
symmetricKey.Mode = CipherMode.CBC;
ICryptoTransform encryptor = symmetricKey.CreateEncryptor(keyBytes,initVectorBytes);
MemoryStream memoryStream = new MemoryStream();
var cryptoStream = new CryptoStream(memoryStream,encryptor,CryptoStreamMode.Write);
cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
cryptoStream.FlushFinalBlock();
byte[] cipherTextBytes = memoryStream.ToArray();
memoryStream.Close();
cryptoStream.Close();
string cipherText = Convert.ToBase64String(cipherTextBytes);
非常感谢您的帮助。