sha256+salt加密验证算法
近期需要转换python的 from werkzeug.security import generate_password_hash,check_password_hash 的加密验证算法PBKDF2_SHA256为java,现记录如下:
package com.example.utils; import lombok.extern.slf4j.Slf4j; import javax.crypto.SecretKey; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.PBEKeySpec; import java.math.BigInteger; import java.nio.charset.Charset; import java.security.NoSuchAlgorithmException; import java.security.spec.InvalidKeySpecException; import java.security.spec.KeySpec; import java.util.Random; /** * PBKDF2_SHA256加密验证算法 */ @Slf4j public class SHA256Util { /** * 盐的长度 */ public static final int SALT_BYTE_SIZE = 8; /** * 生成密文的长度(例:64 * 4,密文长度为64) */ public static final int HASH_BIT_SIZE = 256; /** * 迭代次数(默认迭代次数为 2000) */ private static final Integer DEFAULT_ITERATIONS = 150000; /** * 算法名称 */ private static final String algorithm = "PBKDF2:SHA256"; /** * 获取密文 * * @param password 密码明文 * @param salt 加盐 * @param iterations 迭代次数 * @return */ public static String getEncodedHash(String password, String salt, int iterations) { // Returns only the last part of whole encoded password SecretKeyFactory keyFactory = null; try { keyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); log.warn("Could NOT retrieve PBKDF2WithHmacSHA256 algorithm {}", e.getMessage()); } KeySpec keySpec = new PBEKeySpec(password.toCharArray(), salt.getBytes(Charset.forName("UTF-8")), iterations, HASH_BIT_SIZE); SecretKey secret = null; try { secret = keyFactory.generateSecret(keySpec); } catch (InvalidKeySpecException e) { e.printStackTrace(); log.warn("Could NOT generate secret key {}", e.getMessage()); } // 使用Base64进行转码密文 // byte[] rawHash = secret.getEncoded(); // byte[] hashBase64 = Base64.getEncoder().encode(rawHash); // return new String(hashBase64); // 使用十六进制密文 return toHex(secret.getEncoded()); } /** * 十六进制字符串转二进制字符串 * * @param hex 十六进制字符串 * @return */ private static byte[] fromHex(String hex) { byte[] binary = new byte[hex.length() / 2]; for (int i = 0; i < binary.length; i++) { binary[i] = (byte) Integer.parseInt(hex.substring(2 * i, 2 * i + 2), 16); } return binary; } /** * 二进制字符串转十六进制字符串 * * @param array 二进制数组 * @return */ private static String toHex(byte[] array) { BigInteger bi = new BigInteger(1, array); String hex = bi.toString(16); int paddingLength = (array.length * 2) - hex.length(); if (paddingLength > 0) return String.format("%0" + paddingLength + "d", 0) + hex; else return hex; } /** * 密文加盐 (获取‘SALT_BYTE_SIZE’长度的盐值) * * @return */ public static String getSalt() { //盐值使用ASCII表的数字加大小写字母组成 int length = SALT_BYTE_SIZE; Random rand = new Random(); char[] rs = new char[length]; for (int i = 0; i < length; i++) { int t = rand.nextInt(3); if (t == 0) { // 数字0-9 rs[i] = (char) (rand.nextInt(10) + 48); } else if (t == 1) { // 字母A-Z rs[i] = (char) (rand.nextInt(26) + 65); } else { // 字母a-z rs[i] = (char) (rand.nextInt(26) + 97); } } return new String(rs); } /** * 获取密文 * 默认迭代次数:2000 * * @param password 明文密码 * @return */ public static String encode(String password) { return encode(password, getSalt()); } /** * 获取密文 * * @param password 明文密码 * @param iterations 迭代次数 * @return */ public static String encode(String password, int iterations) { return encode(password, getSalt(), iterations); } /** * 获取密文 * 默认迭代次数:2000 * * @param password 明文密码 * @param salt 盐值 * @return */ public static String encode(String password, String salt) { return encode(password, salt, DEFAULT_ITERATIONS); } /** * 最终返回的整串密文 * <p> * 注:此方法返回密文字符串组成:算法名称+迭代次数+盐值+密文 * 不需要的直接用getEncodedHash方法返回的密文 * * @param password 密码明文 * @param salt 加盐 * @param iterations 迭代次数 * @return */ public static String encode(String password, String salt, int iterations) { // returns hashed password, along with algorithm, number of iterations and salt String hash = getEncodedHash(password, salt, iterations); return String.format("%s:%d$%s$%s", algorithm, iterations, salt, hash); } /** * 验证密码 * * @param password 明文 * @param hashPassword 密文 * @return */ public static boolean verification(String password, String hashPassword) { // hashPassword = 算法名称+迭代次数+盐值+密文; // PBKDF2:SHA256:150000$F1u1nhk0$e584aeef7a859eba0e8cac74e5314a81a71927b8b9636c16e4898fc2b347be39 String[] parts = hashPassword.split("\\$"); if (parts.length != 3) { return false; } //解析得到迭代次数和盐值进行盐值 Integer iterations = Integer.parseInt(parts[0].split(":")[2]); String salt = parts[1]; String hash = encode(password, salt, iterations); return hash.equals(hashPassword); } }
调用方法:
@Override public String generatePassword(UserInfoVo user) { String password = user.getPassword(); String hashPassword = SHA256Util.encode(password); log.info("password: {}, hashPassword: {}", password, hashPassword); return hashPassword; } @Override public String checkPassword(UserInfoVo user) { String hashPassword = "PBKDF2:SHA256:150000$ZJ96RPKw$cc472944d7df87d1e78faf89ffad10542551087422e4db2233c411785869a725"; String password = user.getPassword(); boolean verification = SHA256Util.verification(password, hashPassword); log.info("password: {}, hashPassword: {}", password, hashPassword); return String.valueOf(verification); }
即可
分类:
springboot
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· PowerShell开发游戏 · 打蜜蜂
· 在鹅厂做java开发是什么体验
· 百万级群聊的设计实践
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战
· 永远不要相信用户的输入:从 SQL 注入攻防看输入验证的重要性