在CSharp中写一个使用加密密钥的加密解密示例
时间: 2023-01-11 12:55:36 浏览: 81
在 C# 中,您可以使用 .NET Framework 中的 System.Security.Cryptography 命名空间来加密和解密数据。下面是一个示例,它使用加密密钥加密和解密字符串:
```
using System;
using System.Text;
using System.Security.Cryptography;
namespace ConsoleApp
{
class Program
{
static void Main(string[] args)
{
// 需要加密的字符串
string text = "Hello, world!";
// 加密密钥
string key = "myKey123456";
// 加密字符串
string encryptedText = Encrypt(text, key);
Console.WriteLine($"Encrypted text: {encryptedText}");
// 解密字符串
string decryptedText = Decrypt(encryptedText, key);
Console.WriteLine($"Decrypted text: {decryptedText}");
}
static string Encrypt(string text, string key)
{
// 将密钥转换为字节数组
byte[] keyBytes = Encoding.UTF8.GetBytes(key);
// 使用密钥和初始化向量创建 Rijndael 加密器
using (var aes = Aes.Create())
{
aes.Key = keyBytes;
aes.IV = new byte[aes.BlockSize / 8];
// 创建加密器
ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV);
// 将需要加密的字符串转换为字节数组
byte[] textBytes = Encoding.UTF8.GetBytes(text);
// 使用加密器加密字节数组
byte[] encryptedBytes = encryptor.TransformFinalBlock(textBytes, 0, textBytes.Length);
// 将加密后的字节数组转换为字符串并返回
return Convert.ToBase64String(encryptedBytes);
}
}
static string Decrypt(string encryptedText, string key)
{
// 将密钥转换为字节数组
byte[] keyBytes = Encoding.UTF8.GetBytes(key);
// 将加密后的字符串