Pregunta

I'm currently working with mcrypt.java To encrypt and decrypt data from server side and cryptojs on client side but I have some problems because when I encrypt any string, both java and JavaScript display different results.

Well, I was reading about methods and padding schemes of AES encryption and some blogs talking about is incorrect to use CBC mode with NoPadding and is better/correct use CBC with Pkcs7 or another padding.

Anyone can explain me something related with that?

¿Fue útil?

Solución

Padding your plaintext is required if you perform AES encryption in ECB/CBC block cipher mode, unless your plaintext is a multiple of the blocksize. You could of course make sure that your plaintext is always precisely N blocks, but in effect you would be creating your own padding mode.

Many libraries (e.g. mcrypt in PHP) don't specify any padding while they secretly do pad. They just fill up the last block with 00 valued bytes. The effect of this is that you can encrypt ASCII compatible text, which will then be null terminated. In most languages (that do not use null termination) it is also possible to use a trim method to remove this padding. This is however not an official padding mode. Of course this scheme only works if your plain text does not end with control characters. So it is not suitable for any binary plaintext.

It is definitely better to use PKCS#7 padding. Removing PKCS#7 padding is deterministic for any plaintext. This means you can encrypt any value, including UTF-16 encoded text and any binary value. If PKCS#7 padding is not available it is relatively easy to implement it yourself - this is certainly worth the effort. The only disadvantage of PKCS#7 padding for CBC mode is that it may require an additional block of padding when the plaintext is already N times the block size. The reason for this is that the plaintext may otherwise be misinterpreted as being padding.

Note that padding and padding errors are not suitable to detect if the ciphertext was changed in transit. Padding Oracles are very easy to implement and may reveal your plaintext in 128 times the size of your plaintext in bytes (!!!). So use an authenticated mode of operation or a MAC (HMAC or CMAC) if you want to provide integrity and authenticity to your plaintext.

If you really cannot miss the bytes used for padding, please look at CTR or a similar stream mode of operation for your block cipher.


EDIT

there is also ciphertext stealing or CTS that can be used for CBC mode. It is not used much and as there are three different versions of it, you should make sure which one is used.

Nowadays it is more common to use counter mode (CTR mode) or an authenticated mode which is based on it (if a block cipher is used at all). CTR mode doesn't require any padding as it is a streaming mode of operation.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top