package com.sw.mes.auth.utils;

/**
 * 密码帮助类
 *
 * @author zhanglinlin
 * @Description:
 * @date 2018年03月05日 15:28
 */
public class PasswordUtil {

    private static final int INTERATIONS = 1024;
    private static final int SALT_SIZE = 8;

    public static class HashPassword {
        public String salt;
        public String password;
    }

    /**
     * 根据明文密码，产生一个加密密码和密钥
     * @param plainPassword
     * @return
     * @throws Exception
     */
    public static HashPassword encryptPassword(String plainPassword) throws Exception {
        HashPassword result = new HashPassword();
        byte[] salt = Digests.generateSalt(SALT_SIZE);
        result.salt = Encodes.encodeHex(salt);

        byte[] hashPassword = Digests.sha1(plainPassword.getBytes(), salt, INTERATIONS);
        result.password = Encodes.encodeHex(hashPassword);
        return result;
    }

    /**
     * 验证密码
     *
     * @param plainPassword 明文密码
     * @param password      密文密码
     * @param salt          密钥
     * @return
     */
    public static boolean validatePassword(String plainPassword, String password, String salt) throws Exception {
        byte[] hashPassword = Digests.sha1(plainPassword.getBytes(), Encodes.decodeHex(salt), INTERATIONS);
        String oldPassword = Encodes.encodeHex(hashPassword);
        return password.equals(oldPassword);
    }

}
