一个Hash函数的安全性高低最终要看能否找到函数的整体碰撞,由于SHA-256算法具有迭代型结构,根据迭代算法的雪崩效应,随着轮数的增加,相应的整体碰撞复杂度会急剧上升,这就使得找到整体碰撞变得非常困难,直至目前现有的攻击还无法找到SHA-256的一个整体碰撞。因此,SHA-256算法被认为是目前最安全的Hash函数之一。
/**
* @author lin
*/
public class SHA256 {
public static String encrypt(String str){
MessageDigest messageDigest;
String encodeStr = "";
try {
messageDigest = MessageDigest.getInstance("SHA-256");
messageDigest.update(str.getBytes("UTF-8"));
encodeStr = byte2Hex(messageDigest.digest());
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return encodeStr;
}
/**
* @param bytes
* @return
*/
private static String byte2Hex(byte[] bytes){
StringBuffer stringBuffer = new StringBuffer();
String temp = null;
for (int i=0;i<bytes.length;i++){
temp = Integer.toHexString(bytes[i] & 0xFF);
if (temp.length()==1){
stringBuffer.append("0");
}
stringBuffer.append(temp);
}
return stringBuffer.toString();
}
public static void main(String[] args) {
String url = "https://www.suibibk.com/blog/579412311547052032/557891087667036160/611874046816026624";
String sha256 = SHA256.encrypt(url);
System.out.println("sha256:"+sha256);
}
}