public static string GenerateKey()
{
AesCryptoServiceProvider aesCrypto = (AesCryptoServiceProvider)AesCryptoServiceProvider.Create();
// Use the Automatically generated key for Encryption.
return ASCIIEncoding.ASCII.GetString(aesCrypto.Key);
}
static void EncryptFile(string sInputFilename, string sOutputFilename, string sKey)
{
FileStream fsInput = new FileStream(sInputFilename, FileMode.Open, FileAccess.Read);
FileStream fsEncrypted = new FileStream(sOutputFilename, FileMode.Create, FileAccess.Write);
AesCryptoServiceProvider AES = new AesCryptoServiceProvider();
// Sets the appropriate block size for the AES Encryption Method
AES.BlockSize = 128;
AES.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
AES.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
ICryptoTransform aesencrypt = AES.CreateEncryptor();
CryptoStream cryptostream = new CryptoStream(fsEncrypted, aesencrypt, CryptoStreamMode.Write);
byte[] bytearrayinput = new byte[fsInput.Length];
fsInput.Read(bytearrayinput, 0, bytearrayinput.Length);
cryptostream.Write(bytearrayinput, 0, bytearrayinput.Length);
cryptostream.Close();
fsInput.Close();
fsEncrypted.Close();
}
static void DecryptFile(string sInputFilename, string sOutputFilename, string sKey)
{
AesCryptoServiceProvider AES = new AesCryptoServiceProvider();
//A 64 bit key and IV is required for this provider.
//Set secret key For DES algorithm.
AES.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
//Set initialization vector.
AES.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
//Create a file stream to read the encrypted file back.
FileStream fsread = new FileStream(sInputFilename, FileMode.Open, FileAccess.Read);
//Create a DES decryptor from the DES instance.
ICryptoTransform aesdecrypt = AES.CreateDecryptor();
//Create crypto stream set to read and do a
//DES decryption transform on incoming bytes.
CryptoStream cryptostreamDecr = new CryptoStream(fsread, aesdecrypt, CryptoStreamMode.Read);
//Print the contents of the decrypted file.
StreamWriter fsDecrypted = new StreamWriter(sOutputFilename);
fsDecrypted.Write(new StreamReader(cryptostreamDecr).ReadToEnd());
fsDecrypted.Flush();
fsDecrypted.Close();
}
我在 EncryptFile 方法的这一行中得到了标题中列出的异常。
AES.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
我直接在该行之前设置了 BlockSize,并且我确定 AES 应该使用 16 字节的块大小,那么我该怎么做才能让它工作呢?我不确定为什么代码仍然存在块大小问题。
注意:我只是在尝试我在网上找到的一些示例,这并不意味着是一个锁紧的 AES 实现,只是我想开始工作,以便我可以继续了解该算法。
谢谢你的帮助。