chore: expose chacha20poly1305 size constants
What changed, and why it matters
This commit is a routine code cleanup: it replaces hard-coded numbers like 32, 12, 64, and 16 with named constants for the ChaCha20-Poly1305 encryption algorithm. The behavior of the code does not change; it only becomes easier to read and maintain. There is no security vulnerability being fixed here.
No security action required. Treat as normal maintenance/refactoring.
Security signals we found
No strong security signals were identified.
Evidence from the diff
The change introduces CHACHA20POLY1305_KEY_SIZE (32), RFC7539_NONCE_SIZE (12), CHACHA20POLY1305_BLOCK_SIZE (64), and CHACHA20POLY1305_TAG_SIZE (16) in the crypto headers and exposes them through the MicroPython binding. Existing call sites in Monero, WebAuthn, storage, and benchmarks are updated to use these constants. All numeric values remain identical to the previous literals, so this is a pure refactor with no functional or security behavior change.
Changed components
crypto/chacha20poly1305core/embed/upymod/modtrezorcryptocore/src/apps/monerocore/src/apps/webauthnstorage/storage.cInspect captured patch +88 / −48
### core/embed/upymod/modtrezorcrypto/modtrezorcrypto-chacha20poly1305.h
@@ -29,6 +29,10 @@
/// """
/// ChaCha20Poly1305 context for encryption.
/// """
+/// key_size: int
+/// nonce_size: int
+/// block_size: int
+/// tag_size: int
typedef struct _mp_obj_ChaCha20Poly1305_t {
mp_obj_base_t base;
chacha20poly1305_ctx ctx;
@@ -52,10 +56,10 @@ static mp_obj_t mod_trezorcrypto_ChaCha20Poly1305_make_new(
mp_buffer_info_t key = {0}, nonce = {0};
mp_get_buffer_raise(args[0], &key, MP_BUFFER_READ);
mp_get_buffer_raise(args[1], &nonce, MP_BUFFER_READ);
- if (key.len != 32) {
+ if (key.len != CHACHA20POLY1305_KEY_SIZE) {
mp_raise_ValueError(MP_ERROR_TEXT("Invalid length of key"));
}
- if (nonce.len != 12) {
+ if (nonce.len != RFC7539_NONCE_SIZE) {
mp_raise_ValueError(MP_ERROR_TEXT("Invalid length of nonce"));
}
mp_obj_ChaCha20Poly1305_t *o =
@@ -125,7 +129,7 @@ static mp_obj_t mod_trezorcrypto_ChaCha20Poly1305_encrypt_finish(
o->state = FINISHED;
vstr_t mac = {0};
- vstr_init_len(&mac, 16);
+ vstr_init_len(&mac, CHACHA20POLY1305_TAG_SIZE);
rfc7539_finish(&(o->ctx), o->alen, o->plen, (uint8_t *)mac.buf);
return mp_obj_new_bytes_from_vstr(&mac);
}
@@ -137,6 +141,10 @@ static MP_DEFINE_CONST_FUN_OBJ_1(
/// """
/// ChaCha20Poly1305 context for decryption.
/// """
+/// key_size: int
+/// nonce_size: int
+/// block_size: int
+/// tag_size: int
/// def __init__(self, key: AnyBytes, nonce: AnyBytes) -> None:
/// """
@@ -188,12 +196,12 @@ static mp_obj_t mod_trezorcrypto_ChaCha20Poly1305_decrypt_finish(
o->state = FINISHED;
mp_buffer_info_t exp_mac = {0};
mp_get_buffer_raise(expected_mac, &exp_mac, MP_BUFFER_READ);
- if (exp_mac.len != 16) {
+ if (exp_mac.len != CHACHA20POLY1305_TAG_SIZE) {
mp_raise_ValueError(MP_ERROR_TEXT(
"Invalid length of the expected mac. It has to be 16 bytes."));
}
vstr_t mac = {0};
- vstr_init_len(&mac, 16);
+ vstr_init_len(&mac, CHACHA20POLY1305_TAG_SIZE);
rfc7539_finish(&(o->ctx), o->alen, o->plen, (uint8_t *)mac.buf);
if (!consteq(mac.buf, exp_mac.buf, exp_mac.len)) {
@@ -227,6 +235,11 @@ static const mp_rom_map_elem_t
MP_ROM_PTR(&mod_trezorcrypto_ChaCha20Poly1305_encrypt_finish_obj)},
{MP_ROM_QSTR(MP_QSTR___del__),
MP_ROM_PTR(&mod_trezorcrypto_ChaCha20Poly1305___del___obj)},
+ {MP_ROM_QSTR(MP_QSTR_key_size), MP_ROM_INT(CHACHA20POLY1305_KEY_SIZE)},
+ {MP_ROM_QSTR(MP_QSTR_nonce_size), MP_ROM_INT(RFC7539_NONCE_SIZE)},
+ {MP_ROM_QSTR(MP_QSTR_block_size),
+ MP_ROM_INT(CHACHA20POLY1305_BLOCK_SIZE)},
+ {MP_ROM_QSTR(MP_QSTR_tag_size), MP_ROM_INT(CHACHA20POLY1305_TAG_SIZE)},
};
static MP_DEFINE_CONST_DICT(
mod_trezorcrypto_ChaCha20Poly1305Encrypt_locals_dict,
@@ -242,6 +255,11 @@ static const mp_rom_map_elem_t
MP_ROM_PTR(&mod_trezorcrypto_ChaCha20Poly1305_decrypt_finish_obj)},
{MP_ROM_QSTR(MP_QSTR___del__),
MP_ROM_PTR(&mod_trezorcrypto_ChaCha20Poly1305___del___obj)},
+ {MP_ROM_QSTR(MP_QSTR_key_size), MP_ROM_INT(CHACHA20POLY1305_KEY_SIZE)},
+ {MP_ROM_QSTR(MP_QSTR_nonce_size), MP_ROM_INT(RFC7539_NONCE_SIZE)},
+ {MP_ROM_QSTR(MP_QSTR_block_size),
+ MP_ROM_INT(CHACHA20POLY1305_BLOCK_SIZE)},
+ {MP_ROM_QSTR(MP_QSTR_tag_size), MP_ROM_INT(CHACHA20POLY1305_TAG_SIZE)},
};
static MP_DEFINE_CONST_DICT(
mod_trezorcrypto_ChaCha20Poly1305Decrypt_locals_dict,
### core/mocks/generated/trezorcrypto/__init__.pyi
@@ -201,6 +201,10 @@ class chacha20poly1305_encrypt:
"""
ChaCha20Poly1305 context for encryption.
"""
+ key_size: int
+ nonce_size: int
+ block_size: int
+ tag_size: int
def __init__(self, key: AnyBytes, nonce: AnyBytes) -> None:
"""
@@ -232,6 +236,10 @@ class chacha20poly1305_decrypt:
"""
ChaCha20Poly1305 context for decryption.
"""
+ key_size: int
+ nonce_size: int
+ block_size: int
+ tag_size: int
def __init__(self, key: AnyBytes, nonce: AnyBytes) -> None:
"""
### core/src/apps/benchmark/benchmarks.py
@@ -79,10 +79,18 @@ def verify(self, public_key: bytes, signature: bytes, digest: bytes) -> bool:
lambda: aesgcm_decrypt(random_bytes(32), random_bytes(16)), 16
),
"crypto/cipher/chacha20poly1305/encrypt": EncryptBenchmark(
- lambda: chacha20poly1305_encrypt(random_bytes(32), random_bytes(12)), 64
+ lambda: chacha20poly1305_encrypt(
+ random_bytes(chacha20poly1305_encrypt.key_size),
+ random_bytes(chacha20poly1305_encrypt.nonce_size),
+ ),
+ chacha20poly1305_encrypt.block_size,
),
"crypto/cipher/chacha20poly1305/decrypt": DecryptBenchmark(
- lambda: chacha20poly1305_decrypt(random_bytes(32), random_bytes(12)), 64
+ lambda: chacha20poly1305_decrypt(
+ random_bytes(chacha20poly1305_decrypt.key_size),
+ random_bytes(chacha20poly1305_decrypt.nonce_size),
+ ),
+ chacha20poly1305_decrypt.block_size,
),
"crypto/curve/secp256k1/sign": SignBenchmark(secp256k1),
"crypto/curve/secp256k1/verify": VerifyBenchmark(secp256k1),
### core/src/apps/monero/signing/step_09_sign_input.py
@@ -229,7 +229,7 @@ def _protect_signature(state: State, mg_buffer: list[bytes]) -> list[bytes]:
nonce = offloading_keys.key_signature(
state.opening_key, state.current_input_index, True
- )[:12]
+ )[: chacha20poly1305_encrypt.nonce_size]
key = offloading_keys.key_signature(
state.opening_key, state.current_input_index, False
@@ -240,7 +240,7 @@ def _protect_signature(state: State, mg_buffer: list[bytes]) -> list[bytes]:
# cipher.update() input has to be 512 bit long (besides the last block).
# Thus we go over mg_buffer and buffer 512 bit input blocks before
# calling cipher.update().
- CHACHA_BLOCK = 64 # 512 bit chacha key-stream block size
+ CHACHA_BLOCK = chacha20poly1305_encrypt.block_size
buff = bytearray(CHACHA_BLOCK)
buff_len = 0 # valid bytes in the block buffer
### core/src/apps/monero/xmr/chacha_poly.py
@@ -18,7 +18,7 @@ def encrypt(
"""
from trezor.crypto import random
- nonce = random.bytes(12)
+ nonce = random.bytes(chacha20poly1305_encrypt.nonce_size)
cipher = chacha20poly1305_encrypt(key, nonce)
if associated_data:
cipher.auth(associated_data)
@@ -40,7 +40,8 @@ def _decrypt(
cipher = chacha20poly1305_decrypt(key, iv)
if associated_data:
cipher.auth(associated_data)
- exp_tag, ciphertext = ciphertext[-16:], ciphertext[:-16]
+ tag_size = chacha20poly1305_decrypt.tag_size
+ exp_tag, ciphertext = ciphertext[-tag_size:], ciphertext[:-tag_size]
plaintext = cipher.decrypt(ciphertext)
try:
cipher.finish(exp_tag)
### core/src/apps/webauthn/credential.py
@@ -175,7 +175,7 @@ def generate_id(self) -> None:
key = seed.derive_slip21_node_without_passphrase(
[b"SLIP-0022", _CRED_ID_VERSION, b"Encryption key"]
).key()
- iv = random.bytes(12)
+ iv = random.bytes(chacha20poly1305_encrypt.nonce_size)
ctx = chacha20poly1305_encrypt(key, iv)
ctx.auth(self.rp_id_hash)
ciphertext = ctx.encrypt(cbor.encode(data))
@@ -195,9 +195,10 @@ def from_cred_id(
key = seed.derive_slip21_node_without_passphrase(
[b"SLIP-0022", cred_id[0:4], b"Encryption key"]
).key()
- iv = cred_id[4:16]
- ciphertext = cred_id[16:-16]
- tag = cred_id[-16:]
+ iv_end = len(_CRED_ID_VERSION) + chacha20poly1305_decrypt.nonce_size
+ iv = cred_id[len(_CRED_ID_VERSION) : iv_end]
+ ciphertext = cred_id[iv_end : -chacha20poly1305_decrypt.tag_size]
+ tag = cred_id[-chacha20poly1305_decrypt.tag_size :]
if rp_id_hash is None:
ctx = chacha20poly1305_decrypt(key, iv)
### crypto/chacha20poly1305/chacha20poly1305.h
@@ -5,6 +5,10 @@
#include "ecrypt-sync.h"
#include "poly1305-donna.h"
+#define CHACHA20POLY1305_KEY_SIZE 32
+#define CHACHA20POLY1305_BLOCK_SIZE 64
+#define CHACHA20POLY1305_TAG_SIZE 16
+
typedef struct {
ECRYPT_ctx chacha20;
poly1305_context poly1305;
### crypto/chacha20poly1305/rfc7539.h
@@ -3,6 +3,8 @@
#include "chacha20poly1305.h"
+#define RFC7539_NONCE_SIZE 12
+
void rfc7539_init(chacha20poly1305_ctx *ctx, const uint8_t key[32], const uint8_t nonce[12]);
void rfc7539_auth(chacha20poly1305_ctx *ctx, const uint8_t *in, size_t n);
void rfc7539_finish(chacha20poly1305_ctx *ctx, int64_t alen, int64_t plen, uint8_t mac[16]);
### storage/storage.c
@@ -121,7 +121,7 @@ const uint32_t V0_PIN_EMPTY = 1;
#define HARDWARE_SALT_SIZE SHA256_DIGEST_LENGTH
// The length of the data encryption key in bytes.
-#define DEK_SIZE 32
+#define DEK_SIZE CHACHA20POLY1305_KEY_SIZE
// The length of the storage authentication key in bytes.
#define SAK_SIZE 16
@@ -136,15 +136,6 @@ const uint32_t V0_PIN_EMPTY = 1;
// The length of the storage authentication tag in bytes.
#define STORAGE_TAG_SIZE 16
-// The length of the Poly1305 authentication tag in bytes.
-#define POLY1305_TAG_SIZE 16
-
-// The length of the ChaCha20 IV (aka nonce) in bytes as per RFC 7539.
-#define CHACHA20_IV_SIZE 12
-
-// The length of the ChaCha20 block in bytes.
-#define CHACHA20_BLOCK_SIZE 64
-
// The byte length of the salt used in checking the wipe code.
#define WIPE_CODE_SALT_SIZE 8
@@ -857,7 +848,8 @@ static secbool __wur derive_kek_unlock(
static secbool set_pin(const uint8_t *pin, size_t pin_len,
const uint8_t *ext_salt) {
// Encrypt the cached keys using the new PIN and set the new PVC.
- uint8_t buffer[STORAGE_SALT_SIZE + KEYS_SIZE + POLY1305_TAG_SIZE] = {0};
+ uint8_t buffer[STORAGE_SALT_SIZE + KEYS_SIZE + CHACHA20POLY1305_TAG_SIZE] = {
+ 0};
uint8_t *rand_salt = buffer;
uint8_t *ekeys = buffer + STORAGE_SALT_SIZE;
uint8_t *pvc = buffer + STORAGE_SALT_SIZE + KEYS_SIZE;
@@ -1125,7 +1117,8 @@ static secbool __wur decrypt_dek(const uint8_t *pin, size_t pin_len,
}
uint8_t keys[KEYS_SIZE] = {0};
- uint8_t tag[POLY1305_TAG_SIZE] __attribute__((aligned(sizeof(uint32_t))));
+ uint8_t tag[CHACHA20POLY1305_TAG_SIZE]
+ __attribute__((aligned(sizeof(uint32_t))));
chacha20poly1305_ctx ctx = {0};
// Decrypt the data encryption key and the storage authentication key and
@@ -1396,11 +1389,11 @@ static secbool storage_get_encrypted(const uint16_t key, void *val_dest,
return secfalse;
}
- if (*len < CHACHA20_IV_SIZE + POLY1305_TAG_SIZE) {
+ if (*len < RFC7539_NONCE_SIZE + CHACHA20POLY1305_TAG_SIZE) {
handle_fault("ciphertext length check");
return secfalse;
}
- *len -= CHACHA20_IV_SIZE + POLY1305_TAG_SIZE;
+ *len -= RFC7539_NONCE_SIZE + CHACHA20POLY1305_TAG_SIZE;
if (val_dest == NULL) {
return sectrue;
@@ -1412,9 +1405,9 @@ static secbool storage_get_encrypted(const uint16_t key, void *val_dest,
const uint8_t *iv = (const uint8_t *)val_stored;
const uint8_t *tag_stored =
- (const uint8_t *)val_stored + CHACHA20_IV_SIZE + *len;
- const uint8_t *ciphertext = (const uint8_t *)val_stored + CHACHA20_IV_SIZE;
- uint8_t tag_computed[POLY1305_TAG_SIZE] = {0};
+ (const uint8_t *)val_stored + RFC7539_NONCE_SIZE + *len;
+ const uint8_t *ciphertext = (const uint8_t *)val_stored + RFC7539_NONCE_SIZE;
+ uint8_t tag_computed[CHACHA20POLY1305_TAG_SIZE] = {0};
chacha20poly1305_ctx ctx = {0};
rfc7539_init(&ctx, cached_dek, iv);
rfc7539_auth(&ctx, (const uint8_t *)&key, sizeof(key));
@@ -1423,7 +1416,8 @@ static secbool storage_get_encrypted(const uint16_t key, void *val_dest,
memzero(&ctx, sizeof(ctx));
// Verify authentication tag.
- if (secequal(tag_computed, tag_stored, POLY1305_TAG_SIZE) != sectrue) {
+ if (secequal(tag_computed, tag_stored, CHACHA20POLY1305_TAG_SIZE) !=
+ sectrue) {
memzero(val_dest, max_len);
memzero(tag_computed, sizeof(tag_computed));
handle_fault("authentication tag check");
@@ -1489,32 +1483,35 @@ secbool storage_get(const uint16_t key, void *val_dest, const uint16_t max_len,
*/
static secbool storage_set_encrypted(const uint16_t key, const void *val,
const uint16_t len) {
- if (len > UINT16_MAX - CHACHA20_IV_SIZE - POLY1305_TAG_SIZE) {
+ if (len > UINT16_MAX - RFC7539_NONCE_SIZE - CHACHA20POLY1305_TAG_SIZE) {
return secfalse;
}
// Preallocate space on the flash storage.
if (sectrue !=
- auth_set(key, NULL, CHACHA20_IV_SIZE + POLY1305_TAG_SIZE + len)) {
+ auth_set(key, NULL,
+ RFC7539_NONCE_SIZE + CHACHA20POLY1305_TAG_SIZE + len)) {
return secfalse;
}
// Write the IV to the flash.
- uint8_t buffer[CHACHA20_BLOCK_SIZE] = {0};
- rng_fill_buffer(buffer, CHACHA20_IV_SIZE);
+ uint8_t buffer[CHACHA20POLY1305_BLOCK_SIZE] = {0};
+ rng_fill_buffer(buffer, RFC7539_NONCE_SIZE);
- if (sectrue != norcow_update_bytes(key, buffer, CHACHA20_IV_SIZE)) {
+ if (sectrue != norcow_update_bytes(key, buffer, RFC7539_NONCE_SIZE)) {
return secfalse;
}
// Encrypt all blocks except for the last one.
chacha20poly1305_ctx ctx = {0};
rfc7539_init(&ctx, cached_dek, buffer);
rfc7539_auth(&ctx, (const uint8_t *)&key, sizeof(key));
size_t i = 0;
- for (i = 0; i + CHACHA20_BLOCK_SIZE < len; i += CHACHA20_BLOCK_SIZE) {
+ for (i = 0; i + CHACHA20POLY1305_BLOCK_SIZE < len;
+ i += CHACHA20POLY1305_BLOCK_SIZE) {
chacha20poly1305_encrypt(&ctx, ((const uint8_t *)val) + i, buffer,
- CHACHA20_BLOCK_SIZE);
- if (sectrue != norcow_update_bytes(key, buffer, CHACHA20_BLOCK_SIZE)) {
+ CHACHA20POLY1305_BLOCK_SIZE);
+ if (sectrue !=
+ norcow_update_bytes(key, buffer, CHACHA20POLY1305_BLOCK_SIZE)) {
memzero(&ctx, sizeof(ctx));
memzero(buffer, sizeof(buffer));
return secfalse;
@@ -1526,7 +1523,7 @@ static secbool storage_set_encrypted(const uint16_t key, const void *val,
secbool ret = norcow_update_bytes(key, buffer, len - i);
if (sectrue == ret) {
rfc7539_finish(&ctx, sizeof(key), len, buffer);
- ret = norcow_update_bytes(key, buffer, POLY1305_TAG_SIZE);
+ ret = norcow_update_bytes(key, buffer, CHACHA20POLY1305_TAG_SIZE);
}
memzero(&ctx, sizeof(ctx));
memzero(buffer, sizeof(buffer));
@@ -2025,15 +2022,16 @@ static secbool storage_upgrade(void) {
if (((app & FLAG_PUBLIC) == 0) &&
(app != APP_STORAGE || key == VERSION_KEY)) {
const uint8_t *iv = (const uint8_t *)val;
- const uint8_t *tag = (const uint8_t *)val + CHACHA20_IV_SIZE;
- const uint8_t *ciphertext =
- (const uint8_t *)val + CHACHA20_IV_SIZE + POLY1305_TAG_SIZE;
+ const uint8_t *tag = (const uint8_t *)val + RFC7539_NONCE_SIZE;
+ const uint8_t *ciphertext = (const uint8_t *)val + RFC7539_NONCE_SIZE +
+ CHACHA20POLY1305_TAG_SIZE;
const size_t ciphertext_len =
- len - CHACHA20_IV_SIZE - POLY1305_TAG_SIZE;
+ len - RFC7539_NONCE_SIZE - CHACHA20POLY1305_TAG_SIZE;
if (sectrue != norcow_set(key, NULL, len) ||
- sectrue != norcow_update_bytes(key, iv, CHACHA20_IV_SIZE) ||
+ sectrue != norcow_update_bytes(key, iv, RFC7539_NONCE_SIZE) ||
sectrue != norcow_update_bytes(key, ciphertext, ciphertext_len) ||
- sectrue != norcow_update_bytes(key, tag, POLY1305_TAG_SIZE)) {
+ sectrue !=
+ norcow_update_bytes(key, tag, CHACHA20POLY1305_TAG_SIZE)) {
return secfalse;
}
} else {Why this scored 15/100
Community notes
Notes can correct, qualify, or add evidence to the AI analysis. Every note shown here has been validated by a human moderator.
The AI analysis stands alone for now. Submit a note if you can add evidence or important context.