public final class Pkcs5PaddingMechanism extends PaddingMechanism
This padding mechanism is based on the padding scheme defined in PKCS #5 and RFC 1423, but is also compliant with the padding mechanism defined in ISO 10126-2 and ANSI X9.23; and referenced in the W3C XML Encryption Syntax and Processing Recommendation. The padding scheme, as defined in the PKCS #5 specification, can only operate on blocks of 8 bytes. This implementation extends that design to operate on blocks of any size.
n be the length in octets of
the plaintext; let b be the symmetric block cipher block mode
block size (segment size) in octets. To the end of the final block of
plaintext is appended b-(n mod b) bytes, each having the value
b-(n mod b), the number of octets being added. This appended
value is the padding. In hexadecimal, the possible padding values are:
01, 0202, ..., 0808080808080808, 090909090909090909,
..., BBBB...BBBB, where BB is the hexadecimal
representation of the padding byte.N, that must be suffixed to the plaintext to bring it up
to a multiple of the block size. Let the block size be B octets,
thus N is in the range of 1 to B.
Padding is accomplished by suffixing the plaintext with N-1
arbitrary padding bytes and a final byte whose value is N. Upon
decryption, padding is removed by examining the last byte and stripping that
many bytes from the end of the decrypted cipher text. For example, assume an
8 byte block size and plaintext of 0x616263. The padded
plaintext would then be 0x616263????????05 where the
"??" bytes can be any value. Similarly, plaintext of
0x2122232425262728 would be padded to
0x2122232425262728??????????????08.When removing the padding during decryption, only the last byte is examined; this byte indicates the number of padding bytes that must be removed. All previous other padding bytes are not examined; they are simply removed. To strictly follow PKCS #5, one might think that the values of all padding bytes should be checked to ensure they are all identical. However, doing so provides an attacker with opportunity to employ a side-channel attack (cause plaintext bytes to be leaked). For this reason, no checking is done on the remaining padding bytes; they can have arbitrary values as indicated in the ISO 10126-2 padding scheme description. This fact makes this implementation suitable to represent either PKCS #5 padding or ISO 10126-2 padding.
As with all of Entrust's symmetric block cipher padding mechanisms, since all plaintext is always padded with a set of known padding bytes, the padding can always be removed unambiguously after decryption. Following decryption, if padding was used, the result must be unpadded and the padding value will be removed.