Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A sample C# class to encrypt and decrypt strings using the cipher AES-256-CBC used in Laravel.
using System;
using System.Text;
using System.Security.Cryptography;
using System.Web.Script.Serialization;
using System.Collections.Generic;
namespace Aes256CbcEncrypterApp
{
class MainClass
{
public static void Main(string[] args)
{
Console.WriteLine("Hello, world!");
// The sample encryption key. Must be 32 characters.
string Key = "8UHjPgXZzXCGkhxV2QCnooyJexUzvJrO";
// The sample text to encrypt and decrypt.
string Text = "Here is a text to encrypt!";
// Encrypt and decrypt the sample text via the Aes256CbcEncrypter class.
string Encrypted = Aes256CbcEncrypter.Encrypt(Text, Key);
string Decrypted = Aes256CbcEncrypter.Decrypt(Encrypted, Key);
// Show the encrypted and decrypted data and the key used.
Console.WriteLine("Original: {0}", Text);
Console.WriteLine("Key: {0}", Key);
Console.WriteLine("Encrypted: {0}", Encrypted);
Console.WriteLine("Decrypted: {0}", Decrypted);
}
}
/**
* A class to encrypt and decrypt strings using
* the cipher AES-256-CBC used in Laravel.
*/
class Aes256CbcEncrypter
{
private static readonly Encoding encoding = Encoding.UTF8;
public static string Encrypt(string plainText, string key)
{
try
{
RijndaelManaged aes = new RijndaelManaged();
aes.KeySize = 256;
aes.BlockSize = 128;
aes.Padding = PaddingMode.PKCS7;
aes.Mode = CipherMode.CBC;
aes.Key = encoding.GetBytes(key);
aes.GenerateIV();
ICryptoTransform AESEncrypt = aes.CreateEncryptor(aes.Key, aes.IV);
byte[] buffer = encoding.GetBytes(plainText);
string encryptedText = Convert.ToBase64String(AESEncrypt.TransformFinalBlock(buffer, 0, buffer.Length));
String mac = "";
mac = BitConverter.ToString(HmacSHA256(Convert.ToBase64String(aes.IV) + encryptedText, key)).Replace("-", "").ToLower();
var keyValues = new Dictionary<string, object>
{
{ "iv", Convert.ToBase64String(aes.IV) },
{ "value", encryptedText },
{ "mac", mac },
};
JavaScriptSerializer serializer = new JavaScriptSerializer();
return Convert.ToBase64String(encoding.GetBytes(serializer.Serialize(keyValues)));
}
catch (Exception e)
{
throw new Exception("Error encrypting: " + e.Message);
}
}
public static string Decrypt(string plainText, string key)
{
try
{
RijndaelManaged aes = new RijndaelManaged();
aes.KeySize = 256;
aes.BlockSize = 128;
aes.Padding = PaddingMode.PKCS7;
aes.Mode = CipherMode.CBC;
aes.Key = encoding.GetBytes(key);
// Base 64 decode
byte[] base64Decoded = Convert.FromBase64String(plainText);
string base64DecodedStr = encoding.GetString(base64Decoded);
// JSON Decode base64Str
JavaScriptSerializer ser = new JavaScriptSerializer();
var payload = ser.Deserialize<Dictionary<string, string>>(base64DecodedStr);
aes.IV = Convert.FromBase64String(payload["iv"]);
ICryptoTransform AESDecrypt = aes.CreateDecryptor(aes.Key, aes.IV);
byte[] buffer = Convert.FromBase64String(payload["value"]);
return encoding.GetString(AESDecrypt.TransformFinalBlock(buffer, 0, buffer.Length));
}
catch (Exception e)
{
throw new Exception("Error decrypting: " + e.Message);
}
}
static byte[] HmacSHA256(String data, String key)
{
using (HMACSHA256 hmac = new HMACSHA256(encoding.GetBytes(key)))
{
return hmac.ComputeHash(encoding.GetBytes(data));
}
}
}
}
@breekoy

This comment has been minimized.

Copy link

@breekoy breekoy commented Jun 22, 2018

This is perfect! You're a life-saver! Thanks man. :)

@RaulOrnelasGomez

This comment has been minimized.

Copy link

@RaulOrnelasGomez RaulOrnelasGomez commented Jun 29, 2021

<3

@Tommixoft

This comment has been minimized.

Copy link

@Tommixoft Tommixoft commented Sep 22, 2021

encryption in .net is useless anyone can decompile code and get key., This option is INSECURE and there is other, more secure ways to encrypt strings via Microsoft provided tools like IDataProtector.
Even if you do not store key in app, by decompiling code "hacker" can see from where or how the key is obtained and get it too.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment