0

I'm using the Node-Forge library for AES encryption. I know AES needs to be padded to the ceiling of the block size. Node-Forge uses the hex code 05 for padding. What is this code, and how should I unpad the message?

Right now I'm doing something like this:

Encrypt message "hello world"
Output: e20bf1586a94082707b8dfcf26d70ea5

Decrypted output: 68656c6c6f20776f726c640505050505
Output.replaceAll("05", "")
New output: 68656c6c6f20776f726c64

68656c6c6f20776f726c64 decoded is "hello world"
  • 1
    This is called [PKCS#7 padding](https://en.wikipedia.org/wiki/Padding_(cryptography)#PKCS#5_and_PKCS#7) – Maarten Bodewes Aug 02 '23 at 14:33
  • 1
    Unpadding, take the last byte, remove that amount of bytes. I'd first check that the byte is between 1..blocksize & I'd add checks that the other bytes also have this value. – Maarten Bodewes Aug 02 '23 at 15:23
  • Within, not between. Duh. And you'd perform the action on the bytes, rather than the hexadecimal **representation** of those byte. That you don't need anyway. – Maarten Bodewes Aug 02 '23 at 15:43
  • Node Forge implicitly unpads during decryption, as do most libraries that support PKCS#7 padding. Check if your library used for decryption does not already support unpadding. Also, there are separate implementations for most platforms (e.g. [pkcs7](https://github.com/brightcove/pkcs7) for a 16 bytes blocksize) although unpadding can be implemented quite easily by yourself, see e.g. [here](https://github.com/brightcove/pkcs7/blob/master/src/unpad.js) (more robust implementations would possibly check the validity of the padding before unpadding as described in the previous comments). – Topaco Aug 02 '23 at 17:51
  • Looking at the NPM documentation / samples I indeed see `// Note: CBC and ECB modes use PKCS#7 padding as default`. Maybe no padding is configured or the plaintext has been double padded; can't tell without code. – Maarten Bodewes Aug 02 '23 at 19:47

0 Answers0