42 lines
1.5 KiB
C#
42 lines
1.5 KiB
C#
namespace KssSmaPlaCoreLib.Crypto;
|
|
using System.Security.Cryptography;
|
|
using System.Text;
|
|
|
|
public class SecureConfigServiceUxer(string masterKey)
|
|
{
|
|
private readonly byte[] _key = SHA256.HashData(Encoding.UTF8.GetBytes(masterKey));
|
|
|
|
public string Encrypt(string plainText)
|
|
{
|
|
var plainBytes = Encoding.UTF8.GetBytes(plainText);
|
|
var nonce = RandomNumberGenerator.GetBytes(AesGcm.NonceByteSizes.MaxSize);
|
|
var tag = new byte[AesGcm.TagByteSizes.MaxSize];
|
|
var cipherText = new byte[plainBytes.Length];
|
|
|
|
using var aes = new AesGcm(_key, tag.Length);
|
|
aes.Encrypt(nonce, plainBytes, cipherText, tag);
|
|
|
|
// [Nonce(12)] + [Tag(16)] + [Cipher]
|
|
var result = new byte[nonce.Length + tag.Length + cipherText.Length];
|
|
Buffer.BlockCopy(nonce, 0, result, 0, nonce.Length);
|
|
Buffer.BlockCopy(tag, 0, result, nonce.Length, tag.Length);
|
|
Buffer.BlockCopy(cipherText, 0, result, nonce.Length + tag.Length, cipherText.Length);
|
|
|
|
return Convert.ToBase64String(result);
|
|
}
|
|
|
|
public string Decrypt(string base64Text)
|
|
{
|
|
var data = Convert.FromBase64String(base64Text);
|
|
var nonce = data[..12];
|
|
var tag = data[12..28];
|
|
var cipherText = data[28..];
|
|
var plainBytes = new byte[cipherText.Length];
|
|
|
|
using var aes = new AesGcm(_key, tag.Length);
|
|
aes.Decrypt(nonce, cipherText, tag, plainBytes);
|
|
|
|
return Encoding.UTF8.GetString(plainBytes);
|
|
}
|
|
}
|