%%%-------------------------------------------------------------------
%%% @author aresei
%%% @copyright (C) 2018, <COMPANY>
%%% @doc
%%% 采用的RSA 2048 PKCS1
%%% @end
%%% Created : 21. 六月 2018 09:51
%%%-------------------------------------------------------------------
-module(iot_cipher_rsa).
-author("aresei").

%% API
-export([encode/2, decode/2, private_encode/2]).

%% 解密数据
decode(Data, PrivateKey) when is_binary(Data), is_binary(PrivateKey) ->
    [Pri] = public_key:pem_decode(PrivateKey),
    PriKeyEntry = public_key:pem_entry_decode(Pri),
    public_key:decrypt_private(Data, PriKeyEntry).

%% 解密数据
encode(Data, PublicKey) when is_map(Data), is_binary(PublicKey) ->
    BinData = jiffy:encode(Data, [force_utf8]),
    encode(BinData, PublicKey);

encode(Data, PublicKey) when is_binary(Data), is_binary(PublicKey) ->
    [Pub] = public_key:pem_decode(PublicKey),
    PubKey = public_key:pem_entry_decode(Pub),
    public_key:encrypt_public(Data, PubKey).

private_encode(Data, PrivateKey) when is_binary(Data), is_binary(PrivateKey) ->
    [Private] = public_key:pem_decode(PrivateKey),
    PriKey = public_key:pem_entry_decode(Private),
    public_key:encrypt_private(Data, PriKey).