using System.Security.Cryptography;
using System.Text;
namespace NewLife.Studio.Store;
/// <summary>敏感信息加密保护(AES)</summary>
public class SecretProtection
{
private readonly byte[] _key;
private readonly byte[] _iv;
public SecretProtection()
{
// 使用机器相关的固定熵生成密钥
var entropy = Encoding.UTF8.GetBytes(
Environment.MachineName + Environment.UserName + "NewLife.Studio");
_key = SHA256.HashData(entropy);
_iv = MD5.HashData(entropy);
}
public string Protect(string plain)
{
if (string.IsNullOrEmpty(plain))
return "";
using var aes = Aes.Create();
aes.Key = _key;
aes.IV = _iv;
using var encryptor = aes.CreateEncryptor();
var plainBytes = Encoding.UTF8.GetBytes(plain);
var cipherBytes = encryptor.TransformFinalBlock(plainBytes, 0, plainBytes.Length);
return Convert.ToBase64String(cipherBytes);
}
public string Unprotect(string cipher)
{
if (string.IsNullOrEmpty(cipher))
return "";
try
{
using var aes = Aes.Create();
aes.Key = _key;
aes.IV = _iv;
using var decryptor = aes.CreateDecryptor();
var cipherBytes = Convert.FromBase64String(cipher);
var plainBytes = decryptor.TransformFinalBlock(cipherBytes, 0, cipherBytes.Length);
return Encoding.UTF8.GetString(plainBytes);
}
catch
{
// 解密失败返回原文(可能是旧格式未加密的数据)
return cipher;
}
}
}
|