Skip to content

Instantly share code, notes, and snippets.

@doncadavona
Last active July 1, 2024 14:21
Show Gist options
  • Save doncadavona/fd493b6ced456371da8879c22bb1c263 to your computer and use it in GitHub Desktop.
Save doncadavona/fd493b6ced456371da8879c22bb1c263 to your computer and use it in GitHub Desktop.
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
Copy link

breekoy commented Jun 22, 2018

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

@RaulOrnelasGomez
Copy link

<3

@Tommixoft
Copy link

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.

@whyn0thax
Copy link

@Tommixoft u can secure your code and make the key hidden, also u can make the key get called from a like website. Even in .net its realy easy to use encryption. Also C++ C and other Languages are decompilable and the key can easaly e found.
With Microsofts tools like IDataProtector u cant secure anything too if a "hacker" gets the source got, he can just call and print the tool by himself.
Regards

@cteiosanu
Copy link

cteiosanu commented May 18, 2022

@doncadavona
I think line 51 and 89 should be Convert.FromBase64String(key) otherwise I don't see how/why one would store bytes[] as string without converting them to Base64.

More specificially using also Aes to generate a key :

Aes aes = Aes.Create();
aes.GenerateIV();
aes.GenerateKey();

var key = Convert.ToBase64String(aes.Key);

@pankiwi
Copy link

pankiwi commented Jun 9, 2024

you save me

thanks :}

@KyoRion
Copy link

KyoRion commented Jun 21, 2024

Follow by this code in c# how I can decrypt it in laravel application?
I got no idea for this did you have example?
I using phpseclib on laravel but alway get "Decryption error in file"
My code:
`public function decryptData(Request $request)
{
$encryptedKey = base64_decode($request->input('encrypted_key'));
$iv = base64_decode($request->input('iv'));
$encryptedData = base64_decode($request->input('data'));

    $privateKey = file_get_contents(public_path('key/private_key.pem'));
    $rsa = PublicKeyLoader::load($privateKey);
    $aesKey = $rsa->decrypt($encryptedKey);

    $aes = new AES('cbc');
    $aes->setKey($aesKey);
    $aes->setIV($iv);

    $decryptedData = $aes->decrypt($encryptedData);

    return response()->json(['data' => json_decode($decryptedData)]);
}`

@pankiwi
Copy link

pankiwi commented Jul 1, 2024

Rewrited on NetCore 8

	internal class Aes256CbcEncrypter
	{
private static readonly Encoding encoding = Encoding.UTF8;

public static string Encrypt(string plainText, string key)
{
	try
	{
		Aes aes = Aes.Create();
		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
	},
  };

		return Convert.ToBase64String(encoding.GetBytes(JsonSerializer.Serialize(keyValues)));
	}
	catch (Exception e)
	{
		throw new Exception("Error encrypting: " + e.Message);
	}
}

public static string Decrypt(string plainText, string key)
{
	try
	{
		Aes aes = Aes.Create();
		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
		var payload = JsonSerializer.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));
	}
}
	}

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