Skip to content

Instantly share code, notes, and snippets.

@jimdigriz
Last active September 26, 2022 14:11
Show Gist options
  • Save jimdigriz/846c9b6236f482e033aa15b97dc15f3a to your computer and use it in GitHub Desktop.
Save jimdigriz/846c9b6236f482e033aa15b97dc15f3a to your computer and use it in GitHub Desktop.
HKDF implementation in Erlang
% https://www.rfc-editor.org/rfc/rfc5869
% https://en.wikipedia.org/wiki/HKDF#Example:_Python_implementation
-define(HASH_LENGTH, 32). % maps:get(size, crypto:hash_info(sha256))
hkdf(Length, IKM, Salt0, Info) when not is_list(Salt0) andalso not is_binary(Salt0); Salt0 == []; Salt0 == <<>> ->
Salt = binary:copy(<<0>>, ?HASH_LENGTH),
hkdf(Length, IKM, Salt, Info);
hkdf(Length, IKM, Salt, Info) ->
PRK = crypto:mac(hmac, sha256, Salt, IKM),
hkdf(Length, IKM, Salt, Info, PRK, <<>>, <<>>, 0).
hkdf(Length, _IKM, _Salt, _Info, _PRK, _T0, OKM, I) when I == ceil(Length / ?HASH_LENGTH) ->
binary:part(OKM, 0, Length);
hkdf(Length, IKM, Salt, Info, PRK, T0, OKM, I0) ->
I = I0 + 1,
T = crypto:mac(hmac, sha256, PRK, <<T0/binary, Info/binary, I>>),
hkdf(Length, IKM, Salt, Info, PRK, T, <<OKM/binary, T/binary>>, I).
% binary:decode_hex(<<"3cb25f25faacd57a90434f64d0362f2a2d2d0a90cf1a5a4c5db02d56ecc4c5bf34007208d5b887185865">>) == hkdf(42, binary:decode_hex(<<"0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b">>), binary:decode_hex(<<"000102030405060708090a0b0c">>), binary:decode_hex(<<"f0f1f2f3f4f5f6f7f8f9">>)).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment