如何解决如何使用java解密php yii加密密码
在 yii2 中使用 generatePasswordHash 和 validatePassword 像这样验证密码。 加密后用password_hash存储在DB中
$2y$13$1hVeVwvuKQUE.kJfaQLje.b8iLlTauTOksddD5Gqn6UC416NsnAR2
auth_key oEx6MM0pGs6jHvApr2anxJEINpTpqGUO
现在如何使用java来验证密码? auth_key是什么意思,verify不需要输入auth_key。
解决方法
您所需要的只是在 Java 中创建您的自定义类,并从 PHP 类 \yii\base\Security
(source is here) 进行转换。关于身份验证密钥这个问题已经问过here in SO
终于用下面的方法解决了,棘手的部分是替换标题。
公共类 CheckPassword {
public static boolean checkPassword(String passwordText,String DbHash) {
boolean password_verified = false;
if (null != DbHash) {
if (DbHash.startsWith("$2y$")) {
DbHash = "$2a$" + DbHash.substring(4);
}
}
if (null == DbHash || !DbHash.startsWith("$2a$")) {
throw new java.lang.IllegalArgumentException("Invalid hash provided for comparison");
}
password_verified = BCrypt.checkpw(passwordText,DbHash);
return (password_verified);
}
public static void main(String[] args) {
CheckPassword.checkPassword("xxxxx","$2y$13$5mqgv2wZve89Bz.g1MUcg.7xNich7/nxxxxxxxxxx");
try {
String salt = getSalt();
System.out.println("salt:" + salt);//获取salt
String miwen = getPBKDF2("111",salt); //明文密码加密
System.out.println("miwen:" + miwen);
System.out.println(salt + miwen);
System.out.println(verify("111",salt + miwen));//解密
} catch (Exception e) {
e.printStackTrace();
}
}
public static final String PBKDF2_ALGORITHM = "PBKDF2WithHmacSHA1";
//盐的长度
public static final int SALT_SIZE = 16;
//生成密文的长度
public static final int HASH_SIZE = 16;
// 迭代次数
public static final int PBKDF2_ITERATIONS = 1000;
/**
* 对输入的密码进行验证
* password 密码明文
* dataPassWord 密码加密
*/
public static boolean verify(String password,String dataPassWord)
throws NoSuchAlgorithmException,InvalidKeySpecException {
// 用相同的盐值对用户输入的密码进行加密
String result = getPBKDF2(password,dataPassWord.substring(0,16));
// 把加密后的密文和原密文进行比较,相同则验证成功,否则失败
return result.equals(dataPassWord.substring(16,dataPassWord.length()));
}
/**
* 根据password和salt生成密文
*/
public static String getPBKDF2(String password,String salt) throws NoSuchAlgorithmException,InvalidKeySpecException {
//将16进制字符串形式的salt转换成byte数组
byte[] bytes = DatatypeConverter.parseHexBinary(salt);
KeySpec spec = new PBEKeySpec(password.toCharArray(),bytes,PBKDF2_ITERATIONS,HASH_SIZE * 4);
SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(PBKDF2_ALGORITHM);
byte[] hash = secretKeyFactory.generateSecret(spec).getEncoded();
//将byte数组转换为16进制的字符串
return DatatypeConverter.printHexBinary(hash);
}
/**
* 生成随机盐值
*/
public static String getSalt() throws NoSuchAlgorithmException {
SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
byte[] bytes = new byte[SALT_SIZE / 2];
random.nextBytes(bytes);
//将byte数组转换为16进制的字符串
String salt = DatatypeConverter.printHexBinary(bytes);
return salt;
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。