/** * Returns an MD5 hash. * * @param pw String * @return String */ private static String md5(final String pw) { final StringBuilder sb = new StringBuilder(); try { final MessageDigest md = MessageDigest.getInstance("MD5"); md.update(pw.getBytes()); for (final byte b : md.digest()) { final String s = Integer.toHexString(b & 0xFF); if (s.length() == 1) sb.append('0'); sb.append(s); } } catch (final NoSuchAlgorithmException ex) { // should not occur ex.printStackTrace(); } return sb.toString(); }
/** * Compute the hash an IP address. The hash is the first 8 bytes of the SHA digest of the IP * address. */ private static byte[] computeAddressHash() { /* * Get the local host's IP address. */ byte[] addr = (byte[]) java.security.AccessController.doPrivileged( new PrivilegedAction() { public Object run() { try { return InetAddress.getLocalHost().getAddress(); } catch (Exception e) { } return new byte[] {0, 0, 0, 0}; } }); byte[] addrHash; final int ADDR_HASH_LENGTH = 8; try { /* * Calculate message digest of IP address using SHA. */ MessageDigest md = MessageDigest.getInstance("SHA"); ByteArrayOutputStream sink = new ByteArrayOutputStream(64); DataOutputStream out = new DataOutputStream(new DigestOutputStream(sink, md)); out.write(addr, 0, addr.length); out.flush(); byte digest[] = md.digest(); int hashlength = Math.min(ADDR_HASH_LENGTH, digest.length); addrHash = new byte[hashlength]; System.arraycopy(digest, 0, addrHash, 0, hashlength); } catch (IOException ignore) { /* can't happen, but be deterministic anyway. */ addrHash = new byte[0]; } catch (NoSuchAlgorithmException complain) { throw new InternalError(complain.toString()); } return addrHash; }