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