From f4665e43e858a6695585fd0350ceebad150e57b6 Mon Sep 17 00:00:00 2001 From: Jonathan Almeida Date: Wed, 24 May 2017 18:28:07 -0400 Subject: [PATCH] Add a backward compatible way of getting random bytes --- src/websocket_client.erl | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/src/websocket_client.erl b/src/websocket_client.erl index 07489fc..2591993 100644 --- a/src/websocket_client.erl +++ b/src/websocket_client.erl @@ -241,7 +241,7 @@ error_info(Handler, Reason, State) -> -spec generate_ws_key() -> binary(). generate_ws_key() -> - base64:encode(crypto:strong_rand_bytes(16)). + base64:encode(rand_bytes(16)). %% @doc Validate handshake response challenge -spec validate_handshake(HandshakeResponse :: binary(), Key :: binary()) -> {ok, binary()} | {error, term()}. @@ -430,7 +430,7 @@ encode_frame({Type, Payload}) -> Opcode = websocket_req:name_to_opcode(Type), Len = iolist_size(Payload), BinLen = payload_length_to_binary(Len), - MaskingKeyBin = crypto:strong_rand_bytes(4), + MaskingKeyBin = rand_bytes(4), << MaskingKey:32 >> = MaskingKeyBin, Header = << 1:1, 0:3, Opcode:4, 1:1, BinLen/bits, MaskingKeyBin/bits >>, MaskedPayload = mask_payload(MaskingKey, Payload), @@ -482,3 +482,12 @@ set_continuation_if_empty(WSReq, Opcode) -> _ -> WSReq end. + +rand_bytes(N) -> + case has_crypto_strong_rand_bytes() of + true -> crypto:strong_rand_bytes(N); + false -> (fun crypto:rand_bytes/1)(N) + end. + +has_crypto_strong_rand_bytes() -> + erlang:function_exported(crypto, strong_rand_bytes, 1).