Skip to content

Instantly share code, notes, and snippets.

@jhuamanchumo
Created October 14, 2021 19:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jhuamanchumo/4552ab3fc1b9e2c45edeaef3e5ce8cd6 to your computer and use it in GitHub Desktop.
Save jhuamanchumo/4552ab3fc1b9e2c45edeaef3e5ce8cd6 to your computer and use it in GitHub Desktop.
AES Encryption - C#
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
namespace CryptoUtil
{
class CryptoUtil
{
static String SECRET_KEY = "secretKey";
static String VECTOR_INIT = "vectorInit";
static void Main(string[] args)
{
String plain = "hola";
String encryted = Encrypt(plain);
String decrypted = Decrypt(encryted);
Console.WriteLine("plain: " + plain);
Console.WriteLine("encryted: " + encryted);
Console.WriteLine("decrypted: " + decrypted);
}
private static AesManaged CreateAes()
{
var aes = new AesManaged();
aes.Key = System.Text.Encoding.UTF8.GetBytes(SECRET_KEY); //UTF8-Encoding
aes.IV = System.Text.Encoding.UTF8.GetBytes(VECTOR_INIT);//UT8-Encoding
return aes;
}
static String Encrypt(String plainText)
{
using (AesManaged aes = CreateAes())
{
ICryptoTransform encryptor = aes.CreateEncryptor();
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter sw = new StreamWriter(cs))
sw.Write(plainText);
return Convert.ToBase64String(ms.ToArray());
}
}
}
}
static string Decrypt(String encryptedText)
{
using (var aes = CreateAes())
{
ICryptoTransform decryptor = aes.CreateDecryptor();
using (MemoryStream ms = new MemoryStream(Convert.FromBase64String(encryptedText)))
{
using (CryptoStream cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read))
{
using (StreamReader reader = new StreamReader(cs))
{
return reader.ReadToEnd();
}
}
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment