1 package org.openslx.imagemaster.util;
3 import java.security.MessageDigest;
4 import java.nio.charset.Charset;
5 import java.security.NoSuchAlgorithmException;
12 private static final ThreadLocal<MessageDigest>
md5hash =
new ThreadLocal<MessageDigest>() {
15 public MessageDigest initialValue()
18 return MessageDigest.getInstance(
"MD5" );
19 }
catch ( NoSuchAlgorithmException e ) {
29 private static final ThreadLocal<MessageDigest>
sha256hash =
new ThreadLocal<MessageDigest>() {
32 public MessageDigest initialValue()
35 return MessageDigest.getInstance(
"SHA-256" );
36 }
catch ( NoSuchAlgorithmException e ) {
46 private static final char[]
HEX_CHARS = {
'0',
'1',
'2',
'3',
'4',
'5',
'6',
'7',
'8',
'9',
'A',
'B',
'C',
'D',
'E',
'F' };
50 private static final Charset
UTF8 = Charset.forName(
"UTF-8" );
60 public static String
md5(
final byte[] bytes )
62 return toHexString( md5hash.get().digest( bytes ) );
72 public static String
md5(
final String text )
74 return md5( text.getBytes( UTF8 ) );
85 public static String
sha256(
final byte[] bytes )
87 return toHexString( sha256hash.get().digest( bytes ) );
97 public static String
sha256(
final String text )
99 return sha256( text.getBytes( UTF8 ) );
112 final char[] hexChars =
new char[ bytes.length * 2 ];
113 for (
int j = 0; j < bytes.length; ++j ) {
114 final int v = bytes[j] & 0xFF;
115 hexChars[j * 2] = HEX_CHARS[v >>> 4];
116 hexChars[j * 2 + 1] = HEX_CHARS[v & 0x0F];
118 return new String( hexChars );
static String md5(final byte[] bytes)
Compute md5 hash of given binary data.
static String sha256(final String text)
Compute sha256 hash of the given string.
static String sha256(final byte[] bytes)
Compute sha256 hash of given binary data.
static final Charset UTF8
Constant for the utf-8 charset, saves repeated lookups.
static final ThreadLocal< MessageDigest > sha256hash
Cache of sha256 digesters.
static String toHexString(final byte[] bytes)
Convert given binary data to hex.
static final ThreadLocal< MessageDigest > md5hash
Cache of md5 digesters.
static String md5(final String text)
Compute md5 hash of the given string.
static final char[] HEX_CHARS
For converting to hex string.