www.pudn.com > encryption.rar > Crypt.java


/*
Christoforos Pirillos @ Villanova University - May 1999
based on code from the book "Java Network Programming" by Hughes
*/

package encryption;
/** This class provides a variety of useful methods for manipulating
arrays of bytes*/

public class Crypt {

/**Determines whether the two-byte arrays a and b are equal. They must
have the same length and contents to be equal*/

public static final boolean equals (byte[] a, byte[] b) {
	if (a.length != b.length)
		return false;
	else {
	   for (int i=0; i < a.length; ++i)
		if (a[i] != b[i])
		 return false;
	return true;
	}
}
/**Zeroes l bytes of array a, starting from offset ao*/

public static final void zero (byte[] a, int ao, int l) {
	fill ( (byte) 0, a, ao, l);
}

/**Fills l bytes of array b with the value a, starting from offset bo*/

public static final void fill (byte a, byte[] b, int bo, int l) {
	for (int i=0; i> 24);
	b[bo+1] = (byte) (a >> 16);
	b[bo+2] = (byte) (a >> 8);
	b[bo+3] = (byte) (a);
}

/**Writes l integers from array a as bytes into the byte array b. The
integers are taken from offset ao of array a, and written from offset bo
in array b.*/

public static final void intsToBytes (int[] a, int ao, int l, byte[] b,
int bo) {
	for (int i=0; i>56);
	b[bo+1] = (byte) (a>>48);
	b[bo+2] = (byte) (a>>40);
 	b[bo+3] = (byte) (a>>32);
	b[bo+4] = (byte) (a>>24);
	b[bo+5] = (byte) (a>>16);
	b[bo+6] = (byte) (a>>8);
	b[bo+7] = (byte) (a);
}

/**Reads eight bytes from array a, starting from offset ao, and returns
the corresponding long.*/

public static final long bytesToLong (byte[] a, int ao) {
	return ((a[ao] & 0xffL) << 56) | ((a[ao+1] & 0xffL) << 48) |
	((a[ao+2] & 0xffL) << 40) | ((a[ao+3] & 0xffL) << 32) |
	((a[ao+4] & 0xffL) << 24) | ((a[ao+5] & 0xffL) << 16) |
	((a[ao+6] & 0xffL) << 8) | (a[ao+7] & 0xffL);
}

/**Converts an array of bytes into a hexadecimal String; the result will
consist of two hexadecimal digits for every byte of the input; leading
zeroes will be preserved.*/

public static final String bytesToHex (byte[] a) {
	StringBuffer s = new StringBuffer ();
	for (int i=0; i>4) & 0xf, 16));
		s.append (Character.forDigit (a[i] & 0xf, 16));
	}
	return s.toString();
}

/**Converts a long into a hexadecimal String sixteen digits long*/

public static final String longToHex (long a) {
	byte[] b = new byte[8];
	longToBytes (a, b, 0);
	return bytesToHex (b);
}

}