Home | History | Annotate | Download | only in paddings
      1 package org.bouncycastle.crypto.paddings;
      2 
      3 import java.security.SecureRandom;
      4 
      5 import org.bouncycastle.crypto.InvalidCipherTextException;
      6 
      7 /**
      8  * A padder that adds PKCS7/PKCS5 padding to a block.
      9  */
     10 public class PKCS7Padding
     11     implements BlockCipherPadding
     12 {
     13     /**
     14      * Initialise the padder.
     15      *
     16      * @param random - a SecureRandom if available.
     17      */
     18     public void init(SecureRandom random)
     19         throws IllegalArgumentException
     20     {
     21         // nothing to do.
     22     }
     23 
     24     /**
     25      * Return the name of the algorithm the padder implements.
     26      *
     27      * @return the name of the algorithm the padder implements.
     28      */
     29     public String getPaddingName()
     30     {
     31         return "PKCS7";
     32     }
     33 
     34     /**
     35      * add the pad bytes to the passed in block, returning the
     36      * number of bytes added.
     37      */
     38     public int addPadding(
     39         byte[]  in,
     40         int     inOff)
     41     {
     42         byte code = (byte)(in.length - inOff);
     43 
     44         while (inOff < in.length)
     45         {
     46             in[inOff] = code;
     47             inOff++;
     48         }
     49 
     50         return code;
     51     }
     52 
     53     /**
     54      * return the number of pad bytes present in the block.
     55      */
     56     public int padCount(byte[] in)
     57         throws InvalidCipherTextException
     58     {
     59         int count = in[in.length - 1] & 0xff;
     60         byte countAsbyte = (byte)count;
     61 
     62         // constant time version
     63         boolean failed = (count > in.length | count == 0);
     64 
     65         for (int i = 0; i < in.length; i++)
     66         {
     67             failed |= (in.length - i <= count) & (in[i] != countAsbyte);
     68         }
     69 
     70         if (failed)
     71         {
     72             throw new InvalidCipherTextException("pad block corrupted");
     73         }
     74 
     75         return count;
     76     }
     77 }
     78