|
@@ -0,0 +1,41 @@
|
|
|
+-module(n4u_secret).
|
|
|
+
|
|
|
+-export([pickle/1, depickle/1, secret/0]).
|
|
|
+
|
|
|
+
|
|
|
+% n4u hmac aes/cbc-128 && aes/gcm-256
|
|
|
+
|
|
|
+pickle(Data) ->
|
|
|
+ %Message = erlang:term_to_binary({Data, os:timestamp()}),
|
|
|
+ Message = erlang:term_to_binary(Data),
|
|
|
+ Padding = erlang:size(Message) rem 16,
|
|
|
+ Bits = (16 - Padding) * 8,
|
|
|
+ Key = secret(),
|
|
|
+ IV = crypto:strong_rand_bytes(16),
|
|
|
+ Cipher = crypto:crypto_one_time(aes_128_cbc, Key, IV, <<Message/binary, 0:Bits>>, true), % encrypt
|
|
|
+ Signature = crypto:mac(application:get_env(n4u, mac_type, hmac),
|
|
|
+ application:get_env(n4u, mac_subtype, sha256),
|
|
|
+ Key, <<Cipher/binary, IV/binary>>),
|
|
|
+ %base64:encode(<<IV/binary, Signature/binary, Cipher/binary>>).
|
|
|
+ nitro:hex(<<IV/binary, Signature/binary, Cipher/binary>>).
|
|
|
+
|
|
|
+
|
|
|
+depickle(PickledData) ->
|
|
|
+ try Key = secret(),
|
|
|
+ %Decoded = base64:decode(nitro:to_binary(PickledData)),
|
|
|
+ Decoded = nitro:unhex(erlang:iolist_to_binary(PickledData)),
|
|
|
+ <<IV:16/binary, Signature:32/binary, Cipher/binary>> = Decoded,
|
|
|
+ Signature = crypto:mac(application:get_env(n4u, mac_type, hmac),
|
|
|
+ application:get_env(n4u, mac_subtype, sha256),
|
|
|
+ Key, <<Cipher/binary, IV/binary>>),
|
|
|
+ %{Data, _Time} = erlang:binary_to_term(crypto:block_decrypt(aes_cbc128, Key, IV, Cipher), [safe]),
|
|
|
+ %Data
|
|
|
+ erlang:binary_to_term(crypto:crypto_one_time(aes_128_cbc, Key, IV, Cipher, false), [safe]) % decrypt
|
|
|
+ catch _E:_R ->
|
|
|
+ %wf:info(?MODULE, "Depicke Error: ~p ~p", [_E, _R]),
|
|
|
+ <<"">>
|
|
|
+ end.
|
|
|
+
|
|
|
+
|
|
|
+secret() -> application:get_env(n4u, secret, <<"ThisIsClassified">>).
|
|
|
+
|