Skip to content

Instantly share code, notes, and snippets.

@francisco-perez-sorrosal
Created June 11, 2012 00:23
Show Gist options
  • Save francisco-perez-sorrosal/2907827 to your computer and use it in GitHub Desktop.
Save francisco-perez-sorrosal/2907827 to your computer and use it in GitHub Desktop.
MessageDigest algorithm response times
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class MainDigester {
public enum Digester {
SHA512("SHA-512"),
SHA384("SHA-384"),
SHA256("SHA-256"),
SHA1("SHA-1"),
MD5("MD5"),
SHA512_UTF8("SHA-512", "UTF-8"),
SHA384_UTF8("SHA-384", "UTF-8"),
SHA256_UTF8("SHA-256", "UTF-8"),
SHA1_UTF8("SHA-1", "UTF-8"),
MD5_UTF8("MD5", "UTF-8"),
SHA512_UTF16("SHA-512", "UTF-16"),
SHA384_UTF16("SHA-384", "UTF-16"),
SHA256_UTF16("SHA-256", "UTF-16"),
SHA1_UTF16("SHA-1", "UTF-16"),
MD5_UTF16("MD5", "UTF-16");
private final String secret = "ab25d473857e1129324ad31ede3cf466f33d2fdad9411d63ce1eeb11097ee778a";
private MessageDigest md;
private final String algorithm;
private final String encoding;
Digester(String algorithm) {
this(algorithm, Charset.defaultCharset().toString());
}
Digester(String algorithm, String encoding) {
this.algorithm = algorithm;
this.encoding = encoding;
}
public String algorithm() {
return algorithm;
}
public String encoding() {
return encoding;
}
public byte[] digest(String text) {
try {
String textToDigest = text + secret;
md = MessageDigest.getInstance(algorithm);
md.update(textToDigest.getBytes(encoding));
} catch (UnsupportedEncodingException e) {
// This can not occur
} catch (NoSuchAlgorithmException e) {
// This can not occur
}
return md.digest();
}
}
/**
* @param args
*/
public static void main(String[] args) {
Long id = new Long(1234567890);
String socialNetworkKey = "016d473857f1029884ec80ede8ae486f33d2fdad9411d63cd2aab11097ee997c";
long startTime;
long totalTime;
byte[] digest;
String text = id.toString() + socialNetworkKey;
String result = "Algorithm: %s, Encoding: %s, Nanos: %s, Millis: %s";
System.out.println("Default charset: " + Charset.defaultCharset());
for (Digester d : Digester.values()) {
startTime = System.nanoTime();
digest = d.digest(text);
totalTime = System.nanoTime() - startTime;
System.out.println(String.format(result, d.algorithm, d.encoding, totalTime, totalTime / 1000000));
System.out.println(toHex(digest));
}
}
public static String toHex(byte[] bytes) {
BigInteger bi = new BigInteger(1, bytes);
return String.format("%0" + (bytes.length << 1) + "X", bi);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment