package com.security.sha;
import java.security.MessageDigest;
/**
* @author Administrator
* sha 加密 推荐先
*/
public class Sha {
public static void main(String[] args) throws Exception {
System.out.println("简单的sha加密__:"+shaEncode("123456"));
//避免不同人密文相同
System.out.println("带key映射的加密__:"+shaKeyEncode("zhangsan","123456"));
}
public static String shaEncode(String generalStr) throws Exception {
MessageDigest messageDigest = MessageDigest.getInstance("SHA");
// MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
// MessageDigest messageDigest = MessageDigest.getInstance("SHA-384");
// MessageDigest messageDigest = MessageDigest.getInstance("SHA-512");
messageDigest.update(generalStr.getBytes("UTF-8"));
byte[] bytes = messageDigest.digest();
String shaStr = "";
for (int i = 0; i < bytes.length; i++) {
String hex = Integer.toHexString(bytes[i] & 0xFF);
if (hex.length()<2) {
hex = hex + "0";
}
shaStr = shaStr + hex;
}
return shaStr;
}
public static String shaKeyEncode(String username,String password) throws Exception {
String generalStr=username+password;
MessageDigest messageDigest = MessageDigest.getInstance("SHA");
// MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
// MessageDigest messageDigest = MessageDigest.getInstance("SHA-384");
// MessageDigest messageDigest = MessageDigest.getInstance("SHA-512");
messageDigest.update(generalStr.getBytes("UTF-8"));
byte[] bytes = messageDigest.digest();
String shaStr = "";
for (int i = 0; i < bytes.length; i++) {
String hex = Integer.toHexString(bytes[i] & 0xFF);
if (hex.length()<2) {
hex = hex + "0";
}
shaStr = shaStr + hex;
}
return shaStr;
}
}
//运行结果
//网上结果对比