赞
踩
最近在改由Java取代Python验证用户登录的加密方式。Python通过pbkdf2算法和sha256算法对用户的密码进行加密,由于业务需要,转由Java方式实现。弄了许久也是终于完成了Python和Java的无缝对接。
import org.slf4j.Logger; import org.slf4j.LoggerFactory; 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加密验证算法 * * @author 慌途L */ public class Pbkdf2Sha256 { private static final Logger logger = LoggerFactory.getLogger(Pbkdf2Sha256.class); /** * 盐的长度 */ public static final int SALT_BYTE_SIZE = 16; /** * 生成密文的长度(例:64 * 4,密文长度为64) */ public static final int HASH_BIT_SIZE = 64 * 4; /** * 迭代次数(默认迭代次数为 2000) */ private static final Integer DEFAULT_ITERATIONS = 2000; /** * 算法名称 */ 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) { logger.error("Could NOT retrieve PBKDF2WithHmacSHA256 algorithm", e); } 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) { logger.error("Could NOT generate secret key", e); } //使用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) { rs[i] = (char) (rand.nextInt(10) + 48); } else if (t == 1) { rs[i] = (char) (rand.nextInt(26) + 65); } else { 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); } /** * 最终返回的整串密文 * * 注:此方法返回密文字符串组成:算法名称+迭代次数+盐值+密文 * 不需要的直接用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 hashedPassword 密文 * @return */ public static boolean verification(String password, String hashedPassword) { //hashedPassword = 算法名称+迭代次数+盐值+密文; String[] parts = hashedPassword.split("\\$"); if (parts.length != 4) { return false; } //解析得到迭代次数和盐值进行盐值 Integer iterations = Integer.parseInt(parts[1]); String salt = parts[2]; String hash = encode(password, salt, iterations); return hash.equals(hashedPassword); } }
package com.huangtu.test; import java.io.IOException; public class TestCode { public static void main(String[] args) throws IOException { //获取密文(密码加盐) String salt = Pbkdf2Sha256.encode("123456"); System.out.println("salt===" + salt); boolean verification = Pbkdf2Sha256.verification("123456", salt); System.out.println(verification); /** * Python生成的密码和密文 * admin123456 * PBKDF2&SHA256$2000$SzNgPdzz$50f22e207abec8e837bce97642a46f965f19d992217d7df9be496700b286345d * PBKDF2&SHA256$2000$VzmO4yOZ$71891148cfbdd9103aaa511d20dc52431c8947ce4a00d89708231ec76053f6f3 * PBKDF2&SHA256$2000$3xuRb8AR$6bff0310fd35c88572633b00d36e9039fef3e68c6e37b14204958946e8738e93 */ String oldPassword7 = "PBKDF2&SHA256$2000$SzNgPdzz$50f22e207abec8e837bce97642a46f965f19d992217d7df9be496700b286345d"; String oldPassword8 = "PBKDF2&SHA256$2000$VzmO4yOZ$71891148cfbdd9103aaa511d20dc52431c8947ce4a00d89708231ec76053f6f3"; String oldPassword9 = "PBKDF2&SHA256$2000$3xuRb8AR$6bff0310fd35c88572633b00d36e9039fef3e68c6e37b14204958946e8738e93"; boolean verification7 = Pbkdf2Sha256.verification("admin123456", oldPassword7); boolean verification8 = Pbkdf2Sha256.verification("admin123456", oldPassword8); boolean verification9 = Pbkdf2Sha256.verification("admin123456", oldPassword9); System.out.println(verification7); System.out.println(verification8); System.out.println(verification9); } }
通过测试,用户在python注册加密密码后得到密文,即密码,在java以相同的方式去加密,然后对两个密文进行对比,相同则是密码一致,否则不一致
https://howtodoinjava.com/security/how-to-generate-secure-password-hash-md5-sha-pbkdf2-bcrypt-examples/
https://blog.csdn.net/u014375869/article/details/46773995
https://my.oschina.net/haopeng/blog/2873022
欢迎关注公众号:慌途L
后面会慢慢将文章迁移至公众号,也是方便在没有电脑的时候可以进行翻阅,更新的话会两边同时更新,大家不用担心!
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。