SHA,全称为“Secure Hash Algorithm”,中文名“安全哈希算法”,主要适用于数字签名标准(Digital Signature Standard DSS)里面定义的数字签名算法(Digital Signature Algorithm DSA)。对于长度小于 2^64 位的消息,SHA1 会产生一个 160 位的消息摘要。
sha加密算法特点有两种:
1:sha加密的信息是不可逆的。
2:不一样的字符串不会产生同样的加密数据。
上边也提到了,SHA 规定了很多种算法,包括了 SHA-1,SHA-224,SHA-256,等很多种。这里我以 SHA-1 为例,讲一下 SHA-1 是如何工作的。
package com.baidu;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class ShaDemo {
public static void main(String[] args) {
String s = "hello";
System.out.println(sha1(s.toString()));
}
public static String sha1(String str) {
try {
MessageDigest digest = MessageDigest.getInstance("SHA-1");
digest.update(str.getBytes());
byte messageDigest[] = digest.digest();
StringBuffer hexString = new StringBuffer();
for (int i = 0; i < messageDigest.length; i++) {
String shaHex = Integer.toHexString(messageDigest[i] & 0xFF);
if (shaHex.length() < 2) {
hexString.append(0);
}
hexString.append(shaHex);
}
return hexString.toString();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return "";
}
}