package com.nbclass.util;

import org.apache.shiro.crypto.RandomNumberGenerator;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;

import com.nbclass.system.model.User;

/**
 * 密码加密
 * @author Leon
 * @datetime 2019年4月1日 下午10:09:02
 */
public class PasswordHelper {
	
	private static RandomNumberGenerator randomNumberGenerator = new SecureRandomNumberGenerator();
	private static String algorithmName = "md5";
	private static int hashIterations = 2;

	public static void encryptPassword(User user) {
		user.setSalt(randomNumberGenerator.nextBytes().toHex());
		String newPassword = new SimpleHash(algorithmName, user.getPassword(), ByteSource.Util.bytes(user.getCredentialsSalt()), hashIterations).toHex();
		user.setPassword(newPassword);
	}

	public static String getPassword(User user){
		String encryptPassword = new SimpleHash(algorithmName,user.getPassword(), ByteSource.Util.bytes(user.getCredentialsSalt()),hashIterations).toHex();
		return encryptPassword;
	}

	/**
     * 使用BCrypt对密码进行加密
     * @param password
     * @return
     */
    public static String encryptPwdByBCrypt(String password){
    	return BCrypt.hashpw(password, BCrypt.gensalt());
    }
    
    /**
     * BCrypt 密码验证
     * @param password		明文
     * @param ciphertext	密文
     * @return	if equal ? true : false
     */
    public static boolean checkPwdByBCrypt(String password, String ciphertext){
    	return BCrypt.checkpw(password, ciphertext);
    }
    
	public static void main(String[] args) {
		User user = new User();
		user.setUsername("admin");
		user.setPassword("szxgl.com");
		encryptPassword(user);
		System.out.println("salt="+user.getSalt());
		System.out.println("password="+user.getPassword());
		
		String pwd1 = encryptPwdByBCrypt("123456");
		boolean result = checkPwdByBCrypt("123456", pwd1);
		System.out.println("pwd1="+pwd1+", result="+result);
	}
}
