您的位置:首页 > 编程语言 > Java开发

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

2015-04-17 09:02 260 查看
获取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();
	}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: