加密算法之MD5与SAH-1

示例代码:

package com.java.test;

import java.security.MessageDigest;

public class Demo3 {

	public static void main(String[] args) {
		Demo3 demo = new Demo3();
		System.out.println(demo.digestString("itachi", "MD5"));
		System.out.println(demo.digestString("itachi", "SHA-1"));
	}
	/**
	 * 将信息按指定的算法加密
	 * @param str:要加密的字符串信息
	 * @param digestType:加密类型,选择MD5或SAH-1
	 * @return :加密之后的内容
	 */
	public String digestString(String str, String digestType) {
		MessageDigest md;
		String message = "";
		try {
			md = MessageDigest.getInstance(digestType);
			md.update(str.getBytes());
			message = byteToHex(md.digest());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return message;
	}
	/**
	 * 将字节数组变成十六进制的字符串
	 * @param bytes:字节数组
	 * @return:十六进制的字符串
	 */
	public String byteToHex(byte[] bytes) {
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < bytes.length; i++) {
			int num = 0xFF & bytes[i];
			if(num < 0x10) {
				sb.append("0" + Integer.toHexString(num));
			} else {
				sb.append(Integer.toHexString(num));
			}
		}
		return sb.toString();
	}
}


你可能感兴趣的:(Java,md5,SAH-1,加密算法)