From c368af95764afe4241bf248e52f8092de9a92514 Mon Sep 17 00:00:00 2001 From: Marc Worrell Date: Tue, 27 Oct 2026 09:48:19 +0100 Subject: [PATCH] Add support for 'y$' PHP hashing --- README.md | 29 ++++++++++++- c_src/bcrypt.c | 3 +- src/bcrypt.app.src | 2 +- src/bcrypt.erl | 16 ++++++- test/bcrypt_native_tests.c | 6 +++ test/bcrypt_security_tests.erl | 79 ++++++++++++++++++++++++++++++++++ 6 files changed, 130 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 913db36..1a36641 100644 --- a/README.md +++ b/README.md @@ -192,13 +192,40 @@ following OpenBSD bcrypt. Passwords up to 1,024 bytes are accepted; longer inputs return `{error, invalid_password_length}`. Malformed salts return `{error, invalid_salt}`. These rules apply to both the NIF and port backends. -`$2b$` rejects embedded NUL bytes with `{error, invalid_password}`. Pass text +`$2b$` and `$2y$` reject embedded NUL bytes with `{error, invalid_password}`. Pass text passwords as encoded bytes; do not pass raw binary prehashes containing NULs. Existing `$2a$` hashes retain historical password-length wraparound and NUL termination semantics for verification. After a successful legacy verification, generate a fresh salt and rehash with `$2b$`; do not just change the prefix. Legacy hashes affected by those behaviors may warrant a password reset. +PHP `$2y$` hashes are supported by both backends with the same hashing +semantics as `$2b$`. Pass the stored hash directly to `bcrypt:hashpw/2`; +the returned hash retains `$2y$`, so the usual verification pattern works +without rewriting stored prefixes: + +```erlang +%% StoredHash is the PHP hash as a byte list; Password contains the same +%% encoded bytes used in PHP (for example, a UTF-8 binary). +{ok, StoredHash} =:= bcrypt:hashpw(Password, StoredHash). +``` + +`gen_salt/0` and `gen_salt/1` generate `$2b$` salts. To generate a PHP +`$2y$` hash directly, select the version with `gen_salt(Rounds, Version)`: + +```erlang +{ok, Salt} = bcrypt:gen_salt(12, '2y'), +{ok, PhpHash} = bcrypt:hashpw(<<"password">>, Salt). +``` + +The version must be the atom `'2b'` or `'2y'`, and the cost must be an integer +from 4 to 31. Invalid options raise `function_clause`, as with `gen_salt/1`. +The option works with both backends. `PhpHash` retains `$2y$` and can be +verified using PHP's `password_verify()`. + +The same 1,024-byte input limit and NUL-byte rejection apply to `$2y$`; +`$2x$` remains unsupported. + The NIF uses OTP dirty CPU schedulers. Its asynchronous `hashpw/5` interface uses an Erlang helper process and an opaque reference from `create_ctx/0`; there are no custom native threads, task queues, or blocking destructors. diff --git a/c_src/bcrypt.c b/c_src/bcrypt.c index d5a0e2a..bccb6cf 100644 --- a/c_src/bcrypt.c +++ b/c_src/bcrypt.c @@ -78,6 +78,7 @@ bcrypt_hashpass(const char *key, const char *salt, char *encrypted, key_len = (u_int8_t)(strlen(key) + 1); break; case 'b': + case 'y': /* PHP/crypt_blowfish: identical to $2b$. */ /* strlen() returns a size_t, but the function calls * below result in implicit casts to a narrower integer * type, so cap key_len at the actual maximum supported @@ -271,7 +272,7 @@ int bcrypt_hash(char *out, size_t outlen, const unsigned char *password, memchr(salt, 0, salt_len) != NULL) return BCRYPT_INVALID_SALT; /* Preserve historical C-string behavior only for legacy verification. */ - if (salt[2] == 'b' && password_len && + if ((salt[2] == 'b' || salt[2] == 'y') && password_len && memchr(password, 0, password_len) != NULL) return BCRYPT_INVALID_PASSWORD; if (password_len) diff --git a/src/bcrypt.app.src b/src/bcrypt.app.src index 27cf202..06485f0 100644 --- a/src/bcrypt.app.src +++ b/src/bcrypt.app.src @@ -22,7 +22,7 @@ {exclude_files, [ "priv/bcrypt" ]}, - {maintainers, ["Hunter Morris", "Mrinal Wadhwa", "ErlangPack"]}, + {maintainers, ["ErlangPack"]}, {licenses, ["MIT"]}, {links, [{"Github", "https://github.com/erlangpack/bcrypt"}]} ]}. diff --git a/src/bcrypt.erl b/src/bcrypt.erl index 7674a01..2cf9145 100644 --- a/src/bcrypt.erl +++ b/src/bcrypt.erl @@ -7,14 +7,15 @@ %% API -export([start/0, stop/0]). -export([mechanism/0]). --export([gen_salt/0, gen_salt/1, hashpw/2, is_worker_available/0]). +-export([gen_salt/0, gen_salt/1, gen_salt/2, hashpw/2, is_worker_available/0]). -type mechanism() :: nif | port. -type rounds() :: 4..31. +-type version() :: '2b' | '2y'. -type pwerr() :: invalid_salt | invalid_salt_length | invalid_rounds | invalid_password | invalid_password_length. --export_type([ mechanism/0, rounds/0, pwerr/0 ]). +-export_type([ mechanism/0, rounds/0, version/0, pwerr/0 ]). %% @doc Starts `Application' `bcrypt'. %% See also: @@ -52,6 +53,17 @@ gen_salt() -> gen_salt(Rounds) when is_integer(Rounds), Rounds < 32, Rounds > 3 -> do_gen_salt(mechanism(), Rounds). +%% @doc Generate a random salt with an explicit version. Use '2y' for PHP; +%% gen_salt/0 and gen_salt/1 default to '2b'. +-spec gen_salt(rounds(), version()) -> {ok, [byte()]}. +gen_salt(Rounds, '2b') -> + gen_salt(Rounds); +gen_salt(Rounds, '2y') -> + %% Both versions have identical salt encoding. Reuse the backend's secure + %% random generation and select the prefix before any password is hashed. + {ok, "$2b$" ++ Salt} = gen_salt(Rounds), + {ok, "$2y$" ++ Salt}. + %% @doc Make hash string based on `Password' and `Salt'. -spec hashpw( Password, Salt ) -> Result when diff --git a/test/bcrypt_native_tests.c b/test/bcrypt_native_tests.c index 09e3ec2..963e792 100644 --- a/test/bcrypt_native_tests.c +++ b/test/bcrypt_native_tests.c @@ -8,6 +8,7 @@ int main(void) unsigned char password[1025]; unsigned char salt[1024]; const unsigned char valid[] = "$2b$04$......................"; + const unsigned char php_salt[] = "$2y$04$......................"; char output[BCRYPT_HASHSIZE]; memset(password, 'A', sizeof(password)); memset(salt, '.', sizeof(salt)); @@ -31,9 +32,14 @@ int main(void) assert(bcrypt_hash(output, sizeof(output), password, 72, salt, 29) == BCRYPT_INVALID_SALT); } + assert(bcrypt_hash(output, sizeof(output), password, 1024, + php_salt, 29) == BCRYPT_OK); + assert(strlen(output) == 60 && strncmp(output, "$2y$", 4) == 0); password[0] = 0; assert(bcrypt_hash(output, sizeof(output), password, 72, valid, 29) == BCRYPT_INVALID_PASSWORD); + assert(bcrypt_hash(output, sizeof(output), password, 72, + php_salt, 29) == BCRYPT_INVALID_PASSWORD); bcrypt_clear(password, sizeof(password)); for (size_t i = 0; i < sizeof(password); i++) assert(password[i] == 0); diff --git a/test/bcrypt_security_tests.erl b/test/bcrypt_security_tests.erl index 665275f..eeaa260 100644 --- a/test/bcrypt_security_tests.erl +++ b/test/bcrypt_security_tests.erl @@ -2,6 +2,7 @@ -include_lib("eunit/include/eunit.hrl"). -define(SALT, <<"$2b$04$......................">>). +-define(PHP_SALT, <<"$2y$04$......................">>). -define(LEGACY_SALT, <<"$2a$04$......................">>). security_test_() -> @@ -10,7 +11,12 @@ security_test_() -> fun(_) -> application:stop(bcrypt) end, fun(_) -> [ ?_test(default_version()), + ?_test(explicit_salt_version()), + ?_test(invalid_salt_options()), ?_test(known_vectors()), + ?_test(php_vectors()), + ?_test(php_length_boundaries()), + ?_test(php_invalid_inputs()), ?_test(length_boundaries()), ?_test(legacy_verification()), ?_test(nul_passwords()), @@ -33,6 +39,30 @@ default_version() -> {ok, "$2b$04$" ++ Encoded} = bcrypt:gen_salt(4), ?assertEqual(22, length(Encoded)). +explicit_salt_version() -> + lists:foreach(fun({Version, Prefix}) -> + %% Check cost boundaries without attempting an expensive cost-31 hash. + lists:foreach(fun(Rounds) -> + {ok, Salt} = bcrypt:gen_salt(Rounds, Version), + ExpectedPrefix = lists:flatten(io_lib:format("~s~2..0B$", [Prefix, Rounds])), + ?assert(lists:prefix(ExpectedPrefix, Salt)), + ?assertEqual(29, length(Salt)) + end, [4, 12, 31]), + {ok, Salt} = bcrypt:gen_salt(4, Version), + {ok, Hash} = bcrypt:hashpw(<<"password">>, Salt), + ?assert(lists:prefix(Prefix, Hash)), + ?assertEqual({ok, Hash}, bcrypt:hashpw(<<"password">>, Hash)), + ?assertNotEqual({ok, Hash}, bcrypt:hashpw(<<"wrong">>, Hash)) + end, [{'2b', "$2b$"}, {'2y', "$2y$"}]). + +invalid_salt_options() -> + %% Invalid options follow gen_salt/1's existing function_clause behavior. + lists:foreach(fun(Args) -> + ?assertError(function_clause, apply(bcrypt, gen_salt, Args)) + end, [[4, '2a'], [4, '2x'], [4, "2y"], [4, <<"2y">>], + [3, '2b'], [32, '2b'], [3, '2y'], [32, '2y'], [4.0, '2y']]), + ?assertMatch({ok, "$2b$04$" ++ _}, bcrypt:gen_salt(4)). + known_vectors() -> %% Published Openwall vectors; $2b$ agrees with $2a$ for these inputs. Salt = "$2b$05$CCCCCCCCCCCCCCCCCCCCC.", @@ -42,6 +72,55 @@ known_vectors() -> {"U*U", "E5YPO9kmyuRGyh0XouQYb4YMJKvyOeW"}, {"U*U*", "VGOzA784oUp/Z0DY336zx7pLYAy0lwK"}]). +php_vectors() -> + %% Generated with PHP 8.5.9 crypt($password, '$2y$04$......................'). + %% Fixed fixtures keep PHP out of the test/runtime dependencies. + Vectors = [ + {<<>>, "w74bL5gU7LSJClZClCa.Pkz14aTv/XO"}, + {<<"password">>, "LAtw7/ohmmBAhnXqmkuIz83Rl5Qdjhm"}, + {<<"pässwörd"/utf8>>, "qnB8eqNMuizEQ3mLqW93JYyN8aQz3iO"}, + {<<255, 128, 163>>, "Ob6ydY8/tzRw2F.YD8ZfQe6VkpynLsi"} + ], + lists:foreach(fun({Password, Suffix}) -> + Expected = binary_to_list(?PHP_SALT) ++ Suffix, + %% Both a salt and a stored hash must preserve the $2y$ prefix. + ?assertEqual({ok, Expected}, bcrypt:hashpw(Password, ?PHP_SALT)), + ?assertEqual({ok, Expected}, bcrypt:hashpw(Password, Expected)), + ?assertEqual({ok, Expected}, + bcrypt:hashpw(binary_to_list(Password), list_to_binary(Expected))), + ?assertNotEqual({ok, Expected}, bcrypt:hashpw(<<"wrong">>, Expected)), + ?assertEqual({ok, binary_to_list(?SALT) ++ Suffix}, + bcrypt:hashpw(Password, ?SALT)) + end, Vectors). + +php_length_boundaries() -> + Password = <<"A", (binary:copy(<<"B">>, 1023))/binary>>, + %% PHP reference outputs for 71 bytes and for 72 or more bytes. + Short = binary_to_list(?PHP_SALT) ++ "HngKtCj1MUdG5WavwdNXo.lTVlWjsba", + Long = binary_to_list(?PHP_SALT) ++ "G0G3HvI30KYH1y5QpphZX4Y4p0vztu6", + ?assertEqual({ok, Short}, + bcrypt:hashpw(binary:part(Password, 0, 71), ?PHP_SALT)), + lists:foreach(fun(N) -> + P = binary:part(Password, 0, N), + ?assertEqual({ok, Long}, bcrypt:hashpw(P, ?PHP_SALT)), + ?assertEqual({ok, Long}, bcrypt:hashpw(P, Long)) + end, [72, 73, 254, 255, 256, 257, 511, 512, 1023, 1024]). + +php_invalid_inputs() -> + lists:foreach(fun(Password) -> + ?assertEqual({error, invalid_password}, + bcrypt:hashpw(Password, ?PHP_SALT)) + end, [<<0>>, <<"abc", 0, "def">>, <<"abc", 0>>, + <<(binary:copy(<<"A">>, 72))/binary, 0>>]), + ?assertEqual({error, invalid_password_length}, + bcrypt:hashpw(binary:copy(<<"A">>, 1025), ?PHP_SALT)), + lists:foreach(fun(Salt) -> + ?assertEqual({error, invalid_salt}, bcrypt:hashpw(<<"test">>, Salt)) + end, [<<"$2y$04$">>, <<"$2y$03$......................">>, + <<"$2y$32$......................">>, + <<"$2y$4x$......................">>, + <<"$2y$04$!!!!!!!!!!!!!!!!!!!!!!">>]). + length_boundaries() -> %% $2b$ consumes the first 72 bytes, without an 8-bit length wrap. Password = <<"A", (binary:copy(<<"B">>, 1023))/binary>>,