01: /*
02: *
03: *
04: * Copyright 1990-2007 Sun Microsystems, Inc. All Rights Reserved.
05: * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
06: *
07: * This program is free software; you can redistribute it and/or
08: * modify it under the terms of the GNU General Public License version
09: * 2 only, as published by the Free Software Foundation.
10: *
11: * This program is distributed in the hope that it will be useful, but
12: * WITHOUT ANY WARRANTY; without even the implied warranty of
13: * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14: * General Public License version 2 for more details (a copy is
15: * included at /legal/license.txt).
16: *
17: * You should have received a copy of the GNU General Public License
18: * version 2 along with this work; if not, write to the Free Software
19: * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
20: * 02110-1301 USA
21: *
22: * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
23: * Clara, CA 95054 or visit www.sun.com if you need additional
24: * information or have any questions.
25: */
26:
27: package com.sun.midp.crypto;
28:
29: /**
30: * This class implements padding as specified in the PKCS#5 standard.
31: */
32: public final class PKCS5Padding implements Padder {
33:
34: /** Contains the block size. */
35: private int blockSize;
36:
37: /**
38: * Constructor.
39: * @param blockSize block size
40: */
41: public PKCS5Padding(int blockSize) {
42: this .blockSize = blockSize;
43: }
44:
45: /**
46: * Pads the input according to the PKCS5 padding scheme.
47: * @param queue containing the last bytes of data that must be padded
48: * @param count number of data bytes
49: * @return the number of padding bytes added
50: */
51: public int pad(byte[] queue, int count) {
52: int len = blockSize - count;
53:
54: for (int i = count; i < blockSize; i++) {
55: queue[i] = (byte) len;
56: }
57: return len;
58: }
59:
60: /**
61: * Removes padding bytes that were added to the input.
62: * @param outBuff the output buffer
63: * @param size size of data
64: * @return the number of padding bytes, allowing them to be removed
65: * prior to
66: * putting results in the users output buffer and -1 if input is
67: * not properly
68: * padded
69: * @exception BadPaddingException if not properly padded
70: */
71: public int unPad(byte[] outBuff, int size)
72: throws BadPaddingException {
73: int padValue = outBuff[size - 1] & 0xff;
74:
75: if (padValue < 1 || padValue > blockSize) {
76: throw new BadPaddingException();
77: }
78:
79: for (int i = 0; i < padValue; i++) {
80: if (outBuff[--size] != padValue)
81: throw new BadPaddingException();
82: }
83: return padValue;
84: }
85: }
|