hexSHA1散列加密解密(不可逆)

1.maven引入codec和commons依赖:

<dependency>
  <groupId>commons-codec</groupId>
  <artifactId>commons-codec</artifactId>
  <version>1.9</version>
</dependency>
<dependency>
  <groupId>org.apache.commons</groupId>
  <artifactId>commons-lang3</artifactId>
  <version>3.4</version>
</dependency>

2.util新建secrity包放入Digests.java、Encodes.java和Exceptions.java工具类

3.ValidateUtil:

public class ValidateUtil {
    public static final String HASH_ALGORITHM = "SHA-1";
    public static final int HASH_INTERATIONS = 1024;
    public static final int SALT_SIZE = 8;

    /**
     * @param plainPassword
     * @return password 加密密码(生成安全的密码,生成随机的16位salt并经过1024次 sha-1 hash)
     */
    public static String entryptPassword(String plainPassword) {
        byte[] salt = Digests.generateSalt(SALT_SIZE);
        byte[] hashPassword = Digests.sha1(plainPassword.getBytes(), salt, HASH_INTERATIONS);
        return Encodes.encodeHex(salt) + Encodes.encodeHex(hashPassword);
    }

    /**
     * @param plainPassword
     * @param password
     * @return boolean 解密判断密码是否正确
     */
    public static boolean validatePassword(String plainPassword, String password) {
        byte[] salt = Encodes.decodeHex(password.substring(0, 16));
        byte[] hashPassword = Digests.sha1(plainPassword.getBytes(), salt, HASH_INTERATIONS);
        return password.equals(Encodes.encodeHex(salt) + Encodes.encodeHex(hashPassword));
    }
}

 

上一篇:C#系列 - 正则表达式


下一篇:SpringCloud微服务实战——搭建企业级开发框架(七):自定义通用响应消息及统一异常处理