c# - Why 8bytes plaintext becomes 16bytes Cipher? -


its simple code. don't understand, when blocksize 8byte, cipher size 16bytes, why? expecting same blocksize. simple thinking, give 64bits plaintext , expect have 64bits cipher. , don't see reason padding here. seems after every 8bytes(blocksize) cipher becomes 8bytes more. 16bytes block becomes 24bytes cipher etc. why this? want know.

and curiosity, there possibility/way have 8bytes cipher 8bytes block?

the 3des code: (only encryption part)

static void main(string[] args)     {          console.writeline("enter plain text: ");         string original =console.readline();         tripledescryptoserviceprovider mytripledes = new tripledescryptoserviceprovider();         byte[] encrypted = encryptstringtobytes(original,mytripledes.key, mytripledes.iv);         string encrypt = convert.tobase64string(encrypted);         string decrypted = decryptstringfrombytes(encrypted,mytripledes.key, mytripledes.iv);         console.writeline("encryted: " +encrypt);         console.writeline("decrypted: " +decrypted);         console.readline();      }        static byte[] encryptstringtobytes(string plaintext, byte[] key, byte[] iv)     {         byte [] data= encoding.utf8.getbytes(plaintext);         console.writeline("the block length: " +data.length);         tripledescryptoserviceprovider tdsalg = new tripledescryptoserviceprovider();         tdsalg.blocksize = 64;         tdsalg.keysize = 128;         tdsalg.key = key;           tdsalg.iv = iv;           icryptotransform encryptor = tdsalg.createencryptor(tdsalg.key, tdsalg.iv);         byte[] encrypted = encryptor.transformfinalblock(data, 0, data.length);         console.writeline("the cipher length: " + encrypted.length);         return encrypted;     } 

enter image description here

the default padding mode tripledescryptoserviceprovider in .net pkcs7. pkcs7 padding mode adds many bytes needed fill block, @ least 1 byte(!). means if data ends in block boundary, block needs added consists solely of padding bytes.

you can avoid explicitly setting:

tdsalg.padding = paddingmode.none; 

you set cipher length 8 bytes expected.

as reason why padding needed though data matches block size:

imagine data ends bytes valid padding bytes. in case decryptor of message assume these in fact padding bytes , message shorten. avoid this, there @ least 1 padding byte added in cases. padding bytes in pkcs7 state number of bytes in padding. if padded message ends in 0x07 means 7 padding bytes used , can removed when decoding message.


Comments

Popular posts from this blog

c++ - OpenCV Error: Assertion failed <scn == 3 ::scn == 4> in unknown function, -

php - render data via PDO::FETCH_FUNC vs loop -

The canvas has been tainted by cross-origin data in chrome only -