一、SHA
家族成员编辑
SHA家族的五个算法,分别是SHA-1、SHA-224、SHA-256、SHA-384,和SHA-512,由美国国家安全局(NSA)所设计,并由美国国家标准与技术研究院(NIST)发布;是美国的政府标准。后四者有时并称为SHA-2。SHA-1在许多安全协定中广为使用,包括TLS和SSL、PGP、SSH、S/MIME和IPsec,曾被视为是MD5(更早之前被广为使用的杂凑函数)的后继者。但SHA-1的安全性如今被密码学家严重质疑;虽然至今尚未出现对SHA-2有效的攻击,它的算法跟SHA-1基本上仍然相似;因此有些人开始发展其他替代的杂凑算法。
/**
* 字符串 SHA 加密
*
* @param strSourceText
* @return
*/
private static String SHA(final String strText, final String strType) {
// 返回值
String strResult = null;
// 是否是有效字符串
if (strText != null && strText.length() > 0) {
try {
// SHA 加密开始
// 创建加密对象 并傳入加密類型
MessageDigest messageDigest = MessageDigest.getInstance(strType);
// 传入要加密的字符串
messageDigest.update(strText.getBytes());
// 得到 byte 類型结果
byte byteBuffer[] = messageDigest.digest();
// 將 byte 轉換爲 string
StringBuffer strHexString = new StringBuffer();
// 遍歷 byte buffer
for (int i = 0; i < byteBuffer.length; i++) {
String hex = Integer.toHexString(0xff & byteBuffer[i]);
if (hex.length() == 1) {
strHexString.append('0');
}
strHexString.append(hex);
}
// 得到返回結果
strResult = strHexString.toString();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
}
return strResult;
}
/**
* 传入文本内容,返回 SHA-256 串
*
* @param strText
* @return
*/
public static String SHA256(final String strText) {
return SHA(strText, "SHA-256");
}
/**
* 传入文本内容,返回 SHA-512 串
*
* @param strText
* @return
*/
public static String SHA512(final String strText) {
return SHA(strText, "SHA-512");
}
/**
* 传入文本内容,返回 SHA-1 串
*
* @param strText
* @return
*/
public static String SHA1(final String strText) {
return SHA(strText, "SHA-1");
}
/**
* 传入文本内容,返回 SHA-224 串
*
* @param strText
* @return
*/
public static String SHA224(final String strText) {
return SHA(strText, "SHA-224");
}
/**
* 传入文本内容,返回 SHA-384 串
*
* @param strText
* @return
*/
public static String SHA384(final String strText) {
return SHA(strText, "SHA-384");
}
二、MD5加密
public static String getMD5(String src) {
try {
MessageDigest m = MessageDigest.getInstance("MD5");
m.update(src.getBytes());
byte[] s = m.digest();
return bintoascii(s);
} catch (NoSuchAlgorithmException ex) {
return null;
}
}
public static String bintoascii(byte[] bySourceByte) {
int len, i;
byte tb;
char high, tmp, low;
String result = new String();
len = bySourceByte.length;
for (i = 0; i < len; i++) {
tb = bySourceByte[i];
tmp = (char) ((tb >>> 4) & 0x000f);
if (tmp >= 10) {
high = (char) ('a' + tmp - 10);
} else {
high = (char) ('0' + tmp);
}
result += high;
tmp = (char) (tb & 0x000f);
if (tmp >= 10) {
low = (char) ('a' + tmp - 10);
} else {
low = (char) ('0' + tmp);
}
result += low;
}
return result;
}
测试
String test="啊啊";
System.out.println(Util.SHA256(test));
System.out.println(Util.getMD5(test));