• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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      */
init(SecureRandom random)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      */
getPaddingName()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      */
addPadding( byte[] in, int inOff)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      */
padCount(byte[] in)56     public int padCount(byte[] in)
57         throws InvalidCipherTextException
58     {
59         int count = in[in.length - 1] & 0xff;
60 
61         if (count > in.length || count == 0)
62         {
63             throw new InvalidCipherTextException("pad block corrupted");
64         }
65 
66         for (int i = 1; i <= count; i++)
67         {
68             if (in[in.length - i] != count)
69             {
70                 throw new InvalidCipherTextException("pad block corrupted");
71             }
72         }
73 
74         return count;
75     }
76 }
77