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 the padding according to the scheme referenced in
9  * ISO 7814-4 - scheme 2 from ISO 9797-1. The first byte is 0x80, rest is 0x00
10  */
11 public class ISO7816d4Padding
12     implements BlockCipherPadding
13 {
14     /**
15      * Initialise the padder.
16      *
17      * @param random - a SecureRandom if available.
18      */
init(SecureRandom random)19     public void init(SecureRandom random)
20         throws IllegalArgumentException
21     {
22         // nothing to do.
23     }
24 
25     /**
26      * Return the name of the algorithm the padder implements.
27      *
28      * @return the name of the algorithm the padder implements.
29      */
getPaddingName()30     public String getPaddingName()
31     {
32         return "ISO7816-4";
33     }
34 
35     /**
36      * add the pad bytes to the passed in block, returning the
37      * number of bytes added.
38      */
addPadding( byte[] in, int inOff)39     public int addPadding(
40         byte[]  in,
41         int     inOff)
42     {
43         int added = (in.length - inOff);
44 
45         in [inOff]= (byte) 0x80;
46         inOff ++;
47 
48         while (inOff < in.length)
49         {
50             in[inOff] = (byte) 0;
51             inOff++;
52         }
53 
54         return added;
55     }
56 
57     /**
58      * return the number of pad bytes present in the block.
59      */
padCount(byte[] in)60     public int padCount(byte[] in)
61         throws InvalidCipherTextException
62     {
63         int count = in.length - 1;
64 
65         while (count > 0 && in[count] == 0)
66         {
67             count--;
68         }
69 
70         if (in[count] != (byte)0x80)
71         {
72             throw new InvalidCipherTextException("pad block corrupted");
73         }
74 
75         return in.length - count;
76     }
77 }
78