Implementation of AES Encryption in C#
Introduction to the AES Algorithm The Advanced Encryption Standard (English: Advanced Encryption Standard, abbreviation: AES), also known in cryptography as the Rijndael cipher, is a block cipher standard adopted by the U.S. federal government. This standard is used to replace the original DES, has been analyzed by many parties, and is widely used around the world. After a five-year selection process, the Advanced Encryption Standard was published by the National Institute of Standards and Technology (NIST) on November 26, 2001 in FIPS PUB 197, and on May 26, 2002
目录3 个章节
Introduction to the AES Algorithm

Advanced Encryption Standard (English: Advanced Encryption Standard, abbreviation: AES), also known in cryptography as the Rijndael cipher, is a block cipher standard adopted by the U.S. federal government. This standard is used to replace the original DES, has been analyzed by many parties, and is widely used around the world. After a five-year selection process, the Advanced Encryption Standard was published by the National Institute of Standards and Technology (NIST) on November 26, 2001 in FIPS PUB 197, and became an effective standard on May 26, 2002. In 2006, the Advanced Encryption Standard had already become one of the most popular algorithms in symmetric-key encryption.
This algorithm was designed by Belgian cryptographers Joan Daemen and Vincent Rijmen, who combined the two authors' names and submitted it as Rijndael to the Advanced Encryption Standard selection process. (Rijndael is pronounced similarly to "Rhine doll")
AES Encryption Process
The AES encryption process operates on a 4×4 byte matrix, also called the "body (state)", whose initial value is a plaintext block (the size of one element in the matrix is one Byte in the plaintext block). (Because the Rijndael cipher supports larger blocks, the number of rows in its matrix may be increased as appropriate.) During encryption, each round of the AES encryption cycle (except the last round) includes 4 steps:
AddRoundKey—each byte in the matrix undergoes an XOR operation with that round key (round key); each subkey is generated by the key generation scheme.SubBytes—through a nonlinear substitution function, each byte is replaced with the corresponding byte by means of a lookup table.ShiftRows—cyclically shift each row in the matrix.MixColumns—an operation to thoroughly mix each column in the matrix. This step uses a linear transformation to mix the four bytes of each inline. In the last encryption cycle, theMixColumnsstep is omitted and replaced with anotherAddRoundKey.
C# Code Implementation
Define the default key vector
private static byte[] _aesKetByte = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF, 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
private static string _aesKeyStr = Encoding.UTF8.GetString(_aesKetByte);
Randomly generate a key
public static byte[] GetIv(int n)
{
char[] arrChar = new char[]{
'a','b','d','c','e','f','g','h','i','j','k','l','m','n','p','r','q','s','t','u','v','w','z','y','x',
'0','1','2','3','4','5','6','7','8','9',
'A','B','C','D','E','F','G','H','I','J','K','L','M','N','Q','P','R','T','S','V','U','W','X','Y','Z'
};
StringBuilder num = new StringBuilder();
Random rnd = new Random(DateTime.Now.Millisecond);
for (int i = 0; i < n; i++)
{
num.Append(arrChar[rnd.Next(0, arrChar.Length)].ToString());
}
_aesKetByte = Encoding.UTF8.GetBytes(num.ToString());
return _aesKetByte;
}
AES Encryption
/// <summary>
/// AES加密
/// </summary>
/// <param name="Data">被加密的明文</param>
/// <param name="Key">密钥</param>
/// <param name="Vector">向量</param>
/// <returns>密文</returns>
public static String AESEncrypt(String Data, String Key, String Vector)
{
Byte[] plainBytes = Encoding.UTF8.GetBytes(Data);
Byte[] bKey = new Byte[32];
Array.Copy(Encoding.UTF8.GetBytes(Key.PadRight(bKey.Length)), bKey, bKey.Length);
Byte[] bVector = new Byte[16];
Array.Copy(Encoding.UTF8.GetBytes(Vector.PadRight(bVector.Length)), bVector, bVector.Length);
Byte[] Cryptograph = null; // 加密后的密文
Rijndael Aes = Rijndael.Create();
try
{
// 开辟一块内存流
using (MemoryStream Memory = new MemoryStream())
{
// 把内存流对象包装成加密流对象
using (CryptoStream Encryptor = new CryptoStream(Memory,
Aes.CreateEncryptor(bKey, bVector),
CryptoStreamMode.Write))
{
// 明文数据写入加密流
Encryptor.Write(plainBytes, 0, plainBytes.Length);
Encryptor.FlushFinalBlock();
Cryptograph = Memory.ToArray();
}
}
}
catch
{
Cryptograph = null;
}
return Convert.ToBase64String(Cryptograph);
}
AES Decryption
/// <summary>
/// AES解密
/// </summary>
/// <param name="Data">被解密的密文</param>
/// <param name="Key">密钥</param>
/// <param name="Vector">向量</param>
/// <returns>明文</returns>
public static String AESDecrypt(String Data, String Key, String Vector)
{
Byte[] encryptedBytes = Convert.FromBase64String(Data);
Byte[] bKey = new Byte[32];
Array.Copy(Encoding.UTF8.GetBytes(Key.PadRight(bKey.Length)), bKey, bKey.Length);
Byte[] bVector = new Byte[16];
Array.Copy(Encoding.UTF8.GetBytes(Vector.PadRight(bVector.Length)), bVector, bVector.Length);
Byte[] original = null; // 解密后的明文
Rijndael Aes = Rijndael.Create();
try
{
// 开辟一块内存流,存储密文
using (MemoryStream Memory = new MemoryStream(encryptedBytes))
{
// 把内存流对象包装成加密流对象
using (CryptoStream Decryptor = new CryptoStream(Memory,
Aes.CreateDecryptor(bKey, bVector),
CryptoStreamMode.Read))
{
// 明文存储区
using (MemoryStream originalMemory = new MemoryStream())
{
Byte[] Buffer = new Byte[1024];
Int32 readBytes = 0;
while ((readBytes = Decryptor.Read(Buffer, 0, Buffer.Length)) > 0)
{
originalMemory.Write(Buffer, 0, readBytes);
}
original = originalMemory.ToArray();
}
}
}
}
catch
{
original = null;
}
return Encoding.UTF8.GetString(original);
}
Encrypt and decrypt using the default vector
/// <summary>
/// AES加密(无向量)
/// </summary>
/// <param name="Data">被加密的明文</param>
/// <param name="Key">密钥</param>
/// <returns>密文</returns>
public static string AESEncrypt(String Data, String Key)
{
return AESEncrypt(Data, Key, _aesKeyStr);
}
/// <summary>
/// AES解密(无向量)
/// </summary>
/// <param name="Data">被加密的明文</param>
/// <param name="Key">密钥</param>
/// <returns>明文</returns>
public static string AESDecrypt(String Data, String Key)
{
return AESDecrypt(Data, Key, _aesKeyStr);
}
_EOF_
Implementation of AES Encryption in C#
- 本文作者:
- 程序设计实验室
- 版权声明:
- 本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
相关文章
C#实现生成Markdown文档目录树
前言 之前我写了一篇关于C#处理Markdown文档的文章:C#解析Markdown文档,实现替换图片链接操作 算是第一次尝试使用C#处理Markdown文档,然后最近又把博客网站的前台改了一下,目前文章渲染使用Editor.md组件在前端渲染,但这个插件生成的目录树很丑,我魔改了一下换成bootstrap5-treeview组件,好看多了。详见这篇文章:魔改editormd组件,优化ToC渲染效
2022-10-26 · C# · 约 1 分钟
System.Text.Json使用中的几个常见问题
前言 以前.NetCore是不内置JSON库的,所以大家都用Newtonsoft的JSON库,而且也确实挺好用的,不过既然官方出了标准库,那更方便更值得我们多用用,至少不用每次都nuget安装Newtonsoft.Json库了。 不过日常开发使用中会有一些问题,本文记录一下解决方法,欢迎交流~ ~~(文章末尾包含小彩蛋)~~ 字符编码问题 默认的 System.Text.Json 序列化的时候会把
2022-05-27 · C# · 约 1 分钟
让 C# 也拥有 gofmt 般的体验:用 CSharpier + Roslyn 实现 csfmt
C# 代码长到像答辩?用 CSharpier 自动折行,再用 Roslyn 修正 K&R 花括号,Taskfile 一键收尾。再补上 format-check,省得 CI 反复制造 Git diff。两步流水线并非原生 gofmt,顺序和版本仍得老实锁住。
2026-10-22 · C# · 约 1 分钟
使用C#和MemoryCache组件实现轮流调用APIKey以提高并发能力
本文介绍了如何利用C#语言中的MemoryCache组件,结合并发编程技巧,实现轮流调用多个API Key以提高系统的并发能力。通过示例代码和详细说明,读者将了解如何有效地管理API Key的调用次数限制,并优化系统性能。
2024-03-09 · C# · 约 1 分钟
讨论
共 0 条加载评论中…