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 Trailing-Bit-Compliment padding to a block.
09: * <p>
10: * This padding pads the block out with the compliment of the last bit
11: * of the plain text.
12: * </p>
13: */
14: public class TBCPadding implements BlockCipherPadding {
15: /**
16: * Initialise the padder.
17: *
18: * @param random - a SecureRandom if available.
19: */
20: public void init(SecureRandom random)
21: throws IllegalArgumentException {
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: */
30: public String getPaddingName() {
31: return "TBC";
32: }
33:
34: /**
35: * add the pad bytes to the passed in block, returning the
36: * number of bytes added.
37: * <p>
38: * Note: this assumes that the last block of plain text is always
39: * passed to it inside in. i.e. if inOff is zero, indicating the
40: * entire block is to be overwritten with padding the value of in
41: * should be the same as the last block of plain text.
42: * </p>
43: */
44: public int addPadding(byte[] in, int inOff) {
45: int count = in.length - inOff;
46: byte code;
47:
48: if (inOff > 0) {
49: code = (byte) ((in[inOff - 1] & 0x01) == 0 ? 0xff : 0x00);
50: } else {
51: code = (byte) ((in[in.length - 1] & 0x01) == 0 ? 0xff
52: : 0x00);
53: }
54:
55: while (inOff < in.length) {
56: in[inOff] = code;
57: inOff++;
58: }
59:
60: return count;
61: }
62:
63: /**
64: * return the number of pad bytes present in the block.
65: */
66: public int padCount(byte[] in) throws InvalidCipherTextException {
67: byte code = in[in.length - 1];
68:
69: int index = in.length - 1;
70: while (index > 0 && in[index - 1] == code) {
71: index--;
72: }
73:
74: return in.length - index;
75: }
76: }
|