-
-
Save eoftedal/979038 to your computer and use it in GitHub Desktop.
Padding problem with AesManaged
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.IO; | |
using System.Security.Cryptography; | |
using System.Text; | |
using System.Linq; | |
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]; | |
int length = decrypt.Read(decrypted, 0, decrypted.Length); | |
decrypted = decrypted.Take(length).ToArray(); //Probably wise to use something other than Linq here | |
} | |
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