import java.security.*; public class JCAPlay { /* * Converts a byte to hex digit and writes to the supplied buffer */ private static void byte2hex(byte b, StringBuffer buf) { char[] hexChars = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; int high = ((b & 0xf0) >> 4); int low = (b & 0x0f); buf.append(hexChars[high]); buf.append(hexChars[low]); } /* * Converts a byte array to hex string */ private static String toHexString(byte[] block) { StringBuffer buf = new StringBuffer(); int len = block.length; for (int i = 0; i < len; i++) { byte2hex(block[i], buf); if (i < len-1) { buf.append(":"); } } return buf.toString(); } public static void main(String[] args) { // Create an instance of the random generator SecureRandom sr = null; try { sr = SecureRandom.getInstance("SHA1PRNG"); } catch(NoSuchAlgorithmException e) { e.printStackTrace(); } // Length of the random strings in bytes final int NBYTES = 16; // Declare strings byte[] string1 = new byte[NBYTES]; byte[] string2 = new byte[NBYTES]; // Generate random strings sr.nextBytes(string1); System.out.println("string1 = " + toHexString(string1)); sr.nextBytes(string2); System.out.println("string2 = " + toHexString(string2)); byte[] string = new byte[NBYTES]; for(int i = 0; i < NBYTES; i++) { string[i] = (byte)(string1[i] ^ string2[i]); } System.out.println("string = " + toHexString(string)); // Create an instance of the message digest algorithm MessageDigest md = null; try { md = MessageDigest.getInstance("sHa-1"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } // Hash string1 byte[] digest1 = md.digest(string1); System.out.println(toHexString(digest1)); // Hash string2 md.update(string2); byte[] digest2 = md.digest(); System.out.println(toHexString(digest2)); // Hash string for(int i = 0; i < NBYTES; i++) { md.update(string[i]); } byte[] digest = md.digest(); System.out.println(toHexString(digest)); } }