MD5

package io.renren.rest.tool;

import org.apache.commons.codec.binary.Hex;
import org.apache.commons.lang.StringUtils;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * MD5加密工具
 *
 *
 * @email
 *
 * @date 2017年8月8日 下午5:17:34
 */
public class MD5Utils {

	private static final String SALT = "1qazxsw2";
	
	private static final String ALGORITH_NAME = "md5";
	
	private static final int HASH_ITERATIONS = 2;

	private static String hash(String plainText, String salt) throws NoSuchAlgorithmException {

		if (StringUtils.isBlank(plainText)) {
			return "";
		}

		if (StringUtils.isBlank(salt)) {
			salt = SALT;
		}

		MessageDigest digest = MessageDigest.getInstance(ALGORITH_NAME);
		digest.reset();
		digest.update(salt.getBytes(StandardCharsets.UTF_8));

		byte[] hashed = digest.digest(plainText.getBytes(StandardCharsets.UTF_8));

		int iterations = HASH_ITERATIONS - 1;
		for (int i = 0; i < iterations; i++) {
			digest.reset();
			hashed = digest.digest(hashed);
		}

		return Hex.encodeHexString(hashed);

	}

	/**
	 * 使用md5生成加密后的密码
	 * @param pswd
	 * @return
	 */
	public static String encrypt(String pswd) {

		String hashedStr = null;

		try {
			hashedStr = hash(pswd, null);
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}

		return hashedStr;

	}
	
	/**
	 * 使用md5生成加密后的密码
	 * @param username
	 * @param pswd
	 * @return
	 */
	public static String encrypt(String username, String pswd) {
		String hashedStr = null;

		try {
			hashedStr = hash(pswd, username + SALT);
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}

		return hashedStr;
	}

	public static void main(String[] args) {
		System.out.println(encrypt("admin", "bobo123"));
	}
	
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值