# Padding methods for block ciphers - PKCS7 vs ANSI X.923

I was looking through block cipher padding methods, and found two good candidates:

• ANSI X.923 - pad with zeros, then a final byte for the padding length, e.g. 00 00 00 04.
• PKCS7 - pad with bytes that each show the number of padding bytes, e.g. 04 04 04 04.

Is there any benefit to using PKCS7 over ANSI X.923 padding, or vice versa?

-
I like bit padding best, 80 00 for me. The only thing I like better is no padding. Any padding mode can be used for padding oracle attacks, so please do provide an authentication tag and never rely on padding (for symmetric block ciphers) for security. –  owlstead Jun 3 at 22:50

## 1 Answer

This site is a reference for padding:

http://www.di-mgt.com.au/cryptopad.html

Method 3 refers to the ANSI X.923 and method 1 refers to PKCS7.

The main advantage listed is that PKCS7 allows you to double check the number of padding bytes

-
"PKCS7 allows you to double check the number of padding bytes" - the same can be said for ANSI X.923 by checking for the presence of zeroes, in which case both methods provide an equivalent "failsafe" check. –  Thomas Jul 14 '12 at 10:14
@Thomas You can't actually verify either 100% accurately. You can check that there are at least enough padding bytes, but not that there aren't extra padding bytes. With ANSI X.923, if the data ends with zeros, you can't verify that there aren't extra erroneous padding bytes. With PKCS7, if the data ends with the number of padding bytes, you can't verify that there aren't extra erroneous padding bytes. I guess there isn't really any benefit for either method. –  Polynomial Jul 15 '12 at 14:15
@Polynomial: yeah, I guess. I personally would use PKCS7 since it's compatible with OpenSSL (but I guess it doesn't make much a difference since you can decide to add the padding yourself). –  Thomas Jul 15 '12 at 18:25
@Thomas After thinking about it, I realised that PKCS7 is slightly more resistant to bit-flipping damage. In X.923, a flipped bit (for whatever reason) in the final byte makes it difficult to "guess" the number of padding bytes. In PKCS7, you have a higher confidence in recovery since a single flipped bit in the padding doesn't destroy the length value. This could be a good thing (recovery of messages), or a bad thing (forensic analysis) in terms of the security of the mechanism. To be honest, I think the impact is so negligible it's not really worth the concern. –  Polynomial Jul 16 '12 at 7:56
If you want to protect against damage you should use an authentication tag (e.g. a MAC), whatever padding mechanism you deploy. Single byte padding for both is identical, so if you plaintext is N - 1 in size, neither provides much protection. –  owlstead May 3 at 15:56