AES 内置在框架中,作为 System.Security.Cryptography 中的Aes 类。有两种具体的实现,一种是托管的,一种是使用 Windows Crypto Service Provider(速度更快,但不能移植到其他平台)。还有一个Rijndael 的实现,AES 就是从该实现中派生出来的。
请记住,您需要一个初始化向量以及加密/解密的密钥,因为它是一个分组密码。如果您在未设置的情况下进行加密,则将使用随机一个,但您需要存储和检索它以进行解密。
示例代码:(摘自我即将出版的书 grin 的第 6 章)
static byte[] Encrypt(byte[] clearText, byte[] key, byte[] iv)
{
// Create an instance of our encyrption algorithm.
RijndaelManaged rijndael = new RijndaelManaged();
// Create an encryptor using our key and IV
ICryptoTransform transform = rijndael.CreateEncryptor(key, iv);
// Create the streams for input and output
MemoryStream outputStream = new MemoryStream();
CryptoStream inputStream = new CryptoStream(
outputStream,
transform,
CryptoStreamMode.Write);
// Feed our data into the crypto stream.
inputStream.Write(clearText, 0, clearText.Length);
// Flush the crypto stream.
inputStream.FlushFinalBlock();
// And finally return our encrypted data.
return outputStream.ToArray();
}
解密
static byte[] Decyrpt(byte[] clearText, byte[] key, byte[] iv)
{
// Create an instance of our encryption algorithm.
RijndaelManaged rijndael = new RijndaelManaged();
// Create an decryptor using our key and IV
ICryptoTransform transform = rijndael.CreateDecryptor(key, iv);
// Create the streams for input and output
MemoryStream outputStream = new MemoryStream();
CryptoStream inputStream = new CryptoStream(
outputStream,
transform,
CryptoStreamMode.Write);
// Feed our data into the crypto stream.
inputStream.Write(clearText, 0, clearText.Length);
// Flush the crypto stream.
inputStream.FlushFinalBlock();
// And finally return our decrypted data.
return outputStream.ToArray();
}
将 RijndaelManaged 类替换为 AES 类之一和合适的密钥。