CryptoSys API Library Manual

Padding

Before encrypting random-length plaintext with a block cipher algorithm in ECB or CBC mode it needs to be padded to an exact multiple of the block length.

There are many padding rules used in practice. The padding schemes supported in this library are described in the section Padding schemes for block ciphers. It's up to you and your recipient which method you use, but you must agree on one method and use it consistently. If your data is always an exact multiple of the block length and the sender and the recipient agree then you can omit the padding string.

The most common padding rule is known as "PKCS5Padding" originally from PKCS #5 [PKCS5], which in turn is from [RFC1423] and is also the same as the padding rules in PKCS #7 [PKCS7] and section 6.3 of RFC 5652 [CMS] The rules of the scheme are as follows:

For a 64-bit block size: Append a padding string of between 1 and 8 bytes to make the total length an exact multiple of 8 bytes. The value of each byte of the padding string is set to the number of bytes added; namely, 8 bytes of value 0x08, 7 bytes of value 0x07, ..., 2 bytes of 0x02, or one byte of value 0x01. The length of the plaintext to be encrypted thus will be an exact multiple of 8 bytes and it will be possible to recover the message unambiguously from the decrypted ciphertext.

For a 128-bit block size (e.g. AES): Append a padding string of between 1 and 16 bytes to make the total length an exact multiple of 16 bytes. The value of each byte of the padding string is set to the number of bytes added; namely, 16 bytes of value 0x10, 15 bytes of value 0x0F, ..., 2 bytes of 0x02, or one byte of value 0x01. The length of the plaintext to be encrypted thus will be an exact multiple of 16 bytes and it will be possible to recover the message unambiguously from the decrypted ciphertext.

See the functions PAD_BytesBlock, PAD_UnpadBytes, PAD_HexBlock and PAD_UnpadHex.

The "Pad" functions will always return a longer string than the input. The "Unpad" functions will either return a shorter string (indicating a valid padding string was found and stripped) or will return a DECRYPT_ERROR if no valid padding string was found. Note that it is still possible to have a "valid" padding string at the end of incorrectly deciphered data - just by coincidence - so you may get a "valid" result from using the Unpad function, but the decrypted text is garbage.

[Contents] [Index]

[PREV: Block Cipher Modes and Initialization Vectors...]   [Contents]   [Index]   
   [NEXT: Stream ciphers...]

Copyright © 2001-24 D.I. Management Services Pty Ltd. All rights reserved. Generated 2024-01-07T07:42:00Z.