pbkdf2&sha256加密驗證演算法 | 密碼加密
阿新 • • 發佈:2019-01-28
pbkdf2_sha256加密驗證演算法
最近在改由Java取代Python驗證使用者登入的加密方式。Python通過pbkdf2演算法和sha256演算法對使用者的密碼進行加密,由於業務需要,轉由Java方式實現。弄了許久也是終於完成了Python和Java的無縫對接。
主要使用"getEncodedHash"方法和"encode"方法,具體的加密方式根據自己的需求而定,Python程式碼就不貼了,這裡主要是給大家一個參考思路
Java程式碼:
具體參考 getEncodedHash 方法,因為返回有很多格式,這裡列舉了Base64和64位的十六進位制
下面貼程式碼: Pbkdf2Sha256 工具類
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;
/**
* 迭代次數(預設迭代次數為 30000)
*/
private static final Integer DEFAULT_ITERATIONS = 30000;
/**
* 演算法名稱
*/
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);
}
/**
* 獲取密文
* 預設迭代次數:30000
* @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);
}
/**
* 獲取密文
* 預設迭代次數:30000
* @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);
}
}
Test測試類:通過密碼和密文,驗證Python密文是否和Java的一樣
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生成的密碼和密文
* 123456
* pbkdf2&sha256$30000$UaNFcHyg$1b2ae7dd474ed8ba868e310a6e1af3b28f0cda0b3982d1aeb80bbf28d75bc3bf
* pbkdf2&sha256$30000$PIlXVW8S$c4b6f2710cab9911a5098975b7cd7f41b113b6add2b7a4a76360f218a475b2ad
*/
String oldPassword1 = "pbkdf2&sha256$30000$UaNFcHyg$1b2ae7dd474ed8ba868e310a6e1af3b28f0cda0b3982d1aeb80bbf28d75bc3bf";
String oldPassword2 = "pbkdf2&sha256$30000$PIlXVW8S$c4b6f2710cab9911a5098975b7cd7f41b113b6add2b7a4a76360f218a475b2ad";
boolean verification1 = Pbkdf2Sha256.verification("123456", oldPassword1);
boolean verification2 = Pbkdf2Sha256.verification("123456", oldPassword2);
System.out.println(verification1);
System.out.println(verification2);
/**
* Python生成的密碼和密文
* qdwdqwd4q5678123FF..
* pbkdf2&sha256$30000$DjfyzQJd$f85391e1dd4a73cd9158845688a332779f5bd566e3dcc494022b5018235bdd1b
* pbkdf2&sha256$30000$9WkXOXkn$147498306e8b6fd23661f2f8d5169bed28d8636fb64cf3ca56d549f0e5bb66fd
* pbkdf2&sha256$30000$gB3LTNFA$85cfd2100afea42ea33a104d876b9ee0d2ba9941e26ae492593f01b52acea1b0
*/
String oldPassword4 = "pbkdf2&sha256$30000$DjfyzQJd$f85391e1dd4a73cd9158845688a332779f5bd566e3dcc494022b5018235bdd1b";
String oldPassword5 = "pbkdf2&sha256$30000$9WkXOXkn$147498306e8b6fd23661f2f8d5169bed28d8636fb64cf3ca56d549f0e5bb66fd";
String oldPassword6 = "pbkdf2&sha256$30000$gB3LTNFA$85cfd2100afea42ea33a104d876b9ee0d2ba9941e26ae492593f01b52acea1b0";
boolean verification4 = Pbkdf2Sha256.verification("qdwdqwd4q5678123FF..", oldPassword4);
boolean verification5 = Pbkdf2Sha256.verification("qdwdqwd4q5678123FF..", oldPassword5);
boolean verification6 = Pbkdf2Sha256.verification("qdwdqwd4q5678123FF..", oldPassword6);
System.out.println(verification4);
System.out.println(verification5);
System.out.println(verification6);
/**
* Python生成的密碼和密文
* admin123456
* pbkdf2&sha256$30000$SzNgPdzz$50f22e207abec8e837bce97642a46f965f19d992217d7df9be496700b286345d
* pbkdf2&sha256$30000$VzmO4yOZ$71891148cfbdd9103aaa511d20dc52431c8947ce4a00d89708231ec76053f6f3
* pbkdf2&sha256$30000$3xuRb8AR$6bff0310fd35c88572633b00d36e9039fef3e68c6e37b14204958946e8738e93
*/
String oldPassword7 = "pbkdf2&sha256$30000$SzNgPdzz$50f22e207abec8e837bce97642a46f965f19d992217d7df9be496700b286345d";
String oldPassword8 = "pbkdf2&sha256$30000$VzmO4yOZ$71891148cfbdd9103aaa511d20dc52431c8947ce4a00d89708231ec76053f6f3";
String oldPassword9 = "pbkdf2&sha256$30000$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以相同的方式去加密,然後對兩個密文進行對比,相同則是密碼一致,否則不一致