核心概念
1. 什么是加密?
- 加密:加密是一种将数据转换为一种不可读形式的方法,只有持有相应密钥的人才能解密并读取数据。
- 目的:确保数据的机密性和安全性,特别是在传输过程中过防止未授权访问。
2. 加密类型
对称加密:
- 使用相同的密钥进行加密和解密。
- 常见算法:AES、DES。
- 优点:速度快,适合大数据量加密。
非对称加密:
- 使用公钥加密和私钥解密。
- 常见算法:RSA。
- 优点:安全性高,适合密钥交换和数字签名。
3. 散列函数
- 散列函数:又称为哈希函数,将任意长度的数据转换为固定长度的字符串。
- 特点:不可逆,常用于验证数据完整性。
- 常见算法:MD5、SHA-256。
实际使用
对称加密示例:AES
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
public class AesEncryptionExample
{
public static void Main()
{
string original = "Sensitive data that needs encryption";
// 创建AES加密服务实例
using (Aes aesAlg = Aes.Create())
{
// 加密字符串到字节数组
byte[] encrypted = EncryptStringToBytes_Aes(original, aesAlg.Key, aesAlg.IV);
// 解密字节数组回字符串
string decrypted = DecryptStringFromBytes_Aes(encrypted, aesAlg.Key, aesAlg.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(nameof(plainText));
if (Key == null || Key.Length <= 0)
throw new ArgumentNullException(nameof(Key));
if (IV == null || IV.Length <= 0)
throw new ArgumentNullException(nameof(IV));
byte[] encrypted;
// 使用AES算法
using (Aes aesAlg = Aes.Create())
{
aesAlg.Key = Key; // 设置加密密钥
aesAlg.IV = IV; // 设置初始化向量
// 创建一个加密器来执行流转换
ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.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(nameof(cipherText));
if (Key == null || Key.Length <= 0)
throw new ArgumentNullException(nameof(Key));
if (IV == null || IV.Length <= 0)
throw new ArgumentNullException(nameof(IV));
string plaintext = null;
// 使用AES算法
using (Aes aesAlg = Aes.Create())
{
aesAlg.Key = Key; // 解密密钥
aesAlg.IV = IV; // 初始化向量
// 创建解密器
ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.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; // 返回解密后的字符串
}
}
非对称加密示例:RSA
using System;
using System.Security.Cryptography;
using System.Text;
public class RsaEncryptionExample
{
public static void Main()
{
// 创建RSA实例
using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
{
// 导出公钥和私钥
string publicKey = rsa.ToXmlString(false); // 公钥,不包含私钥
string privateKey = rsa.ToXmlString(true); // 私钥,包含全部信息
string original = "Data for RSA encryption";
// 加密数据
byte[] encrypted = Encrypt(original, publicKey);
// 解密数据
string decrypted = Decrypt(encrypted, privateKey);
Console.WriteLine($"Original: {original}");
Console.WriteLine($"Decrypted: {decrypted}");
}
}
public static byte[] Encrypt(string data, string publicKey)
{
using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
{
rsa.FromXmlString(publicKey); // 加载公钥
var dataBytes = Encoding.UTF8.GetBytes(data); // 转换数据为字节数组
return rsa.Encrypt(dataBytes, false); // 执行加密
}
}
public static string Decrypt(byte[] data, string privateKey)
{
using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
{
rsa.FromXmlString(privateKey); // 加载私钥
var decryptedBytes = rsa.Decrypt(data, false); // 执行解密
return Encoding.UTF8.GetString(decryptedBytes); // 转换回字符串
}
}
}
SHA-256 散列示例
using System;
using System.Security.Cryptography;
using System.Text;
public class HashingExample
{
public static void Main()
{
string data = "Data to hash";
// 计算SHA-256散列值
string hash = ComputeSha256Hash(data);
Console.WriteLine($"Data: {data}");
Console.WriteLine($"Hash: {hash}");
}
public static string ComputeSha256Hash(string rawData)
{
using (SHA256 sha256Hash = SHA256.Create())
{
// 将输入字符串转换为字节数组并计算其哈希值
byte[] bytes = sha256Hash.ComputeHash(Encoding.UTF8.GetBytes(rawData));
// 将字节数组转变为十六进制字符串
StringBuilder builder = new StringBuilder();
for (int i = 0; i < bytes.Length; i++)
{
builder.Append(bytes[i].ToString("x2")); // 格式化为两位十六进制
}
return builder.ToString(); // 返回散列值
}
}
}
- SHA-256散列值,通常用来验证两个文件是否相同。
这些示例展示了如何在C#中实现常见的安全和加密任务。如果有其他问题或需要进一步讲解,请随时告诉我!