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 X9.23 padding to a block - if a SecureRandom is 9 * passed in random padding is assumed, otherwise padding with zeros is used. 10 */ 11 public class X923Padding 12 implements BlockCipherPadding 13 { 14 SecureRandom random = null; 15 16 /** 17 * Initialise the padder. 18 * 19 * @param random a SecureRandom if one is available. 20 */ init(SecureRandom random)21 public void init(SecureRandom random) 22 throws IllegalArgumentException 23 { 24 this.random = random; 25 } 26 27 /** 28 * Return the name of the algorithm the padder implements. 29 * 30 * @return the name of the algorithm the padder implements. 31 */ getPaddingName()32 public String getPaddingName() 33 { 34 return "X9.23"; 35 } 36 37 /** 38 * add the pad bytes to the passed in block, returning the 39 * number of bytes added. 40 */ addPadding( byte[] in, int inOff)41 public int addPadding( 42 byte[] in, 43 int inOff) 44 { 45 byte code = (byte)(in.length - inOff); 46 47 while (inOff < in.length - 1) 48 { 49 if (random == null) 50 { 51 in[inOff] = 0; 52 } 53 else 54 { 55 in[inOff] = (byte)random.nextInt(); 56 } 57 inOff++; 58 } 59 60 in[inOff] = code; 61 62 return code; 63 } 64 65 /** 66 * return the number of pad bytes present in the block. 67 */ padCount(byte[] in)68 public int padCount(byte[] in) 69 throws InvalidCipherTextException 70 { 71 int count = in[in.length - 1] & 0xff; 72 73 if (count > in.length) 74 { 75 throw new InvalidCipherTextException("pad block corrupted"); 76 } 77 78 return count; 79 } 80 } 81