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