sdlan/src/sdlan_cipher.erl
2026-04-02 14:26:48 +08:00

81 lines
2.4 KiB
Erlang

%%%-------------------------------------------------------------------
%%% @author anlicheng
%%% @copyright (C) 2024, <COMPANY>
%%% @doc
%%%
%%% @end
%%% Created : 11. 3月 2024 11:07
%%%-------------------------------------------------------------------
-module(sdlan_cipher).
-author("anlicheng").
%% API
-export([rsa_encrypt/2, rsa_pem_decode/1]).
-export([aes_encrypt/3, aes_decrypt/3]).
-export([test/0, test_chacha20/0]).
test() ->
Key = <<"abcdabcdabcdabcd">>,
X = aes_encrypt(Key, Key, <<"hello world">>),
logger:debug("x is: ~p, raw: ~p", [X, aes_decrypt(Key, Key, X)]),
ok.
-spec rsa_pem_decode(PubKey :: binary()) -> public_key:rsa_public_key().
rsa_pem_decode(PubKey) when is_binary(PubKey) ->
[PubPem] = public_key:pem_decode(PubKey),
public_key:pem_entry_decode(PubPem).
%% 加密数据
-spec rsa_encrypt(binary(), public_key:rsa_public_key()) -> binary().
rsa_encrypt(BinData, PublicKey) when is_binary(BinData) ->
public_key:encrypt_public(BinData, PublicKey, [{rsa_padding, rsa_pkcs1_padding}]).
%% 基于aes的加密算法
-spec aes_encrypt(binary(), binary(), binary()) -> binary().
aes_encrypt(Key, IVec, PlainText) when is_binary(Key), is_binary(IVec), is_binary(PlainText) ->
crypto:crypto_one_time(aes_128_ofb, Key, IVec, PlainText, [{encrypt, true}, {padding, pkcs_padding}]).
%% 基于aes的解密算法
-spec aes_decrypt(binary(), binary(), binary()) -> binary().
aes_decrypt(Key, IVec, CipherText) when is_binary(Key), is_binary(IVec), is_binary(CipherText) ->
crypto:crypto_one_time(aes_128_ofb, Key, IVec, CipherText, [{encrypt, false}, {padding, pkcs_padding}]).
test_chacha20() ->
Key = crypto:strong_rand_bytes(32),
Nonce = crypto:strong_rand_bytes(12),
PlainText = <<"hello world">>,
Enc = chacha20_encrypt(Key, Nonce, PlainText),
Ex = chacha20_decrypt(Key, Enc),
logger:debug("yes ex is: ~p", [Ex]),
ok.
chacha20_encrypt(Key, Nonce, Plain) ->
AAD = <<>>,
{Cipher, Tag} = crypto:crypto_one_time_aead(
chacha20_poly1305,
Key,
Nonce,
Plain,
AAD,
true
),
<<Nonce/binary, Cipher/binary, Tag/binary>>.
chacha20_decrypt(Key, <<Nonce:12/binary, Rest/binary>>) ->
AAD = <<>>,
CipherLen = byte_size(Rest) - 16,
<<Cipher:CipherLen/binary, Tag:16/binary>> = Rest,
crypto:crypto_one_time_aead(
chacha20_poly1305,
Key,
Nonce,
Cipher,
AAD,
Tag,
false
).