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实现,只是我想要工作的东西所以我可以继续了解算法。
感谢您的帮助。
答案 0 :(得分:9)
IV必须与块大小完全相同,在AES的情况下,该大小为16字节。