java 实现各种加密(MD5 ,SHA-1,SHA-256)

常用加密算法通用方法:

package BinTest.bin;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class jiami {
public static void main(String args[]){
    String signString="Thank you!";
    String type="SHA-1";
    String result=sign(signString,type);
    System.out.println("采用"+type+"加密之后的串为:"+result);
    type="MD5";
    result=sign(signString,type);
    System.out.println("采用"+type+"加密之后的串为:"+result);
    type="SHA-256";
    result=sign(signString,type);
    System.out.println("采用"+type+"加密之后的串为:"+result);
    type="SHA-384";
    result=sign(signString,type);
    System.out.println("采用"+type+"加密之后的串为:"+result);
}
    //签名     
        public static String sign(String str, String type){
           String s=Encrypt(str,type);
            return s;
        }
        public static String Encrypt(String strSrc, String encName) {
            MessageDigest md = null;
            String strDes = null;
            byte[] bt = strSrc.getBytes();
            try {
                md = MessageDigest.getInstance(encName);
                md.update(bt);
                strDes = bytes2Hex(md.digest()); // to HexString
            } catch (NoSuchAlgorithmException e) {
                System.out.println("签名失败!");
                return null;
            }
            return strDes;
        }
        public static String bytes2Hex(byte[] bts) {
            String des = "";
            String tmp = null;
            for (int i = 0; i < bts.length; i++) {
                tmp = (Integer.toHexString(bts[i] & 0xFF));
                if (tmp.length() == 1) {
                    des += "0";
                }
                des += tmp;
            }
            return des;
        }
}

运行结果:

采用SHA-1加密之后的串为:184eb63a906e3136190bfe5ddab6df3340bd9b91
采用MD5加密之后的串为:498cd895eb5a102c5aeb977e2b928dee
采用SHA-256加密之后的串为:3afdda2c098fc8346a9f2e0ba06ec9c6188411cf78cc7934cfd8b666ce632f55
采用SHA-384加密之后的串为:219604fb00c9d599e84a79821123275b54a08080f26c911b177c9b3893c4996337a4c8caf9eea8fcff6b438b77f68b8b

你可能感兴趣的:(java工具)