Java(三)- Hash算法

密码学哈希函数

主要性质

  • 1.抗碰撞性(collition-resistance),常用来进行完整性验证。(计算上成立,数学上不成立)
  • 2.原像不可逆
  • 3.难题/谜题友好性(Puzzle Friendliness)

一. hash算法

HashUtils

import org.bouncycastle.crypto.digests.RIPEMD128Digest;
import org.bouncycastle.crypto.digests.RIPEMD160Digest;

import java.security.MessageDigest;
public class HashUtils {

//字节数组转字符串
    public static String byte2HexStr(byte[] bytes){
    StringBuilder sb=new StringBuilder();
    for(byte byt:bytes){
        sb.append(Integer.toString((byt&0xff)+0x100,16).substring(1));
    }
    return sb.toString();
}
//MD5,SHA1,SHA-224,SHA-256,SHA-384,SHA-512 方法同
    public static String md5(byte[] data) throws Exception {
    MessageDigest md5 = MessageDigest.getInstance("MD5");
//    md5.update(data);
    byte[] digest = md5.digest(data);
    return byte2HexStr(digest);
}
    public static String sha1(byte[] data) throws Exception {
        MessageDigest sha1 = MessageDigest.getInstance("SHA1");
        byte[] digest = sha1.digest(data);
        return byte2HexStr(digest);
    }
// RIPEMD160,RIPEMD128 
 public static String ripemd160(byte[] data) throws Exception {
        RIPEMD160Digest ripemd160Digest=new RIPEMD160Digest();
        ripemd160Digest.update(data,0,data.length);
        byte[] bytes = new byte[ripemd160Digest.getDigestSize()];
        ripemd160Digest.doFinal(bytes, 0);
        return byte2HexStr(bytes);
    }
//sha3算法使用:224,256,384,512。128和288没找到网站
   public static String k256(byte[] data) throws Exception {
        KeccakDigest keccakDigest=new KeccakDigest(256);
        keccakDigest.update(data,0,data.length);
        byte[] bytes = new byte[keccakDigest.getDigestSize()];
        keccakDigest.doFinal(bytes, 0);
        return byte2HexStr(bytes);
    }

你可能感兴趣的:(Java(三)- Hash算法)