A-A+
PBKDF2算法 示例详解

【注意:此文章为博主原创文章!转载需注意,请带原文链接,至少也要是txt格式!】
l 算法描述:
- PBKDF2算法
- 哈希算法名称sha256
- 每个卡号对应的迭代次数随机生成(16到20的int次数)
- 每个卡号对应的盐值随机生成(由小写字母和数字组成的12位字符串)
- 生成密文为长度128位的字符串
l 代码示例:
PHP代码参考示例:
<?php //php7+ 版本
$passwd = "123456";
$aa = hash_pbkdf2("sha256", $passwd, "xa312345svsl",16, 128);
print($aa);
?>
Python代码参考示例:
import hashlib, binascii #Python3.7+ 版本
passwd = 123456
slat = 'xa312345svsl'
dk = hashlib.pbkdf2_hmac('sha256', bytes(passwd, encoding="utf8"), bytes(slat, encoding="utf8"), 16, dklen=64)
print(dk.hex())
java代码参考示例:
加密类:
package com.service;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;
import java.math.BigInteger;
public class Encryption {
/**
* 加密方法
* @param String password 需要加密码的明文
* @param byte[] salt 盐值
* @param int iterations 迭代次数
* @param int derivedKeyLength 密文长度
* @return byte[] 密文字节数组
* */
public byte[] getEncryptedPassword(String password, byte[] salt, int iterations, int derivedKeyLength) throws NoSuchAlgorithmException, InvalidKeySpecException {
KeySpec spec = new PBEKeySpec(password.toCharArray(), salt, iterations, derivedKeyLength*4);
SecretKeyFactory f = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
return f.generateSecret(spec).getEncoded();
}
/**
* 字节数组转string方法
* */
public 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;
}
}
测试类:
package com.main;
import com.service.Encryption;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
public class Yum_main {
public static void main(String[] args) throws InvalidKeySpecException, NoSuchAlgorithmException {
Encryption encryption = new Encryption();
byte [] outs = encryption.getEncryptedPassword("123456", "xa12345ksvsl".getBytes(), 16, 128);
System.out.println(encryption.toHex(outs));
}
}
布施恩德可便相知重
微信扫一扫打赏
支付宝扫一扫打赏