软测单独项目
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

74 lines
2.5 KiB

using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
namespace FangYar.Common
{
/// <summary>
/// Aes加密帮助类
/// </summary>
public class AesHelper
{
//生成字节数组
private static readonly byte[] salt = Encoding.Unicode.GetBytes("7BANANAS");
//迭代次数 应最少设置1000
private static readonly int iterations = 2000;
/// <summary>
/// 加密
/// </summary>
/// <param name="plainText">加密文本</param>
/// <param name="password">密钥</param>
/// <returns>返回加密后的字节字符串</returns>
public static string Encrypt(string plainText, string password = "kndhurlp")
{
byte[] encryptedBytes;
byte[] plainBytes = Encoding.Unicode.GetBytes(plainText);
var aes = Aes.Create();
var pbkdf2 = new Rfc2898DeriveBytes(password, salt, iterations); //使用密码 字节数组 和 迭代次数 生成密钥
aes.Key = pbkdf2.GetBytes(32);
aes.IV = pbkdf2.GetBytes(16);
using (var ms = new MemoryStream())
{
using (var cs = new CryptoStream(ms, aes.CreateEncryptor(), CryptoStreamMode.Write))
{
cs.Write(plainBytes, 0, plainBytes.Length);
}
encryptedBytes = ms.ToArray();
}
return Convert.ToBase64String(encryptedBytes);
}
/// <summary>
/// 解密
/// </summary>
/// <param name="crytoText">字节文本</param>
/// <param name="password">密钥:默认:kndhurlp</param>
/// <returns>将字节文本解密为字符串返回</returns>
public static string Decrypt(string crytoText, string password = "kndhurlp")
{
byte[] plainBytes;
byte[] cryptoBytes = Convert.FromBase64String(crytoText);
var aes = Aes.Create();
var pbkdf2 = new Rfc2898DeriveBytes(password, salt, iterations);
aes.Key = pbkdf2.GetBytes(32);
aes.IV = pbkdf2.GetBytes(16);
using (var ms = new MemoryStream())
{
using (var cs = new CryptoStream(ms, aes.CreateDecryptor(), CryptoStreamMode.Write))
{
cs.Write(cryptoBytes, 0, cryptoBytes.Length);
}
plainBytes = ms.ToArray();
}
return Encoding.Unicode.GetString(plainBytes);
}
}
}