package org.openslx.imagemaster.util; import java.security.MessageDigest; import java.nio.charset.Charset; import java.security.NoSuchAlgorithmException; public class Hash { // Cache of md5 digesters private static final ThreadLocal md5hash = new ThreadLocal() { @Override public MessageDigest initialValue() { try { return MessageDigest.getInstance( "MD5" ); } catch ( NoSuchAlgorithmException e ) { e.printStackTrace(); System.exit(1); return null; } } }; // Cache of sha256 digesters private static final ThreadLocal sha256hash = new ThreadLocal() { @Override public MessageDigest initialValue() { try { return MessageDigest.getInstance( "SHA-256" ); } catch ( NoSuchAlgorithmException e ) { e.printStackTrace(); System.exit(1); return null; } } }; // Cache of sha512 digesters private static final ThreadLocal sha512hash = new ThreadLocal() { @Override public MessageDigest initialValue() { try { return MessageDigest.getInstance( "SHA-512" ); } catch ( NoSuchAlgorithmException e ) { e.printStackTrace(); System.exit(1); return null; } } }; // For converting to hex string private static final char[] HEX_CHARS = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; // Constant private static final Charset UTF8 = Charset.forName( "UTF-8" ); // MD5 public static String md5( final byte[] bytes ) { return toHexString( md5hash.get().digest( bytes ) ); } public static String md5( final String text ) { return md5( text.getBytes( UTF8 )); } // SHA-256 public static String sha256( final byte[] bytes ) { return toHexString( sha256hash.get().digest( bytes ) ); } public static String sha256( final String text ) { return sha256( text.getBytes( UTF8 )); } // SHA-512 public static MessageDigest getSha512Digest() { return sha512hash.get(); } // Helper private static String toHexString( final byte[] bytes ) { final char[] hexChars = new char[bytes.length * 2]; for ( int j = 0; j < bytes.length; ++j ) { final int v = bytes[j] & 0xFF; hexChars[j * 2] = HEX_CHARS[v >>> 4]; hexChars[j * 2 + 1] = HEX_CHARS[v & 0x0F]; } return new String( hexChars ); } }