Mbed TLS doesn't support the 16-byte variant yet. Currently the initial
counter value is always 0 with the PSA API and with the legacy cipher API.
https://github.com/Mbed-TLS/mbedtls/issues/5616
You can use a different ICV with the low-level mbedtls_chacha20_xxx API.
--
Gilles Peskine
Mbed TLS developer and PSA Crypto architect
On 12/09/2023 23:35, Christian Huitema wrote:
> Thanks, Gilles.
>
> I am stumbling on a ChaCha20 issue for now. I am implementing section
> 5.4.4 of RFC 9001
> (
https://www.rfc-editor.org/rfc/rfc9001.html#name-chacha20-based-header-prote),
> which requires using ChaCha20 with a 32 bits counter and a 12 bytes
> nonce.
>
> The PSA spec says: call to psa_cipher_set_iv() on a multi-part cipher
> operation can support the following IV sizes:
>
> 12 bytes: the provided IV is used as the nonce, and the counter
> value is set to zero.
> 16 bytes: the first four bytes of the IV are used as the counter
> value (encoded as little-endian), and the remaining 12 bytes is used
> as the nonce.
>
> Good! the 16 bytes version is exactly what I need. But I get a failed
> check in
>
> psa_status_t mbedtls_psa_cipher_set_iv(
> mbedtls_psa_cipher_operation_t *operation,
> const uint8_t *iv, size_t iv_length)
> {
> if (iv_length != operation->iv_length) {
> return PSA_ERROR_INVALID_ARGUMENT;
> }
> ...
>
> I am setting the IV length to 16, but operation->iv_length is set to
> 12...
>
> I assume that I am doing something wrong. The series of calls is:
>
> 1) ptls_mbedtls_cipher_setup_key, with PSA_ALG_STREAM_CIPHER, and
> PSA_KEY_TYPE_CHACHA20
>
> 2) psa_cipher_encrypt_setup, with the computed key and
> alg=PSA_ALG_STREAM_CIPHER
>
> 3) psa_cipher_set_iv, with 16 bytes IV, which fails.
>
> Is there some sample that I can look at?
>
> -- Christian Huitema
>
>
>
> On 9/12/2023 1:12 PM, Gilles Peskine via mbed-tls wrote:
>> On 12/09/2023 19:50, Christian Huitema via mbed-tls wrote:
>>> By the way, I have a similar question regarding
>>> mbedtls_ctr_drbg_random. I assume that I should use
>>> psa_generate_random instead, but I do not see the PSA equivalents of
>>> mbedtls_ctr_drbg_seed or mbedtls_entropy_func. Is it correct to
>>> assume that these are handled "under the hood", for example by
>>> psa_crypto_init?
>> That's correct. psa_crypto_init() seeds a PRNG. psa_generate_random()
>> produces output from this PRNG and reseeds periodically.
>>
>> Under the hood, by default, the entropy sources are the same as
>> mbedtls_entropy_func() and the DRBG is the one from the CTR_DRBG
>> module with its default configuration.
>>
>> By the way, if you have working code using the mbedtls crypto API and
>> you want to migrate to the PSA API, you may be interested in this
>> guide (not yet reviewed):
https://github.com/Mbed-TLS/mbedtls/pull/7766
>>
>> Best regards,
>>