知识点整理之Java获取MD5或者SHA

来源:互联网 发布:下载不了软件怎么办 编辑:程序博客网 时间:2024/06/01 07:26

获取MD5或者是SHA是经常需要用到的功能.

        /**         * MD5         */public String getMd5(String msg) throws NoSuchAlgorithmException {return this.digest(msg, "MD5");}        /**         * SHA         */public String getSha(String msg) throws NoSuchAlgorithmException {return this.digest(msg, "SHA-1");}        /**         * 具体的生成MD5或SHA的过程         */private String digest(String msg, String type) throws NoSuchAlgorithmException {String result = null;MessageDigest alg = MessageDigest.getInstance(type);alg.update(msg.getBytes());byte[] resultBytes = alg.digest();result  = this.byte2hex(resultBytes);return result;}        /**         * 转16进制         */private String byte2hex(byte[] bytes) {StringBuilder resultStr = new StringBuilder("");for (byte b : bytes) {String onebyte = Integer.toHexString(b & 0xFF);if (onebyte.length() == 1)resultStr.append("0").append(onebyte);elseresultStr.append(onebyte);}return resultStr.toString();}

 

2 0
原创粉丝点击