首页 > 解决方案 > AES decryption without padding in crypt file

问题描述

I would like to decrypt a crypt file without padding with AES 128 bits algorithm : IV (initial vector) and key are 16 Bytes long. I could use OpenSSL to do that, but I won't use it in order to compare result with it. My main problem isn't to withdraw the padding of crypt files, but to regenerate it and I don't know how to do it, and OpenSSL do it. For example, on a file of 19 bytes, the padding on the crypt file will be 13 bytes long, so the crypt file will be saved as 32 bytes long, but I want to remove it. Is there a little function to add to my C/C++ program that I must use?

Edit : Don't answer to fast at my question, this code won't be use on a computer but on a little electronic card and I don't have some helpful commands on it; this is a light Linux OS on it

AES blocks are 16 bytes long, so it need padding when your last block isn't 16 bytes long

Thanks

标签: cencryptionaespadding

解决方案


Ciphertexts aren't padded -- plaintexts get padded so that they're a valid input to an encryption algorithm.

The AES algorithm requires that the input be a whole number of 16 byte blocks, and its output is the same length as the input.

So, for your 19 byte plaintext file, whatever tool you're using to encrypt is:

  1. Adding 13 bytes (probably at the end), yielding a 32 byte padded plaintext. The result needs to contain information about the padding, so that the receiving end can remove it.
  2. Encrypting the padded plaintext, yielding a 32 byte ciphertext

The significant information is spread evenly among the 32 bytes of the ciphertext, so you cannot trim the ciphertext without making it useless.

At your end, when you decrypt, you need to:

  1. Decrypt the 32 byte ciphertext, yielding a 32 byte padded plaintext
  2. Remove the last 13 bytes, yielding the original plaintext

The wording of your question suggests that you already know how to decrypt, and that removing padding is the problem.

So, how do you know how many bytes to trim? It depends on what padding scheme was used to create it. There are many - see Wikipedia.

One common padding scheme is PKCS#7, in which the pad bytes all have a value of n, where n is the number of bytes added. So in your example, the 13 bytes padding bytes all have a value of 13. To remove this, simply read the last byte, and trim off that number of bytes.

(Note that in PKCS#7 an input that's already a whole number of blocks long, will have an extra block added, with every byte set to 16.)

But, don't assume your encrypting end is using PKCS#7 - find out for sure. Either by looking at the documentation/source of what's doing the encrypting, or empirically by decrypting and examining the contents of the still-padded plaintext.


推荐阅读