Java和PHP(Laravel)的Bcrypt加密兼容

[版权声明] 本站内容采用 知识共享署名-非商业性使用-相同方式共享 3.0 中国大陆 (CC BY-NC-SA 3.0 CN) 进行许可。
部分内容和资源来自网络,纯学习研究使用。如有侵犯您的权益,请及时联系我,我将尽快处理。
如转载请注明来自: Dreamlike博客,本文链接: Java和PHP(Laravel)的Bcrypt加密兼容

后端早期使用的是Laravel构建的,用户系统的密码加密方式用的是原生的语法:password_hash

现在需要部分业务用到Java做用户验证,这里就涉及到密码验证的兼容问题。先来用spring security的BCryptPasswordEncoder测试一下:

发现测试通不过。网上查了下password_hash()默认的加密算法是CRYPT_BLOWFISH官方文档有这样一段描述:

  • CRYPT_BLOWFISH - Blowfish hashing with a salt as follows: "$2a$", "$2x$" or "$2y$", a two digit cost parameter, "$", and 22 characters from the alphabet "./0-9A-Za-z". Using characters outside of this range in the salt will cause crypt() to return a zero-length string. The two digit cost parameter is the base-2 logarithm of the iteration count for the underlying Blowfish-based hashing algorithmeter and must be in range 04-31, values outside this range will cause crypt() to fail. Versions of PHP before 5.3.7 only support "$2a$" as the salt prefix: PHP 5.3.7 introduced the new prefixes to fix a security weakness in the Blowfish implementation. Please refer to » this document for full details of the security fix, but to summarise, developers targeting only PHP 5.3.7 and later should use "$2y$" in preference to "$2a$".

可以发现二者之间的区别在于字符串开头 $2a$ 与 $2y$。大意是$2y$开头的是新版本的安全修复。Java仅支持$2a$。

其实解决方法很简单,在判断之前,用正则把$2y$改成$2a$,然后进行判断:

参考链接:《How to calculate in java a Bcrypt password compatible with Laravel

如果本文对您有所帮助,可以请作者喝杯咖啡,感谢支持^_^

支付宝支付
微信支付

发表评论

电子邮件地址不会被公开。 必填项已用*标注