Android - Removing padded bits in decryption

后端 未结 2 626
心在旅途
心在旅途 2021-02-11 08:53

I\'m working on a security application using my own customized cryptography method, and having a problem on message decryption.

According to the theory, the input has to

相关标签:
2条回答
  • 2021-02-11 09:34

    You should use a padding such as Cipher.getInstance("AES/CBC/PKCS5Padding"). Zero padding, as you are now using, has got the problem that you cannot distinguish between a plain text ending with 00 valued bytes and the padding. If you perform unpadding then you will at least have trouble with the final block. Of course, with text you can just removed the 00 valued bytes at the end before you perform the character decoding routine. Another method is to simply add a 64-bit size indicator at the start of your plain text.

    Note that the default Oracle Java providers do not have zero padding options (as far as I know) so you either have to do the unpadding yourself, or you will have to use another JCE provider such as the Bouncy Castle provider that does include zero padding options (e.g. for Cipher.getInstance("AES/CBC/ZeroPadding").

    Note that the Wikipedia page on padding has much to say on the matter. Also note that CBC mode does not provide integrity protection or authentication by itself, only confidentiality and only if used correctly.

    0 讨论(0)
  • 2021-02-11 09:38

    You can use a block cipher such as AES in streaming mode to get rid of the padding altogether. So you could use e.g. Cipher.getInstance("AES/CTR/NoPadding") or if you also want to include an authentication tag Cipher.getInstance("AES/GCM/NoPadding"). The latter will add some bytes to the end of your ciphertext which you can use to make sure that the ciphertext was created using the correct key, and that the ciphertext was not altered.

    Beware that you may leak information about the size of the plain-text. This is also true for CBC-mode but in that case you will at least have a 16 byte (block size) margin. With streaming mode encryption you will encrypt to precisely the same number of bytes. Also be aware that you need to use a fresh IV value for each encryption with the same key, otherwise you may directly expose the plaintext to an attacker.

    0 讨论(0)
提交回复
热议问题