java 实现 PHP password_hash() password_verify() 单向验证

近期一个 php 转 java 项目中遇到。写出来分享一下:

java BCrypt 类库。

https://github.com/patrickfav/bcrypt

 @Test
    public void testBCrypt() {
        String password = "abcd";
        String bcryptHashString = BCrypt.withDefaults().hashToString(12, password.toCharArray());
        System.out.println(bcryptHashString);
// $2a$12$US00g/uMhoSBm.HiuieBjeMtoN69SN.GE25fCpldebzkryUyopws6
        BCrypt.Result result = BCrypt.verifyer().verify(password.toCharArray(), bcryptHashString);
        assert result.verified;
//        String hash = BCrypt.with(customVersion2f).hashToString(10, password.toCharArray());
//        String hash = BCrypt.with(BCrypt.Version.VERSION_2X).hashToString(10, password.toCharArray());
        String hash = BCrypt.with(BCrypt.Version.VERSION_2Y).hashToString(10, password.toCharArray());
        System.out.println(hash);
        //from php
//        hash = "$2y$10$SUr/RXt7IwSALE8x3W25huJDGDKWjBEisXIdS/As7CIqwLMgaUOE.";
//        hash = "$2y$10$L.D2Q/d.7f0/vtJv7KzwXesxjlnAOkjmg/HjS4FXdWLJBE.tBZDSq";
        hash = "$2y$10$gNNdf9tIKD3Sa.XOL/7zreGL9YQwk.d1iFYcOjMy3ab6EFKQ6P2yq";
        //from php 'abCd'
//        hash = "$2y$10$3i/2nXwBYFW353MhCDQJYusVhwlwZHiYKTSA9nm6GB6aiISsYzuXa";
        BCrypt.Result res = BCrypt.verifyer().verify(password.toCharArray(), hash);
        assert res.verified;
    }

php hash 到 java 没有问题

java hash 到 php 需要重新定义一些函数,文档中提到:

For example the PHP implementation of bcrypt will return hashes with version $2y$. By using BCrypt.withDefaults() it will default to version $2a$. The older $2$ version is not supported. For advanced use cases you may add your own version by providing a version identifier and a custom message formatter as well as parser.

Version customVersion2f = new Version(new byte[]{0x32, 0x66} /* 2f */,true ,true, myCustomFormatter, myCustomParser);

 

 

 

 

 

你可能感兴趣的:(java,php)