1 /* $Id: Util.java,v 1.3 2003/02/07 15:06:24 gelderen Exp $ 2 * 3 * Copyright (C) 2000 The Cryptix Foundation Limited. 4 * All rights reserved. 5 * 6 * Use, modification, copying and distribution of this software is subject 7 * the terms and conditions of the Cryptix General Licence. You should have 8 * received a copy of the Cryptix General Licence along with this library; 9 * if not, you can download a copy from http://www.cryptix.org/ . 10 */ 11 package cryptix.jce.provider.util; 12 13 14 import java.math.BigInteger; 15 16 17 /** 18 * Misc utility methods. 19 * 20 * @version $Revision: 1.3 $ 21 * @author Jeroen C. van Gelderen (gelderen@cryptix.org) 22 */ 23 public final class Util 24 { 25 public static final BigInteger BI_ZERO = BigInteger.valueOf(0L); 26 27 28 public static final BigInteger BI_ONE = BigInteger.valueOf(1L); 29 30 Util()31 private Util() {} 32 33 34 /** 35 * Fit (stretch or shrink) the given positive BigInteger into a 36 * byte[] of resultByteLen bytes without losing precision. 37 * 38 * @trhows IllegalArgumentException 39 * If x negative, or won't fit in requested number of bytes. 40 */ toFixedLenByteArray(BigInteger x, int resultByteLen)41 public static byte[] toFixedLenByteArray(BigInteger x, int resultByteLen) { 42 43 if (x.signum() != 1) 44 throw new IllegalArgumentException("BigInteger not positive."); 45 46 byte[] x_bytes = x.toByteArray(); 47 int x_len = x_bytes.length; 48 49 if (x_len <= 0) 50 throw new IllegalArgumentException("BigInteger too small."); 51 52 /* 53 * The BigInteger contract specifies that we now have at most one 54 * superfluous leading zero byte: 55 */ 56 int x_off = (x_bytes[0] == 0) ? 1 : 0; 57 x_len -= x_off; 58 59 /* 60 * Check whether the BigInteger will fit in the requested byte length. 61 */ 62 if ( x_len > resultByteLen) 63 throw new IllegalArgumentException("BigInteger too large."); 64 65 /* 66 * Now stretch or shrink the encoding to fit in resByteLen bytes. 67 */ 68 byte[] res_bytes = new byte[resultByteLen]; 69 int res_off = resultByteLen-x_len; 70 System.arraycopy(x_bytes, x_off, res_bytes, res_off, x_len); 71 return res_bytes; 72 } 73 74 75 /** 76 * Compare two byte[] for equality. byte[]s are considered equal if they 77 * have the same length and the same contents (same elems, same order). 78 * Additionally, two null arguments compare equal too. 79 */ equals(byte[] a, byte[] b)80 public static boolean equals(byte[] a, byte[] b) { 81 82 if( a==null && b==null ) return true; 83 84 if( a==null ^ b==null ) return false; 85 86 int aLen = a.length; 87 int bLen = b.length; 88 if( aLen != bLen ) return false; 89 90 for(int i=0; i<aLen; i++) 91 if( a[i] != b[i] ) return false; 92 93 return true; 94 } 95 } 96