您好,登录后才能下订单哦!
在现代计算机科学中,数据安全是一个至关重要的话题。随着互联网的普及和信息技术的发展,数据加密技术成为了保护信息安全的重要手段之一。AES(Advanced Encryption Standard)算法作为一种广泛使用的对称加密算法,因其高效性和安全性而被广泛应用于各种场景中。本文将详细介绍如何在C#中实现AES算法加密,并通过多个示例展示其应用。
AES算法是由美国国家标准与技术研究院(NIST)于2001年发布的一种对称加密算法。它取代了之前广泛使用的DES(Data Encryption Standard)算法,成为新的加密标准。AES算法的设计目标是提供更高的安全性和更快的加密速度。
AES算法是一种分组加密算法,它将明文数据分成固定长度的块(128位),然后通过多轮加密操作将其转换为密文。AES算法的加密过程包括四个主要步骤:字节替换(SubBytes)、行移位(ShiftRows)、列混淆(MixColumns)和轮密钥加(AddRoundKey)。这些步骤在多轮加密中重复进行,最终生成密文。
AES算法支持三种密钥长度:128位、192位和256位。密钥长度越长,加密的安全性越高,但加密速度也会相应降低。在实际应用中,通常根据安全需求和性能要求选择合适的密钥长度。
在C#中,加密操作主要通过System.Security.Cryptography
命名空间中的类来实现。该命名空间提供了多种加密算法,包括对称加密算法(如AES、DES)、非对称加密算法(如RSA)和哈希算法(如SHA)。
在System.Security.Cryptography
命名空间中,常用的加密类包括:
Aes
:用于实现AES加密算法。Rijndael
:AES算法的前身,现已不推荐使用。DES
:用于实现DES加密算法。RSA
:用于实现RSA非对称加密算法。SHA256
:用于实现SHA-256哈希算法。在AES加密中,密钥和初始化向量(IV)是加密和解密的关键。密钥用于加密数据,而IV用于确保相同的明文在不同加密操作中生成不同的密文。密钥和IV通常通过随机数生成器生成。
在C#中,可以使用Aes
类创建AES加密器。通过设置Key
和IV
属性,可以指定加密所需的密钥和初始化向量。然后,使用CreateEncryptor
方法创建加密器对象。
加密数据的过程通常包括以下步骤:
解密数据的过程与加密过程类似,但使用解密器对象。具体步骤包括:
using System;
using System.Security.Cryptography;
class Program
{
static void Main()
{
using (Aes aes = Aes.Create())
{
aes.GenerateKey();
aes.GenerateIV();
Console.WriteLine("Key: " + Convert.ToBase64String(aes.Key));
Console.WriteLine("IV: " + Convert.ToBase64String(aes.IV));
}
}
}
using System;
using System.Security.Cryptography;
using System.Text;
class Program
{
static void Main()
{
string original = "Hello, World!";
using (Aes aes = Aes.Create())
{
aes.GenerateKey();
aes.GenerateIV();
byte[] encrypted = EncryptStringToBytes_Aes(original, aes.Key, aes.IV);
Console.WriteLine("Encrypted: " + Convert.ToBase64String(encrypted));
}
}
static byte[] EncryptStringToBytes_Aes(string plainText, byte[] Key, byte[] IV)
{
if (plainText == null || plainText.Length <= 0)
throw new ArgumentNullException("plainText");
if (Key == null || Key.Length <= 0)
throw new ArgumentNullException("Key");
if (IV == null || IV.Length <= 0)
throw new ArgumentNullException("IV");
byte[] encrypted;
using (Aes aes = Aes.Create())
{
aes.Key = Key;
aes.IV = IV;
ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV);
using (MemoryStream msEncrypt = new MemoryStream())
{
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
{
swEncrypt.Write(plainText);
}
encrypted = msEncrypt.ToArray();
}
}
}
return encrypted;
}
}
using System;
using System.Security.Cryptography;
using System.Text;
class Program
{
static void Main()
{
string original = "Hello, World!";
using (Aes aes = Aes.Create())
{
aes.GenerateKey();
aes.GenerateIV();
byte[] encrypted = EncryptStringToBytes_Aes(original, aes.Key, aes.IV);
string decrypted = DecryptStringFromBytes_Aes(encrypted, aes.Key, aes.IV);
Console.WriteLine("Original: " + original);
Console.WriteLine("Decrypted: " + decrypted);
}
}
static byte[] EncryptStringToBytes_Aes(string plainText, byte[] Key, byte[] IV)
{
if (plainText == null || plainText.Length <= 0)
throw new ArgumentNullException("plainText");
if (Key == null || Key.Length <= 0)
throw new ArgumentNullException("Key");
if (IV == null || IV.Length <= 0)
throw new ArgumentNullException("IV");
byte[] encrypted;
using (Aes aes = Aes.Create())
{
aes.Key = Key;
aes.IV = IV;
ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV);
using (MemoryStream msEncrypt = new MemoryStream())
{
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
{
swEncrypt.Write(plainText);
}
encrypted = msEncrypt.ToArray();
}
}
}
return encrypted;
}
static string DecryptStringFromBytes_Aes(byte[] cipherText, byte[] Key, byte[] IV)
{
if (cipherText == null || cipherText.Length <= 0)
throw new ArgumentNullException("cipherText");
if (Key == null || Key.Length <= 0)
throw new ArgumentNullException("Key");
if (IV == null || IV.Length <= 0)
throw new ArgumentNullException("IV");
string plaintext = null;
using (Aes aes = Aes.Create())
{
aes.Key = Key;
aes.IV = IV;
ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV);
using (MemoryStream msDecrypt = new MemoryStream(cipherText))
{
using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
{
using (StreamReader srDecrypt = new StreamReader(csDecrypt))
{
plaintext = srDecrypt.ReadToEnd();
}
}
}
}
return plaintext;
}
}
在实际应用中,AES加密不仅可以用于加密字符串,还可以用于加密文件。以下是一个使用AES加密文件的示例:
using System;
using System.IO;
using System.Security.Cryptography;
class Program
{
static void Main()
{
string inputFile = "input.txt";
string outputFile = "output.enc";
string decryptedFile = "decrypted.txt";
using (Aes aes = Aes.Create())
{
aes.GenerateKey();
aes.GenerateIV();
EncryptFile(inputFile, outputFile, aes.Key, aes.IV);
DecryptFile(outputFile, decryptedFile, aes.Key, aes.IV);
}
}
static void EncryptFile(string inputFile, string outputFile, byte[] Key, byte[] IV)
{
using (FileStream fsInput = new FileStream(inputFile, FileMode.Open, FileAccess.Read))
using (FileStream fsOutput = new FileStream(outputFile, FileMode.Create, FileAccess.Write))
using (Aes aes = Aes.Create())
{
aes.Key = Key;
aes.IV = IV;
ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV);
using (CryptoStream csEncrypt = new CryptoStream(fsOutput, encryptor, CryptoStreamMode.Write))
{
fsInput.CopyTo(csEncrypt);
}
}
}
static void DecryptFile(string inputFile, string outputFile, byte[] Key, byte[] IV)
{
using (FileStream fsInput = new FileStream(inputFile, FileMode.Open, FileAccess.Read))
using (FileStream fsOutput = new FileStream(outputFile, FileMode.Create, FileAccess.Write))
using (Aes aes = Aes.Create())
{
aes.Key = Key;
aes.IV = IV;
ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV);
using (CryptoStream csDecrypt = new CryptoStream(fsInput, decryptor, CryptoStreamMode.Read))
{
csDecrypt.CopyTo(fsOutput);
}
}
}
}
在数据库应用中,敏感数据(如用户密码、信用卡信息)通常需要加密存储。以下是一个使用AES加密数据库字段的示例:
using System;
using System.Data.SqlClient;
using System.Security.Cryptography;
using System.Text;
class Program
{
static void Main()
{
string connectionString = "YourConnectionString";
string original = "SensitiveData";
using (Aes aes = Aes.Create())
{
aes.GenerateKey();
aes.GenerateIV();
byte[] encrypted = EncryptStringToBytes_Aes(original, aes.Key, aes.IV);
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
string query = "INSERT INTO SensitiveDataTable (EncryptedData) VALUES (@EncryptedData)";
using (SqlCommand command = new SqlCommand(query, connection))
{
command.Parameters.AddWithValue("@EncryptedData", encrypted);
command.ExecuteNonQuery();
}
}
}
}
static byte[] EncryptStringToBytes_Aes(string plainText, byte[] Key, byte[] IV)
{
if (plainText == null || plainText.Length <= 0)
throw new ArgumentNullException("plainText");
if (Key == null || Key.Length <= 0)
throw new ArgumentNullException("Key");
if (IV == null || IV.Length <= 0)
throw new ArgumentNullException("IV");
byte[] encrypted;
using (Aes aes = Aes.Create())
{
aes.Key = Key;
aes.IV = IV;
ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV);
using (MemoryStream msEncrypt = new MemoryStream())
{
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
{
swEncrypt.Write(plainText);
}
encrypted = msEncrypt.ToArray();
}
}
}
return encrypted;
}
}
在网络通信中,数据的安全性至关重要。以下是一个使用AES加密网络通信的示例:
using System;
using System.Net.Sockets;
using System.Security.Cryptography;
using System.Text;
class Program
{
static void Main()
{
string server = "127.0.0.1";
int port = 12345;
using (Aes aes = Aes.Create())
{
aes.GenerateKey();
aes.GenerateIV();
using (TcpClient client = new TcpClient(server, port))
using (NetworkStream stream = client.GetStream())
{
string message = "Hello, Server!";
byte[] encrypted = EncryptStringToBytes_Aes(message, aes.Key, aes.IV);
stream.Write(encrypted, 0, encrypted.Length);
byte[] buffer = new byte[1024];
int bytesRead = stream.Read(buffer, 0, buffer.Length);
byte[] decrypted = DecryptBytesFromBytes_Aes(buffer, aes.Key, aes.IV);
Console.WriteLine("Received: " + Encoding.UTF8.GetString(decrypted));
}
}
}
static byte[] EncryptStringToBytes_Aes(string plainText, byte[] Key, byte[] IV)
{
if (plainText == null || plainText.Length <= 0)
throw new ArgumentNullException("plainText");
if (Key == null || Key.Length <= 0)
throw new ArgumentNullException("Key");
if (IV == null || IV.Length <= 0)
throw new ArgumentNullException("IV");
byte[] encrypted;
using (Aes aes = Aes.Create())
{
aes.Key = Key;
aes.IV = IV;
ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV);
using (MemoryStream msEncrypt = new MemoryStream())
{
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
{
swEncrypt.Write(plainText);
}
encrypted = msEncrypt.ToArray();
}
}
}
return encrypted;
}
static byte[] DecryptBytesFromBytes_Aes(byte[] cipherText, byte[] Key, byte[] IV)
{
if (cipherText == null || cipherText.Length <= 0)
throw new ArgumentNullException("cipherText");
if (Key == null || Key.Length <= 0)
throw new ArgumentNullException("Key");
if (IV == null || IV.Length <= 0)
throw new ArgumentNullException("IV");
byte[] decrypted;
using (Aes aes = Aes.Create())
{
aes.Key = Key;
aes.IV = IV;
ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV);
using (MemoryStream msDecrypt = new MemoryStream(cipherText))
{
using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
{
using (MemoryStream msOutput = new MemoryStream())
{
csDecrypt.CopyTo(msOutput);
decrypted = msOutput.ToArray();
}
}
}
}
return decrypted;
}
}
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。