Skip to content

Instantly share code, notes, and snippets.

@wang2bo2
Last active August 29, 2015 14:00
Show Gist options
  • Save wang2bo2/7ff0212e2b00ec47b4c3 to your computer and use it in GitHub Desktop.
Save wang2bo2/7ff0212e2b00ec47b4c3 to your computer and use it in GitHub Desktop.
Commonly used hash functions
package com.calciumion.util;
import android.util.Base64;
import java.security.MessageDigest;
import java.security.SignatureException;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
/**
* Commonly used hash functions
*
* @author bowang
*
*/
public final class HashUtils {
private static final String HMAC_SHA1_ALGORITHM = "HmacSHA1";
private HashUtils() {
throw new AssertionError();
}
static final String hexString(byte[] raw) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < raw.length; i++) {
sb.append(Integer.toString((raw[i] & 0xff) + 0x100, 16)
.substring(1));
}
return sb.toString();
}
public static final String md5(String raw) {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(raw.getBytes());
return hexString(md.digest());
} catch (Exception e) {
}
return null;
}
public static final String sha1(String raw) {
return sha1(raw.getBytes());
}
public static final String sha1(byte[] bytes) {
try {
MessageDigest md = MessageDigest.getInstance("SHA1");
md.update(bytes);
return hexString(md.digest());
} catch (Exception e) {
}
return null;
}
public static final String sha1Base64(byte[] bytes) {
try {
MessageDigest md = MessageDigest.getInstance("SHA1");
md.update(bytes);
return Base64.encodeToString(md.digest(), Base64.DEFAULT);
} catch (Exception e) {
}
return null;
}
/**
* Computes RFC 2104-compliant HMAC signature.
*
* @param raw
* The data to be signed.
* @param key
* The signing key.
* @return The Base64-encoded RFC 2104-compliant HMAC signature.
* @throws java.security.SignatureException
* when signature generation fails
*/
public static String hmacsha1(String raw, String key)
throws SignatureException {
try {
// get an hmac_sha1 key from the raw key bytes
SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(),
HMAC_SHA1_ALGORITHM);
// get an hmac_sha1 Mac instance and initialize with the signing key
Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM);
mac.init(signingKey);
// compute the hmac on input data bytes
byte[] rawHmac = mac.doFinal(raw.getBytes());
return hexString(rawHmac);
} catch (Exception e) {
throw new SignatureException("Failed to generate HMAC : "
+ e.getMessage());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment