以下Hash算法经常被用在数据的签名中,这里整理了一下Java版sha-x和md5算法
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.security.MessageDigest;
public class SHA_1 {
public static void main(String[] args) {
String v0_1, v0_2, v0_3;
v0_1 = MD5("测试qwerty1234");
System.out.println("MD5加密:" + v0_1.toUpperCase());
v0_2 = SHA1("测试qwerty1234");
System.out.println("SHA1加密:" + v0_2.toUpperCase());
v0_3 = SHA256("测试qwerty1234");
System.out.println("SHA256加密:" + v0_3.toUpperCase());
}
public final static String MD5(String plaintext) {
char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
try {
MessageDigest mdTemp = MessageDigest.getInstance("MD5");
mdTemp.update(plaintext.getBytes("UTF-8")); // 不设置编码的话中文加密会错误
byte tmp[] = mdTemp.digest();
char str[] = new char[16 * 2];
int k = 0;
for (int i = 0; i < 16; i++) {
str[k++] = hexDigits[tmp[i] >>> 4 & 0xf];
str[k++] = hexDigits[tmp[i] & 0xf];
}
return new String(str);
} catch (UnsupportedEncodingException | NoSuchAlgorithmException e) {
return null;
}
}
public final static String SHA1(String plaintext) {
try {
MessageDigest digest = MessageDigest.getInstance("SHA-1");
digest.update(plaintext.getBytes("UTF-8")); // 不设置编码的话中文加密会错误
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 (UnsupportedEncodingException | NoSuchAlgorithmException e) {
e.printStackTrace();
}
return "";
}
public final static String SHA256(String plaintext) {
try {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
digest.update(plaintext.getBytes("UTF-8")); // 不设置编码的话中文加密会错误
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 (UnsupportedEncodingException | NoSuchAlgorithmException e) {
e.printStackTrace();
}
return "";
}
}
输出
MD5加密:A93D78B74CC3472A98EAC49F3B9996ED
SHA1加密:36565A8732E345BB785BEA18DD5924B637062627
SHA256加密:C45D2D155D599DF32272B1AC75CDF6799AEB584FD24FDBC5FB0620B946BE7DAC