%%%-------------------------------------------------------------------
%%% @author aresei
%%% @copyright (C) 2018, <COMPANY>
%%% @doc
%%%
%%% @end
%%% Created : 29. 六月 2018 09:30
%%%-------------------------------------------------------------------
-module(iot_cipher_aes).
-author("aresei").

%% API
-export([encrypt/2, decrypt/2]).
-export([test/0]).

test() ->
    Aes = list_to_binary(iot_util:rand_bytes(32)),
    Enc = encrypt(Aes, <<"sdfsff hesdfs sfsdfsdffffffffffxyz yes call me">>),
    Data = decrypt(Aes, Enc),

    lager:debug("enc: ~p, size: ~p, data len is: ~p, data: ~p", [Enc, byte_size(Enc), byte_size(Data), Data]).

%% 基于aes的加密算法, aes_256_cbc
-spec encrypt(binary(), binary()) -> binary().
encrypt(Key, PlainText) when is_binary(Key), is_binary(PlainText) ->
    IV = binary:part(Key, {0, 16}),
    crypto:crypto_one_time(aes_256_cbc, Key, IV, PlainText, [{encrypt, true}, {padding, pkcs_padding}]).

%% 基于aes的解密算法
-spec decrypt(binary(), binary()) -> binary().
decrypt(Key, CipherText) when is_binary(Key), is_binary(CipherText) ->
    IV = binary:part(Key, {0, 16}),
    crypto:crypto_one_time(aes_256_cbc, Key, IV, CipherText, [{encrypt, false}, {padding, pkcs_padding}]).