From d6a9e6a3ac1078a4063f52924c26513e03888d19 Mon Sep 17 00:00:00 2001 From: anlicheng <244108715@qq.com> Date: Tue, 17 Mar 2026 14:38:45 +0800 Subject: [PATCH] add chacha20 --- apps/sdlan/src/sdlan_cipher.erl | 44 +++++++++++++++++++++++++++++++-- message.proto | 8 ++++-- 2 files changed, 48 insertions(+), 4 deletions(-) diff --git a/apps/sdlan/src/sdlan_cipher.erl b/apps/sdlan/src/sdlan_cipher.erl index 3dcc281..59a0484 100644 --- a/apps/sdlan/src/sdlan_cipher.erl +++ b/apps/sdlan/src/sdlan_cipher.erl @@ -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">>, @@ -38,4 +38,44 @@ aes_encrypt(Key, IVec, PlainText) when is_binary(Key), is_binary(IVec), is_binar %% 基于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}]). \ No newline at end of file + 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 + ), + <>. + +chacha20_decrypt(Key, <>) -> + AAD = <<>>, + CipherLen = byte_size(Rest) - 16, + <> = Rest, + crypto:crypto_one_time_aead( + chacha20_poly1305, + Key, + Nonce, + Cipher, + AAD, + Tag, + false + ). \ No newline at end of file diff --git a/message.proto b/message.proto index 0d2637c..e21e3cf 100644 --- a/message.proto +++ b/message.proto @@ -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 {