using System.Security.Cryptography;
public static void Main()
String data = "This is a data which I would like to encrypt with AES128 CBC and should ok and fast.. Perhaps..";
String password = "123456";
String iv = "just random. #@$#@R ERTEWGREGEWg";
byte[] dataBytes = Encoding.ASCII.GetBytes(data);
byte[] passwordBytes = MD5_password(password);
byte[] ivBytes = MD5_password(iv);
Console.WriteLine("Data: {0}", byte_array_to_hex(dataBytes));
Console.WriteLine("Key: {0}", byte_array_to_hex(passwordBytes));
Console.WriteLine("IV: {0}", byte_array_to_hex(ivBytes));
Console.WriteLine(byte_array_to_hex(AES_encrypt_cbc(dataBytes, passwordBytes, ivBytes)));
public static string byte_array_to_hex(byte[] bytes)
StringBuilder hex = new StringBuilder(bytes.Length * 2);
foreach (byte b in bytes)
hex.AppendFormat("{0:x2}", b);
private static byte[] MD5_password(String password)
using (MD5 md5 = MD5.Create())
return md5.ComputeHash(Encoding.ASCII.GetBytes(password));
private static byte[] AES_encrypt_cbc(byte[] plaintext, byte[] key, byte[] iv)
int reminder = plaintext.Length % 16;
int padding = (reminder != 0 ? 16 - reminder : 16);
byte[] ciphertext = new byte[plaintext.Length + padding];
for (; i < plaintext.Length - reminder; i += 16)
XOR_byte_block(iv, 0, plaintext, i, ciphertext, i);
AES_encrypt_block(ciphertext, i, key, iv, 0);
Array.Copy(iv, 0, ciphertext, i, 16);
Array.Copy(plaintext, i, ciphertext, i, reminder);
for (int p = plaintext.Length; p < ciphertext.Length; ++p)
ciphertext[p] = (byte) padding;
XOR_byte_block(iv, 0, ciphertext, i, ciphertext, i);
AES_encrypt_block(ciphertext, i, key, iv, 0);
Array.Copy(iv, 0, ciphertext, i, 16);
private static void XOR_byte_block(byte[] a, int aofs, byte[] b, int bofs, byte[] dest, int destofs)
for (int i = 0; i < 16; ++i)
dest[destofs + i] = (byte) (a[aofs + i] ^ b[bofs + i]);
private static void AES_encrypt_block(byte[] plaintext, int plainofs, byte[] key, byte[] ciphertext, int cipherofs)
using (AesManaged aes = new AesManaged())
aes.Mode = CipherMode.ECB;
aes.KeySize = key.Length * 8;
aes.Padding = PaddingMode.None;
ICryptoTransform enc = aes.CreateEncryptor(aes.Key, aes.IV);
enc.TransformBlock(plaintext, plainofs, 16, ciphertext, cipherofs);