tags:

views:

84

answers:

2

Why can I encrypt only 16 characters of text?

Works:

string plainText = "1234567890123456";

Doesn't work:

string plainText = "12345678901234561";

Doesn't work:

string plainText = "123456789012345";

Code:

string plainText = "1234567890123456";
byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);

byte[] keyBytes = System.Text.Encoding.UTF8.GetBytes("1234567890123456");

byte[] initVectorBytes = System.Text.Encoding.UTF8.GetBytes("1234567890123456");

RijndaelManaged symmetricKey = new RijndaelManaged();
symmetricKey.Mode = CipherMode.CBC;
symmetricKey.Padding = PaddingMode.Zeros;

ICryptoTransform encryptor = symmetricKey.CreateDecryptor(keyBytes, initVectorBytes);

MemoryStream memoryStream = new MemoryStream();

CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write);

cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);

cryptoStream.FlushFinalBlock();

byte[] cipherTextBytes = memoryStream.ToArray();

memoryStream.Close();
cryptoStream.Close();

string cipherText = Convert.ToBase64String(cipherTextBytes);

Console.ReadLine();
A: 

Probably because AES is a block cipher with 128 bits per block.. maybe you just need to add a padding such that length % 128 == 0.

(I'm not a C# developer but it can happen that an implementation doesn't care about adding padding by itself)

Just a hint: try if it works with 256 bits

Jack
bytes --> bits?
dtb
PaddingMode (set to Zeros in the example) should add padding automatically. Looks like the error is typo: "encryptor = symmetricKey.CreateDecryptor"
PaulG
yes, it was supposed to be bits ofc :)
Jack
+3  A: 

Not sure I understand the question, but looking at what I assume the intent is of the code the following

symmetricKey.CreateDecryptor

Should probably be

symmetricKey.CreateEncryptor
Chris Taylor