C#, Microsoft Windows

Rijndael (AES 128) decryption in C#

Let’s see how we can decrypt a base64 encoded cipher text in C#!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
public String Decrypt(String text, String key)
{
	//decode cipher text from base64
	byte[] cipher = Convert.FromBase64String(text);
	//get key bytes
	byte[] btkey = Encoding.ASCII.GetBytes(key);
 
	//init AES 128
	RijndaelManaged aes128 = new RijndaelManaged();
	aes128.Mode = CipherMode.ECB;
	aes128.Padding = PaddingMode.Zeros;
 
	//decrypt
	ICryptoTransform decryptor = aes128.CreateDecryptor(btkey, null);
	MemoryStream ms = new MemoryStream(cipher);
	CryptoStream cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read);
 
	byte[] plain = new byte[cipher.Length];
	int decryptcount = cs.Read(plain, 0, plain.Length);
 
	ms.Close();
	cs.Close();
 
	//return plaintext in String
	return Encoding.UTF8.GetString(plain, 0, decryptcount);
}

Usage:

String plaintext = Decrypt(base64_ciphered_text, 128bit_key);