ChatRAG/Services/Crypt/CryptUtil.cs
2025-06-09 23:06:37 -03:00

67 lines
2.3 KiB
C#

using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
namespace ChatApi.Services.Crypt
{
public class CryptUtil
{
private readonly IConfigurationManager _configuration;
public CryptUtil(IConfigurationManager configuration)
{
_configuration = configuration;
}
public string Encrypt(string text)
{
string key = _configuration.GetSection("DataKey").Value;
using (Aes aes = Aes.Create())
{
aes.Key = Encoding.UTF8.GetBytes(key.PadRight(32).Substring(0, 32));
aes.GenerateIV(); // Cria um vetor de inicialização aleatório
byte[] iv = aes.IV;
using (var encryptor = aes.CreateEncryptor(aes.Key, iv))
using (var ms = new MemoryStream())
{
// Primeiro, escreva o IV para o fluxo (será necessário para descriptografia)
ms.Write(iv, 0, iv.Length);
using (var cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
using (var writer = new StreamWriter(cs))
{
writer.Write(text);
}
return Convert.ToBase64String(ms.ToArray());
}
}
}
public string Descrypt(string text)
{
string key = _configuration.GetSection("DataKey").Value;
byte[] bytes = Convert.FromBase64String(text);
using (Aes aes = Aes.Create())
{
aes.Key = Encoding.UTF8.GetBytes(key.PadRight(32).Substring(0, 32));
// Extrair o IV do início dos dados criptografados
byte[] iv = new byte[aes.BlockSize / 8];
Array.Copy(bytes, 0, iv, 0, iv.Length);
aes.IV = iv;
using (var decryptor = aes.CreateDecryptor(aes.Key, aes.IV))
using (var ms = new MemoryStream(bytes, iv.Length, bytes.Length - iv.Length))
using (var cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read))
using (var reader = new StreamReader(cs))
{
return reader.ReadToEnd();
}
}
}
}
}