`
redstarofsleep
  • 浏览: 439751 次
  • 性别: Icon_minigender_1
  • 来自: 苏州
社区版块
存档分类
最新评论

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

    博客分类:
  • Java
 
阅读更多

获取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);
			else
				resultStr.append(onebyte);
		}
		return resultStr.toString();
	}

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics