67 lines
2.4 KiB
C#

using Marco.Pms.Services.Service.ServiceInterfaces;
using System.Security.Cryptography;
using System.Text;
namespace Marco.Pms.Services.Service
{
public class AesEncryption : IAesEncryption
{
public (byte[] ciphertext, byte[] nonce, byte[] tag) Encrypt(string plaintext, byte[] key)
{
byte[] autoKey = new byte[32]; // 32 bytes = 256 bits
RandomNumberGenerator.Fill(autoKey);
var stringKey = Convert.ToBase64String(autoKey);
byte[] nonce = RandomNumberGenerator.GetBytes(12);
byte[] plaintextBytes = Encoding.UTF8.GetBytes(plaintext);
byte[] ciphertext = new byte[plaintextBytes.Length];
byte[] tag = new byte[16];
using var aes = new AesGcm(key, 16);
aes.Encrypt(nonce, plaintextBytes, ciphertext, tag);
return (ciphertext, nonce, tag);
}
public string Decrypt(byte[] ciphertext, byte[] nonce, byte[] tag, byte[] key)
{
byte[] plaintext = new byte[ciphertext.Length];
using var aes = new AesGcm(key, 16);
aes.Decrypt(nonce, ciphertext, tag, plaintext);
return Encoding.UTF8.GetString(plaintext);
}
public string EncryptResponse(string plainText)
{
var key = Convert.FromBase64String("h9J4kL2mN5pQ8rS1tV3wX6yZ0aB7cD9eF1gH3jK5mN6=");
if (string.IsNullOrEmpty(plainText)) return plainText;
var plainBytes = Encoding.UTF8.GetBytes(plainText);
// 1. Generate Nonce (12 bytes)
var nonce = new byte[12];
RandomNumberGenerator.Fill(nonce);
// 2. Prepare Buffers
var tag = new byte[16];
var ciphertext = new byte[plainBytes.Length];
// 3. Encrypt
using (var aesGcm = new AesGcm(key, 16))
{
aesGcm.Encrypt(nonce, plainBytes, ciphertext, tag);
}
// 4. Combine: [Nonce] + [Ciphertext] + [Tag]
var combined = new byte[nonce.Length + ciphertext.Length + tag.Length];
Buffer.BlockCopy(nonce, 0, combined, 0, nonce.Length);
Buffer.BlockCopy(ciphertext, 0, combined, nonce.Length, ciphertext.Length);
Buffer.BlockCopy(tag, 0, combined, nonce.Length + ciphertext.Length, tag.Length);
return Convert.ToBase64String(combined);
}
}
}