Skip to content

Instantly share code, notes, and snippets.

@jumoog
Last active April 20, 2024 21:39
Show Gist options
  • Save jumoog/44387fe0c125ca2b1a48431d0da3abe4 to your computer and use it in GitHub Desktop.
Save jumoog/44387fe0c125ca2b1a48431d0da3abe4 to your computer and use it in GitHub Desktop.
aes256Decrypt in C#
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
namespace ConsoleApp
{
internal class Program
{
static void Main(string[] args)
{
Console.WriteLine(Decrypt(new byte[] { 0x37, 0x21, 0xa5, 0xd1, 0xd2, 0x26, 0x78, 0x48, 0x89, 0xd6, 0xe3, 0x42, 0x33, 0x7c, 0x12, 0x9a }, "MYSUPERSECRECTKEYDONTLEAKIT!!!!!"));
Console.WriteLine(Encrypt("my secrect code", "MYSUPERSECRECTKEYDONTLEAKIT!!!!!"));
}
public static string Encrypt(string plainText, string keyString)
{
byte[] cipherData;
byte[] key = Encoding.UTF8.GetBytes(keyString);
// resize like WinCC OA
Array.Resize(ref key, 32);
Aes aes = Aes.Create();
aes.Mode = CipherMode.CBC;
aes.Padding = PaddingMode.Zeros;
aes.Key = key;
aes.IV = new byte[16];
ICryptoTransform cipher = aes.CreateEncryptor(aes.Key, aes.IV);
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, cipher, CryptoStreamMode.Write))
{
using (StreamWriter sw = new StreamWriter(cs))
{
sw.Write(plainText);
}
}
cipherData = ms.ToArray();
}
return Convert.ToHexString(cipherData);
}
public static string Decrypt(byte[] combinedData, string keyString)
{
string plainText;
byte[] key = Encoding.UTF8.GetBytes(keyString);
// resize like WinCC OA
Array.Resize(ref key, 32);
Aes aes = Aes.Create();
aes.Mode = CipherMode.CBC;
aes.Padding = PaddingMode.Zeros;
aes.Key = key;
aes.IV = new byte[16];
ICryptoTransform decipher = aes.CreateDecryptor(aes.Key, aes.IV);
using (MemoryStream ms = new MemoryStream(combinedData))
{
using (CryptoStream cs = new CryptoStream(ms, decipher, CryptoStreamMode.Read))
{
using (StreamReader sr = new StreamReader(cs))
{
plainText = sr.ReadToEnd();
}
}
return plainText;
}
}
}
}
main()
{
string password;
string enc = "3721A5D1D226784889D6E342337C129A";
aes256Decrypt((blob)enc, "MYSUPERSECRECTKEYDONTLEAKIT!!!!!", password);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment