mirror of
https://github.com/azaion/annotations.git
synced 2026-04-22 21:46:30 +00:00
6229ca8a03
zoom fix
59 lines
1.9 KiB
C#
59 lines
1.9 KiB
C#
using System.Security.Cryptography;
|
|
using System.Text;
|
|
using Newtonsoft.Json;
|
|
|
|
namespace Azaion.Common;
|
|
|
|
public class Security
|
|
{
|
|
private static string GenDefaultKey()
|
|
{
|
|
var date = DateTime.UtcNow;
|
|
return $"sAzaion_default_dfvkjhg_{date:yyyy}-{date:MM}_{date:dd}_{date:HH}_key";
|
|
}
|
|
|
|
public static string Encrypt<T>(T model, string? key = null) where T : class
|
|
{
|
|
var json = JsonConvert.SerializeObject(model);
|
|
var inputBytes = Encoding.UTF8.GetBytes(json);
|
|
|
|
var keyBytes = SHA256.HashData(Encoding.UTF8.GetBytes(key ?? GenDefaultKey()));
|
|
var iv = RandomNumberGenerator.GetBytes(16);
|
|
|
|
using var aes = Aes.Create();
|
|
aes.Key = keyBytes;
|
|
aes.IV = iv;
|
|
aes.Mode = CipherMode.CFB;
|
|
aes.Padding = PaddingMode.ISO10126;
|
|
|
|
using var encryptor = aes.CreateEncryptor();
|
|
var ciphertext = encryptor.TransformFinalBlock(inputBytes, 0, inputBytes.Length);
|
|
|
|
var result = new byte[iv.Length + ciphertext.Length];
|
|
iv.CopyTo(result, 0);
|
|
ciphertext.CopyTo(result, iv.Length);
|
|
|
|
return Convert.ToBase64String(result);
|
|
}
|
|
|
|
public static T Decrypt<T>(string encryptedData, string? key = null) where T : class
|
|
{
|
|
var ciphertextWithIv = Convert.FromBase64String(encryptedData);
|
|
var keyBytes = SHA256.HashData(Encoding.UTF8.GetBytes(key ?? GenDefaultKey()));
|
|
|
|
var iv = ciphertextWithIv[..16];
|
|
var ciphertext = ciphertextWithIv[16..];
|
|
|
|
using var aes = Aes.Create();
|
|
aes.Key = keyBytes;
|
|
aes.IV = iv;
|
|
aes.Mode = CipherMode.CFB;
|
|
aes.Padding = PaddingMode.ISO10126;
|
|
|
|
using var decryptor = aes.CreateDecryptor();
|
|
var plaintext = decryptor.TransformFinalBlock(ciphertext, 0, ciphertext.Length);
|
|
|
|
var json = Encoding.UTF8.GetString(plaintext);
|
|
return JsonConvert.DeserializeObject<T>(json)!;
|
|
}
|
|
} |