~brian-thomason/+junk/bouncycastle

« back to all changes in this revision

Viewing changes to src/org/bouncycastle/crypto/paddings/TBCPadding.java

  • Committer: Brian Thomason
  • Date: 2011-12-20 17:20:32 UTC
  • Revision ID: brian.thomason@canonical.com-20111220172032-rdtm13jgdxtksacr
Initial import

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
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 Trailing-Bit-Compliment padding to a block.
 
9
 * <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
 
15
    implements BlockCipherPadding
 
16
{
 
17
    /**
 
18
     * Initialise the padder.
 
19
     *
 
20
     * @param random - a SecureRandom if available.
 
21
     */
 
22
    public void init(SecureRandom random)
 
23
        throws IllegalArgumentException
 
24
    {
 
25
        // nothing to do.
 
26
    }
 
27
 
 
28
    /**
 
29
     * Return the name of the algorithm the padder implements.
 
30
     *
 
31
     * @return the name of the algorithm the padder implements.
 
32
     */
 
33
    public String getPaddingName()
 
34
    {
 
35
        return "TBC";
 
36
    }
 
37
 
 
38
    /**
 
39
     * add the pad bytes to the passed in block, returning the
 
40
     * number of bytes added.
 
41
     * <p>
 
42
     * Note: this assumes that the last block of plain text is always 
 
43
     * passed to it inside in. i.e. if inOff is zero, indicating the
 
44
     * entire block is to be overwritten with padding the value of in
 
45
     * should be the same as the last block of plain text.
 
46
     * </p>
 
47
     */
 
48
    public int addPadding(
 
49
        byte[]  in,
 
50
        int     inOff)
 
51
    {
 
52
        int     count = in.length - inOff;
 
53
        byte    code;
 
54
        
 
55
        if (inOff > 0)
 
56
        {
 
57
            code = (byte)((in[inOff - 1] & 0x01) == 0 ? 0xff : 0x00);
 
58
        }
 
59
        else
 
60
        {
 
61
            code = (byte)((in[in.length - 1] & 0x01) == 0 ? 0xff : 0x00);
 
62
        }
 
63
            
 
64
        while (inOff < in.length)
 
65
        {
 
66
            in[inOff] = code;
 
67
            inOff++;
 
68
        }
 
69
 
 
70
        return count;
 
71
    }
 
72
 
 
73
    /**
 
74
     * return the number of pad bytes present in the block.
 
75
     */
 
76
    public int padCount(byte[] in)
 
77
        throws InvalidCipherTextException
 
78
    {
 
79
        byte code = in[in.length - 1];
 
80
 
 
81
        int index = in.length - 1;
 
82
        while (index > 0 && in[index - 1] == code)
 
83
        {
 
84
            index--;
 
85
        }
 
86
 
 
87
        return in.length - index;
 
88
    }
 
89
}