[erlang-questions] hmac sha256 erlang

Steve Davis steven.charles.davis@REDACTED
Fri May 6 14:52:47 CEST 2011


On May 6, 3:00 am, Paolo Negri <paolo.ne...@REDACTED> wrote:
> I'd like also to know if someone is aware of an hmac sha-256
> implementation built on top of this library.

For HMAC-NNN with the sha2 library, you can do something like...

% HMAC SHA
-define(SHA_224_BLOCKSIZE, 64).
-define(SHA_256_BLOCKSIZE, 64).
-define(SHA_384_BLOCKSIZE, 128).
-define(SHA_512_BLOCKSIZE, 128).

% HMAC test vectors at http://tools.ietf.org/html/rfc4231
hmac(Key, Data) ->
	crypto:sha_mac(Key, Data).
hmac224(Key, Data) ->
	hmac(Key, Data, fun sha2:hexdigest224/1, ?SHA_224_BLOCKSIZE).
hmac256(Key, Data) ->
	hmac(Key, Data, fun sha2:hexdigest256/1, ?SHA_256_BLOCKSIZE).
hmac384(Key, Data) ->
	hmac(Key, Data, fun sha2:hexdigest384/1, ?SHA_384_BLOCKSIZE).
hmac512(Key, Data) ->
	hmac(Key, Data, fun sha2:hexdigest512/1, ?SHA_512_BLOCKSIZE).
%
hmac(Key, Data, Hash, Blocksize) when is_binary(Key), is_binary(Data) -
>
	HashKey =
		case Blocksize - byte_size(Key) of
		X when X < 0 ->
			KeyDigest = Hash(Key),
			Pad = Blocksize - byte_size(KeyDigest),
			<<KeyDigest/binary, 0:(Pad * 8)>>;
		X when X > 0 ->
			<<Key/binary, 0:(X * 8)>>;
		X when X =:= 0 ->
			Key
		end,
	IPad = list_to_binary(lists:duplicate(Blocksize, 16#36)),
	OPad = list_to_binary(lists:duplicate(Blocksize, 16#5c)),
	H1 = Hash(<<(crypto:exor(HashKey, IPad))/binary, Data/binary>>),
	Hash(<<(crypto:exor(HashKey, OPad))/binary, H1/binary>>).



More information about the erlang-questions mailing list