feat: 初始化NewLife Studio项目,完成基础框架与数据管理模块
何炳宏 authored at 2026-05-26 12:09:09
1.63 KiB
NewLife.Studio
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;
        }
    }
}