请写一个C#的加密函数
以下是一个简单的基于AES算法的加密函数示例:
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
public static class EncryptionHelper
{
private static readonly byte[] Salt = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };
public static string Encrypt(string plainText, string password)
{
byte[] plainBytes = Encoding.UTF8.GetBytes(plainText);
using (Aes aes = Aes.Create())
{
Rfc2898DeriveBytes keyDerivation = new Rfc2898DeriveBytes(password, Salt);
aes.Key = keyDerivation.GetBytes(aes.KeySize / 8);
aes.IV = keyDerivation.GetBytes(aes.BlockSize / 8);
using (MemoryStream memoryStream = new MemoryStream())
{
using (CryptoStream cryptoStream = new CryptoStream(memoryStream, aes.CreateEncryptor(), CryptoStreamMode.Write))
{
cryptoStream.Write(plainBytes, 0, plainBytes.Length);
cryptoStream.FlushFinalBlock();
}
byte[] encryptedBytes = memoryStream.ToArray();
return Convert.ToBase64String(encryptedBytes);
}
}
}
public static string Decrypt(string encryptedText, string password)
{
byte[] encryptedBytes = Convert.FromBase64String(encryptedText);
using (Aes aes = Aes.Create())
{
Rfc2898DeriveBytes keyDerivation = new Rfc2898DeriveBytes(password, Salt);
aes.Key = keyDerivation.GetBytes(aes.KeySize / 8);
aes.IV = keyDerivation.GetBytes(aes.BlockSize / 8);
using (MemoryStream memoryStream = new MemoryStream())
{
using (CryptoStream cryptoStream = new CryptoStream(memoryStream, aes.CreateDecryptor(), CryptoStreamMode.Write))
{
cryptoStream.Write(encryptedBytes, 0, encryptedBytes.Length);
cryptoStream.FlushFinalBlock();
}
byte[] decryptedBytes = memoryStream.ToArray();
return Encoding.UTF8.GetString(decryptedBytes);
}
}
}
}
使用示例:
string password = "myPassword123";
string plainText = "Hello, world!";
string encryptedText = EncryptionHelper.Encrypt(plainText, password);
string decryptedText = EncryptionHelper.Decrypt(encryptedText, password);
Console.WriteLine($"Encrypted Text: {encryptedText}");
Console.WriteLine($"Decrypted Text: {decryptedText}");
``
原文地址: https://www.cveoy.top/t/topic/fHzN 著作权归作者所有。请勿转载和采集!