Skip to content

Instantly share code, notes, and snippets.

@follesoe
Created May 18, 2011 15:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save follesoe/978790 to your computer and use it in GitHub Desktop.
Save follesoe/978790 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 = "Hello World";
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();
}
using (var ms = new MemoryStream(encrypted))
using (var decrypt = new CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Read))
{
decrypted = new byte[ms.Length];
decrypt.Read(decrypted, 0, decrypted.Length);
}
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;
}
}
}
@eoftedal
Copy link

Read returns how much was actually read. This Linq usage is probably not the smartest choice performance wise, but you get the point:
decrypted = new byte[ms.Length];
int i = decrypt.Read(decrypted, 0, decrypted.Length);
decrypted = decrypted.Take(i).ToArray();

@follesoe
Copy link
Author

Pen syntax, men ytelsen er vel som du siker ikke helt optimalt, en ekstra pass gjennom arrayet i hvertfal? Uansett - takk for input :))

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