如何使用C#代码实现利用字符串作为密钥加密字符串
要使用C#代码实现利用字符串作为密钥加密字符串,可以使用对称加密算法(如AES)和哈希函数(如SHA256)的组合。下面是一个示例代码:
using System;
using System.Security.Cryptography;
using System.Text;
public class Program
{
public static void Main()
{
string plaintext = "Hello, world!";
string keyString = "MySecretKey"; // 密钥字符串
// 将密钥字符串转换为字节数组
byte[] keyBytes = Encoding.UTF8.GetBytes(keyString);
// 使用哈希函数生成固定长度的密钥
byte[] key = new byte[32]; // 256位密钥
using (SHA256 sha256 = SHA256.Create())
{
key = sha256.ComputeHash(keyBytes);
}
// 使用对称加密算法加密字符串
using (Aes aes = Aes.Create())
{
aes.Key = key;
aes.GenerateIV(); // 自动生成初始化向量
// 创建加密器和解密器
ICryptoTransform encryptor = aes.CreateEncryptor();
ICryptoTransform decryptor = aes.CreateDecryptor();
// 加密字符串
byte[] encryptedBytes = EncryptStringToBytes(plaintext, encryptor);
// 解密字符串
string decryptedText = DecryptStringFromBytes(encryptedBytes, decryptor);
Console.WriteLine("Encrypted: " + Convert.ToBase64String(encryptedBytes));
Console.WriteLine("Decrypted: " + decryptedText);
}
}
private static byte[] EncryptStringToBytes(string plaintext, ICryptoTransform encryptor)
{
byte[] encryptedBytes;
// 将字符串转换为字节数组
byte[] plaintextBytes = Encoding.UTF8.GetBytes(plaintext);
// 创建内存流
using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
{
// 加密数据并写入内存流
cs.Write(plaintextBytes, 0, plaintextBytes.Length);
}
// 获取加密后的字节数组
encryptedBytes = ms.ToArray();
}
return encryptedBytes;
}
private static string DecryptStringFromBytes(byte[] encryptedBytes, ICryptoTransform decryptor)
{
string plaintext;
// 创建内存流
using (System.IO.MemoryStream ms = new System.IO.MemoryStream(encryptedBytes))
{
using (CryptoStream cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read))
{
// 创建字节数组缓冲区
byte[] decryptedBytes = new byte[encryptedBytes.Length];
// 从加密流中读取解密后的数据
int decryptedByteCount = cs.Read(decryptedBytes, 0, decryptedBytes.Length);
// 将解密后的字节数组转换为字符串
plaintext = Encoding.UTF8.GetString(decryptedBytes, 0, decryptedByteCount);
}
}
return plaintext;
}
}
在上面的代码中,首先将密钥字符串转换为字节数组,并使用SHA256哈希函数生成固定长度的密钥。然后,使用Aes对称加密算法创建加密器和解密器,并使用密钥进行初始化。接下来,使用加密器将字符串加密为字节数组,再使用解密器将字节数组解密为字符串。
请注意,此示例仅用于演示目的,实际应用中需要根据具体安全需求和加密算法选择适当的密钥生成和加密方式
原文地址: http://www.cveoy.top/t/topic/iCdK 著作权归作者所有。请勿转载和采集!