Created
April 19, 2025 17:10
-
-
Save Staars/b88a1451e0abc057b54db0e833721559 to your computer and use it in GitHub Desktop.
Test implementation chacha_poly
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
int32_t m_chacha20_poly_run(bvm *vm, int32_t _encrypt) { | |
int32_t argc = be_top(vm); // Get the number of arguments | |
if (argc >= 4 && be_isbytes(vm, 1) // secret_key - 32 bytes | |
&& be_isbytes(vm, 2) // iv/nonce - 12 bytes | |
&& be_isbytes(vm, 3) // data/cipher | |
&& be_isbytes(vm, 4) // mac/tag - 16 bytes | |
// optional: aad | |
) { | |
size_t key_len = 0; | |
const void * key = be_tobytes(vm, 1, &key_len); | |
if (key_len != 32) { | |
AddLog(LOG_LEVEL_INFO, PSTR(" %d bytes"), key_len); | |
be_raise(vm, "value_error", "Key size must be 32 bytes"); | |
} | |
size_t iv_len = 0; | |
void * iv = (void *) be_tobytes(vm, 2, &iv_len); | |
if (iv_len != 12) { | |
AddLog(LOG_LEVEL_INFO, PSTR(" %d bytes"), iv_len); | |
be_raise(vm, "value_error", "IV size must be 12"); | |
} | |
size_t data_len = 0; | |
void * data = (void *) be_tobytes(vm, 3, &data_len); | |
size_t mac_len = 0; | |
void * mac = (void *) be_tobytes(vm, 4, &mac_len); | |
if (mac_len != 16) { | |
AddLog(LOG_LEVEL_INFO, PSTR(" %d bytes"), mac_len); | |
be_raise(vm, "value_error", "MAC size must be 16"); | |
} | |
size_t aad_len = 0; | |
void * aad = NULL; | |
if(argc == 5 && be_isbytes(vm, 5)){ | |
aad = (void *) be_tobytes(vm, 5, &aad_len); | |
} | |
char _mac[16]; | |
bbool _success = false; | |
br_chacha20_run bc = br_chacha20_ct_run; | |
br_poly1305_ctmul32_run(key, iv, data, | |
data_len, aad, aad_len, | |
_mac, bc, _encrypt); | |
if (_encrypt==1) { | |
memcpy(mac, _mac, 16); | |
_success = true; | |
} else if (memcmp(mac, _mac, 16) == 0) { | |
_success = true; | |
} | |
memcpy(mac, _mac, 16); | |
be_pushbool(vm, _success); | |
be_return(vm); | |
} | |
be_raise(vm, kTypeError, nullptr); | |
} | |
// `chacha_encrypt1(secret_key:bytes(32),iv:bytes(12),data:bytes(n*16)),tag:bytes(),aad:bytes()-> bool (true) | |
// int32_t m_chacha20_encrypt1(bvm *vm); | |
int32_t m_chacha20_poly_encrypt(bvm *vm) { | |
return m_chacha20_poly_run(vm, 1); | |
} | |
// `chacha_decrypt1(secret_key:bytes(32),iv:bytes(12),cipher:bytes(n*16),tag:bytes()add:bytes())-> bool (true) | |
// int32_t m_chacha20_decrypt1(bvm *vm); | |
int32_t m_chacha20_poly_decrypt(bvm *vm) { | |
return m_chacha20_poly_run(vm, 0); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment