Skip to content

Instantly share code, notes, and snippets.

@kveber
Last active January 18, 2019 11:48
Show Gist options
  • Save kveber/d0373d0f76e3bf8e6de4fcd03d8dd5d6 to your computer and use it in GitHub Desktop.
Save kveber/d0373d0f76e3bf8e6de4fcd03d8dd5d6 to your computer and use it in GitHub Desktop.
AES/Rijndael Cryptography Simple Sample
using System;
using System.IO;
using System.Text;
using System.Security.Cryptography;
public class Program
{
public static void Main()
{
string key = "1234567812345678";
string originalValue = "{\"keys\":{\"id-origin\":null,\"nome\":\"Maria da Silva\",\"data-nascimento\":\"19620506\",\"nome-mae\":null,\"genero\":\"F\",\"estado-civil\":null,\"nacionalidade\":null,\"end-logradouro\":null,\"end-cidade\":\"S\u00E3o Paulo\",\"end-estado\":\"SP\",\"end-pais\":\"Brasil\",\"fone-celular\":\"11988888888\",\"fone-fixo\":null,\"email\":\"mariadasilva@dataopera.com\",\"doc-cpf\":\"11111111111\",\"doc-rg\":\"222222222\",\"doc-cns\":\"1111111111111\",\"doc-passaporte\":null,\"contatos\":null},\"class\":\"dto-v1\",\"tokenTtl\":\"3600\",\"kind\":\"0\",\"origin\":\"DTO-CLINICWEB-DEV\"}";
Console.WriteLine(" Original: " + originalValue);
Console.WriteLine();
string encriptedValue = Crypto.Encrypt(originalValue, key);
Console.WriteLine("Encripted: " + encriptedValue);
Console.WriteLine();
string decryptedValue = Crypto.Decrypt(encriptedValue, key);
Console.WriteLine("Decrypted: " + decryptedValue);
Console.ReadLine();
}
}
public static class Crypto
{
public static string Encrypt(string plainText, string key)
{
string cipherText;
var rijndael = new RijndaelManaged()
{
Key = Encoding.UTF8.GetBytes(key),
Mode = CipherMode.ECB,
BlockSize = 128,
};
ICryptoTransform encryptor = rijndael.CreateEncryptor(rijndael.Key, rijndael.IV);
using (var memoryStream = new MemoryStream())
{
using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
{
using (var streamWriter = new StreamWriter(cryptoStream))
{
streamWriter.Write(plainText);
streamWriter.Flush();
}
cipherText = Convert.ToBase64String(memoryStream.ToArray());
//cryptoStream.FlushFinalBlock();
}
}
return cipherText;
}
public static string Decrypt(string cipherText, string key)
{
string plainText;
byte[] cipherArray = Convert.FromBase64String(cipherText);
var rijndael = new RijndaelManaged()
{
Key = Encoding.UTF8.GetBytes(key),
Mode = CipherMode.ECB,
BlockSize = 128
};
ICryptoTransform decryptor = rijndael.CreateDecryptor(rijndael.Key, rijndael.IV);
using (var memoryStream = new MemoryStream(cipherArray))
{
using (var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read))
{
using (var streamReader = new StreamReader(cryptoStream))
{
plainText = streamReader.ReadToEnd();
}
}
}
return plainText;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment