01: package org.bouncycastle.crypto.paddings;
02:
03: import java.security.SecureRandom;
04:
05: import org.bouncycastle.crypto.InvalidCipherTextException;
06:
07: /**
08: * A padder that adds X9.23 padding to a block - if a SecureRandom is
09: * passed in random padding is assumed, otherwise padding with zeros is used.
10: */
11: public class X923Padding implements BlockCipherPadding {
12: SecureRandom random = null;
13:
14: /**
15: * Initialise the padder.
16: *
17: * @param random a SecureRandom if one is available.
18: */
19: public void init(SecureRandom random)
20: throws IllegalArgumentException {
21: this .random = random;
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: return "X9.23";
31: }
32:
33: /**
34: * add the pad bytes to the passed in block, returning the
35: * number of bytes added.
36: */
37: public int addPadding(byte[] in, int inOff) {
38: byte code = (byte) (in.length - inOff);
39:
40: while (inOff < in.length - 1) {
41: if (random == null) {
42: in[inOff] = 0;
43: } else {
44: in[inOff] = (byte) random.nextInt();
45: }
46: inOff++;
47: }
48:
49: in[inOff] = code;
50:
51: return code;
52: }
53:
54: /**
55: * return the number of pad bytes present in the block.
56: */
57: public int padCount(byte[] in) throws InvalidCipherTextException {
58: int count = in[in.length - 1] & 0xff;
59:
60: if (count > in.length) {
61: throw new InvalidCipherTextException("pad block corrupted");
62: }
63:
64: return count;
65: }
66: }
|