安全散列算法SHA(Secure Hash Algorithm,SHA)
该算法的思想是接收一段明文,然后以一种不可逆的方式将它转换成一段(通常更小)密文, 也可以简单的理解为取一串输入码(称为预映射或信息),并把它们转化为长度较短、位数固定的输出序列即散列值(也称为信息摘要或信息认证代码)的过程。
SHA-1,SHA-224,SHA-256,SHA-384,和SHA-512这几种单向散列算法。
SHA-1,SHA-224和SHA-256适用于长度不超过2^64二进制位的消息。
SHA-384和SHA-512适用于长度不超过2^128二进制位的消息。
package com.soap.util;
import java.security.MessageDigest;
/**
* 安全散列算法SHA(Secure Hash Algorithm,SHA)
*
* @author Roger
*/
public class SHAUtil {
/**
* SHA加密 生成40位SHA码
*
* @param 待加密字符串
*
* @return 返回40位SHA码
*/
public static String shaEncode(String inStr) throws Exception {
MessageDigest sha = null;
try {
sha = MessageDigest.getInstance("SHA");
} catch (Exception e) {
System.out.println(e.toString());
e.printStackTrace();
return "";
}
byte[] byteArray = inStr.getBytes("UTF-8");
byte[] md5Bytes = sha.digest(byteArray);
StringBuffer hexValue = new StringBuffer();
for (int i = 0; i
int val = ((int) md5Bytes[i]) & 0xff;
if (val
hexValue.append("0");
}
hexValue.append(Integer.toHexString(val));
}
return hexValue.toString();
}
/**
* 测试主函数
*
* @param args
* @throws Exception
*/
public static void main(String args[]) throws Exception {
String str = new String("123456");
System.out.println("SHA" + shaEncode(str));
}
}