Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save blowdart/979051 to your computer and use it in GitHub Desktop.
Save blowdart/979051 to your computer and use it in GitHub Desktop.
Padding problem with AesManaged
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
namespace CryptoTest
{
class Program
{
static void Main(string[] args)
{
string text = "Buy my book, available now from Wrox Press";
byte[] data = Encoding.UTF8.GetBytes(text);
byte[] encrypted;
byte[] decrypted;
var encryptor = GetEncryptor();
using (var ms = new MemoryStream())
using (var encrypt = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write))
{
encrypt.Write(data, 0, data.Length);
encrypt.FlushFinalBlock();
encrypted = ms.ToArray();
}
// "Correct" approach. By initialising the MemoryStream with the encrypted data you're fixing the length
// So instead do the same as you did during encryption, except create a decryptor.
// Start with an empty MemoryStream, attach the CryptoStream to it, then write the encrypted data
// into the CryptoStream, flush, and tada.
using (var ms = new MemoryStream())
using (var decrypt = new CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write))
{
decrypt.Write(encrypted, 0, encrypted.Length);
decrypt.FlushFinalBlock();
decrypted = ms.ToArray();
}
Console.WriteLine("Data length: {0}", data.Length);
Console.WriteLine("Encrypted length: {0}", encrypted.Length);
Console.WriteLine("Decrypted length: {0}", decrypted.Length);
Console.WriteLine();
Console.WriteLine("Original content: -{0}-", text);
Console.WriteLine("Decrypted content: -{0}-", Encoding.UTF8.GetString(decrypted));
Console.ReadLine();
}
private static AesManaged GetEncryptor()
{
string key = "this is my super secret key bojah!";
byte[] keyBytes = Encoding.UTF8.GetBytes(key);
var rfc = new Rfc2898DeriveBytes(key, keyBytes, 1000);
var encryptor = new AesManaged();
encryptor.Key = rfc.GetBytes(16);
encryptor.IV = rfc.GetBytes(16);
return encryptor;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment