import java.security.*; import java.nio.ByteBuffer; import java.util.Random; public class SHATest { protected static int toSHA1(byte[] bytes) { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA-1"); } catch(NoSuchAlgorithmException e) { e.printStackTrace(); System.exit(1); } ByteBuffer bb = ByteBuffer.wrap(md.digest(bytes)); return bb.getInt(); } protected static String intAsBinaryString(int num) { String s = ""; for (int i = 0; i < 4; i++) { // this gets the ith byte byte ithByte = (byte) ((num >> 8 * i) & 0xFF); s = byteAsBinaryString(ithByte) + s; } return s; } protected static String byteAsBinaryString(byte num) { String s = ""; for (int i = 0; i < 8; i++) { byte mask = (byte) (1 << i); if ((num & mask) != 0) { s = "1" + s; } else { s = "0" + s; } } return s; } protected static byte[] keyToBytes(T key) { int hc = key.hashCode(); byte[] bytes = new byte[4]; /* Fill in this part. * The goal is to turn the int hc into a byte array. * You will need to extract each of the four bytes * and put them into the byte[] declared above. * Looking around at other code in this program should * give you some very helpful hints. */ return bytes; } protected static String randomString() { Random r = new Random(); String s = ""; for (int i = 0; i < 8; i++) { // 97 is ASCII 'a', so 97 + k is a letter from a-z. int k = r.nextInt(26) + 97; char c = (char)k; s += c; } return s; } public static void main(String[] args) { String key = randomString(); System.out.println("key: " + key); System.out.println("hash: " + toSHA1(keyToBytes(key))); // is the hash deterministic? yes, if the line above and line below agree. System.out.println("hash: " + toSHA1(keyToBytes(key))); } }