Skip to content

Instantly share code, notes, and snippets.

@duongphuhiep
Created July 10, 2023 14:37
Show Gist options
  • Save duongphuhiep/e461ba8bbade964e0abc78eafb85fa53 to your computer and use it in GitHub Desktop.
Save duongphuhiep/e461ba8bbade964e0abc78eafb85fa53 to your computer and use it in GitHub Desktop.
AesEncryptionHelper
using System.Security.Cryptography;
using System.Text;
namespace Lemonway.TransactionService.Application
{
public static class AesEncryptionHelper
{
public static string Encrypt(string payload, string secret)
{
byte[] iv = new byte[16];
byte[] array;
byte[] key = new byte[32];
Array.Copy(Encoding.ASCII.GetBytes(secret), 0, key, 0, 32);
using (Aes aes = Aes.Create())
{
aes.Key = key;
aes.IV = iv;
ICryptoTransform encryptor = aes.CreateEncryptor();
using var memoryStream = new MemoryStream();
using var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write);
using (var streamWriter = new StreamWriter(cryptoStream))
{
streamWriter.Write(payload);
}
array = memoryStream.ToArray();
}
return Convert.ToBase64String(array);
}
public static string Decrypt(string encodedPayload, string secret)
{
using Aes aes = Aes.Create();
aes.Key = Encoding.ASCII.GetBytes(secret).AsSpan(0, 32).ToArray();
aes.IV = new byte[16];
ICryptoTransform cryptoTransform = aes.CreateDecryptor();
byte[] buffer = Convert.FromBase64String(encodedPayload);
using var memoryStream = new MemoryStream(buffer);
using var cryptoStream = new CryptoStream(memoryStream, cryptoTransform, CryptoStreamMode.Read);
using var streamReader = new StreamReader(cryptoStream);
return streamReader.ReadToEnd();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment