XQY
XQY

Reputation: 562

ICryptoTransform.TransformBlock : What's going on?

I'm learning the ICryptoTransform.

And I encrypted some data and decrypted them back using the ICryptoTransform.TransformBlock. No exception is throwed, but I found my data move right about one bolck.

Please looks below codes:

//Init
var aes = new AesCryptoServiceProvider();
var key = new byte[16];
var IV = new byte[16];
var rand = new Random();
rand.NextBytes(key);
rand.NextBytes(IV);
var dev = aes.CreateEncryptor(key, IV);
var invdev = aes.CreateDecryptor(key, IV);
const int bufsize = 16 * 2;
var input = new byte[bufsize];
var output = new byte[bufsize];
var backbuf = new byte[bufsize];
rand.NextBytes(input);

// Start Caculate
for (int i = 0; i < bufsize; i += 16)
    dev.TransformBlock(input, i, 16, output, i);
backbuf[0] = 10; // it seems that invdev didn't touch backbuf[0 ~ 15]
for (int i = 0; i < bufsize; i += 16)
    invdev.TransformBlock(output, i, 16, backbuf, i);

// Output
for (int i = 0; i < bufsize; ++i)
{ Console.Write(input[i]); Console.Write(' '); }
Console.WriteLine();
for (int i = 0; i < bufsize; ++i)
{ Console.Write(output[i]); Console.Write(' '); }
Console.WriteLine();
for (int i = 0; i < bufsize; ++i)
{ Console.Write(backbuf[i]); Console.Write(' '); }
Console.WriteLine();
Console.ReadKey();

I think input should equal to backput

But my program outputs :

83 202 85 77 101 146 91 55 90 194 242 26 118 40 46 218 196 202 75 234 228 232 146 156 169 250 72 130 78 185 52 14

219 44 184 142 192 20 222 199 39 232 160 115 254 18 250 70 43 81 149 152 140 4 249 193 248 57 18 59 149 30 41 23

10 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 83 202 85 77 101 146 91 55 90 194 242 26 118 40 46 218

It's funny and confusing... What's wrong with ICryptoTransform.TransformBlock and my program? Or can we use ICryptoTransform.TransformBlock directly ?

Thanks. ( at last please excuse my poor English... )

Upvotes: 0

Views: 3737

Answers (1)

XQY
XQY

Reputation: 562

Well, I may find the solution In fact, there is a integer return value in ICryptoTransform.TransformBlock, which means the number of bytes transformed succedded as CodesInChaos said. And the correct usage of ICryptoTransform.TransformBlock is:

int transed = 0;
for (int i = 0; i < bufsize; i += transed )
    transed = invdev.TransformBlock(output, i, 16, backbuf, i);

And amusing, the first TransformBlock method returns 0... And it's why my program wrong.

It seems that Aes may need a prepare before transform so that the first TransformBlock returns 0.

Upvotes: 1

Related Questions