add chacha20

This commit is contained in:
anlicheng 2026-03-17 14:38:45 +08:00
parent c28699bc08
commit d6a9e6a3ac
2 changed files with 48 additions and 4 deletions

View File

@ -12,7 +12,7 @@
%% API
-export([rsa_encrypt/2, rsa_pem_decode/1]).
-export([aes_encrypt/3, aes_decrypt/3]).
-export([test/0]).
-export([test/0, test_chacha20/0]).
test() ->
Key = <<"abcdabcdabcdabcd">>,
@ -39,3 +39,43 @@ aes_encrypt(Key, IVec, PlainText) when is_binary(Key), is_binary(IVec), is_binar
-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
).

View File

@ -53,8 +53,12 @@ message SDLRegisterSuper {
// quic去通讯session_token校验
message SDLRegisterSuperAck {
uint32 pkt_id = 1;
bytes aes_key = 2;
bytes session_token = 3;
// aes, chacha20
string algorithm = 2;
bytes key = 3;
// chacha20加密算法需要使用该字段
uint32 region_id = 4;
bytes session_token = 5;
}
message SDLRegisterSuperNak {