Skip to content

Instantly share code, notes, and snippets.

@yaoxinghuo
Created November 11, 2013 03:40
Show Gist options
  • Save yaoxinghuo/7407429 to your computer and use it in GitHub Desktop.
Save yaoxinghuo/7407429 to your computer and use it in GitHub Desktop.
Java 的 Hash 工具类(MD5 SHA1)
package com.terrynow.common;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
* Developer: Terry DateTime : 2007-12-18 下午03:36:22
*/
public class HashUtils {
public static String md5(String str){
return compute(str, "MD5");
}
public static String sha1(String str){
return compute(str, "SHA-1");
}
private static String compute(String inStr, String hash) {
String result = null;
try {
byte[] valueByte = inStr.getBytes();
MessageDigest md = MessageDigest.getInstance(hash);
md.update(valueByte);
result = toHex(md.digest());
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return result;
}
// 将传递进来的字节数组转换成十六进制的字符串形式并返回
private static String toHex(byte[] buffer) {
StringBuffer sb = new StringBuffer(buffer.length * 2);
for (int i = 0; i < buffer.length; i++) {
sb.append(Character.forDigit((buffer[i] & 0xf0) >> 4, 16));
sb.append(Character.forDigit(buffer[i] & 0x0f, 16));
}
return sb.toString();
}
public static void main(String[] args){
System.out.println(md5("123456"));
System.out.println(sha1("123456"));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment