|
37 | 37 | #include <string.h> |
38 | 38 |
|
39 | 39 | #include <mbedtls/aes.h> |
| 40 | +#include <mbedtls/ccm.h> |
40 | 41 | #include <mbedtls/cmac.h> |
41 | 42 | #include <mbedtls/ctr_drbg.h> |
42 | 43 | #include <mbedtls/ecdsa.h> |
@@ -152,6 +153,56 @@ OT_TOOL_WEAK otError otPlatCryptoAesFree(otCryptoContext *aContext) |
152 | 153 | return error; |
153 | 154 | } |
154 | 155 |
|
| 156 | +#if OPENTHREAD_CONFIG_CRYPTO_PLATFORM_CCM_ONE_SHOT_ENABLE |
| 157 | + |
| 158 | +OT_TOOL_WEAK otError otPlatCryptoAesCcmProcessOneShot(bool aEncrypt, |
| 159 | + const otPlatCryptoAesCcmConfig *aConfig, |
| 160 | + const uint8_t *aHeader, |
| 161 | + uint8_t *aData) |
| 162 | +{ |
| 163 | + Error error = kErrorNone; |
| 164 | + mbedtls_ccm_context ctx; |
| 165 | + int ret; |
| 166 | + |
| 167 | + mbedtls_ccm_init(&ctx); |
| 168 | + |
| 169 | + VerifyOrExit(aConfig != nullptr && aConfig->mKey.mKey != nullptr && aConfig->mNonce != nullptr && aData != nullptr, |
| 170 | + error = kErrorInvalidArgs); |
| 171 | + |
| 172 | + ret = mbedtls_ccm_setkey(&ctx, MBEDTLS_CIPHER_ID_AES, aConfig->mKey.mKey, aConfig->mKey.mKeyLength * 8); |
| 173 | + VerifyOrExit(ret == 0, error = kErrorFailed); |
| 174 | + |
| 175 | + if (aEncrypt) |
| 176 | + { |
| 177 | + ret = mbedtls_ccm_encrypt_and_tag(&ctx, aConfig->mPlainTextLength, aConfig->mNonce, aConfig->mNonceLength, |
| 178 | + aHeader, aConfig->mHeaderLength, aData, aData, |
| 179 | + aData + aConfig->mPlainTextLength, aConfig->mTagLength); |
| 180 | + VerifyOrExit(ret == 0, error = kErrorFailed); |
| 181 | + } |
| 182 | + else |
| 183 | + { |
| 184 | + // MBEDTLS_ERR_CCM_AUTH_FAILED is the expected return on tag mismatch; map to kErrorSecurity. |
| 185 | + ret = mbedtls_ccm_auth_decrypt(&ctx, aConfig->mPlainTextLength, aConfig->mNonce, aConfig->mNonceLength, aHeader, |
| 186 | + aConfig->mHeaderLength, aData, aData, aData + aConfig->mPlainTextLength, |
| 187 | + aConfig->mTagLength); |
| 188 | + |
| 189 | + if (ret == MBEDTLS_ERR_CCM_AUTH_FAILED) |
| 190 | + { |
| 191 | + error = kErrorSecurity; |
| 192 | + } |
| 193 | + else |
| 194 | + { |
| 195 | + VerifyOrExit(ret == 0, error = kErrorFailed); |
| 196 | + } |
| 197 | + } |
| 198 | + |
| 199 | +exit: |
| 200 | + mbedtls_ccm_free(&ctx); |
| 201 | + return error; |
| 202 | +} |
| 203 | + |
| 204 | +#endif // OPENTHREAD_CONFIG_CRYPTO_PLATFORM_CCM_ONE_SHOT_ENABLE |
| 205 | + |
155 | 206 | #if OPENTHREAD_FTD || OPENTHREAD_MTD |
156 | 207 |
|
157 | 208 | // HMAC implementations |
|
0 commit comments