| 1 | /* |
| 2 | * Copyright 2019 The OpenSSL Project Authors. All Rights Reserved. |
| 3 | * |
| 4 | * Licensed under the Apache License 2.0 (the "License"). You may not use |
| 5 | * this file except in compliance with the License. You can obtain a copy |
| 6 | * in the file LICENSE in the source distribution or at |
| 7 | * https://www.openssl.org/source/license.html |
| 8 | */ |
| 9 | |
| 10 | #include "prov/ciphercommon.h" |
| 11 | #include "prov/ciphercommon_ccm.h" |
| 12 | |
| 13 | int ccm_generic_setiv(PROV_CCM_CTX *ctx, const unsigned char *nonce, |
| 14 | size_t nlen, size_t mlen) |
| 15 | { |
| 16 | return CRYPTO_ccm128_setiv(&ctx->ccm_ctx, nonce, nlen, mlen) == 0; |
| 17 | } |
| 18 | |
| 19 | int ccm_generic_setaad(PROV_CCM_CTX *ctx, const unsigned char *aad, size_t alen) |
| 20 | { |
| 21 | CRYPTO_ccm128_aad(&ctx->ccm_ctx, aad, alen); |
| 22 | return 1; |
| 23 | } |
| 24 | |
| 25 | int ccm_generic_gettag(PROV_CCM_CTX *ctx, unsigned char *tag, size_t tlen) |
| 26 | { |
| 27 | return CRYPTO_ccm128_tag(&ctx->ccm_ctx, tag, tlen) > 0; |
| 28 | } |
| 29 | |
| 30 | int ccm_generic_auth_encrypt(PROV_CCM_CTX *ctx, const unsigned char *in, |
| 31 | unsigned char *out, size_t len, |
| 32 | unsigned char *tag, size_t taglen) |
| 33 | { |
| 34 | int rv; |
| 35 | |
| 36 | if (ctx->str != NULL) |
| 37 | rv = CRYPTO_ccm128_encrypt_ccm64(&ctx->ccm_ctx, in, |
| 38 | out, len, ctx->str) == 0; |
| 39 | else |
| 40 | rv = CRYPTO_ccm128_encrypt(&ctx->ccm_ctx, in, out, len) == 0; |
| 41 | |
| 42 | if (rv == 1 && tag != NULL) |
| 43 | rv = (CRYPTO_ccm128_tag(&ctx->ccm_ctx, tag, taglen) > 0); |
| 44 | return rv; |
| 45 | } |
| 46 | |
| 47 | int ccm_generic_auth_decrypt(PROV_CCM_CTX *ctx, const unsigned char *in, |
| 48 | unsigned char *out, size_t len, |
| 49 | unsigned char *expected_tag, size_t taglen) |
| 50 | { |
| 51 | int rv = 0; |
| 52 | |
| 53 | if (ctx->str != NULL) |
| 54 | rv = CRYPTO_ccm128_decrypt_ccm64(&ctx->ccm_ctx, in, out, len, |
| 55 | ctx->str) == 0; |
| 56 | else |
| 57 | rv = CRYPTO_ccm128_decrypt(&ctx->ccm_ctx, in, out, len) == 0; |
| 58 | if (rv) { |
| 59 | unsigned char tag[16]; |
| 60 | |
| 61 | if (!CRYPTO_ccm128_tag(&ctx->ccm_ctx, tag, taglen) |
| 62 | || CRYPTO_memcmp(tag, expected_tag, taglen) != 0) |
| 63 | rv = 0; |
| 64 | } |
| 65 | if (rv == 0) |
| 66 | OPENSSL_cleanse(out, len); |
| 67 | return rv; |
| 68 | } |
| 69 | |
| 70 | |