As the title asks. OpenSSL will pad stuff with PKCS5 if you encrypt something, however is there a way to access this feature without encrypting something?

migrated from crypto.stackexchange.com Oct 30 '13 at 12:19

This question came from our site for software developers, mathematicians and others interested in cryptography.

  • 3
    A not-so-ideal solution would be to encrypt with the default PKCS5#5 padding, and then decrypt specifying 'nopad' (which should leave you with padded cleartext) – hunter Oct 29 '13 at 16:44
  • 1
    Have you seen what PKCS#5/7 padding consists of? The specification of the padding protocol takes a single line in the PKCS#5 and PKCS#7 standards. In this case it is probably easier to program it yourself. By the way, this question really belongs on stackoverflow. – Maarten Bodewes Oct 30 '13 at 1:55
  • This question appears to be off-topic because it is about programming (stackoverflow) – Maarten Bodewes Oct 30 '13 at 1:57
  • I'm going to move your question to Security.SE as I think it is more on topic there. – mikeazo Oct 30 '13 at 12:18

PKCS#5 padding is defined relatively to the block size of the underlying block cipher. If there is no block cipher, then there is no block size, and thus the padding is ill-defined.

Nevertheless, if you take as extra input the block size s to use, then the padding is not hard to implement. If the data length is n, then the padding adds exactly k bytes, such that:

  • 1 ≤ k ≤ s
  • n + k is a multiple of s
  • the k bytes all have numerical value k

These rules make the padding unambiguous. There is exactly one solution for k, given by the equation: k = s - (n mod s). Here is an ugly shell script (for Linux) which adds the padding to an input file:


n=$(wc -c < "$input")
k=$(expr "$s" - "$n" "%" "$s")
for i in $(seq "$k") ; do
        sk="${sk}$(/usr/bin/printf "\\\x%02X" "$k")"
cat "$input" ; /usr/bin/printf "%b" "$sk"

(use the input file name as first parameter and the block size as second parameter; the padded file is written on the standard output.)

The reverse operation is left as an exercise (shell programming is not very adequate for this sort of treatment).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.