2 * Copyright 2018 The OpenSSL Project Authors. All Rights Reserved.
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
11 #include "internal/cryptlib.h"
12 #include <openssl/x509.h>
13 #include <openssl/x509v3.h>
14 #include <openssl/evp.h>
15 #include <openssl/cmac.h>
16 #include "internal/evp_int.h"
18 /* local CMAC pkey structure */
20 /* typedef EVP_MAC_IMPL */
21 struct evp_mac_impl_st {
22 /* tmpcipher and tmpengine are set to NULL after a CMAC_Init call */
23 const EVP_CIPHER *tmpcipher; /* cached CMAC cipher */
24 const ENGINE *tmpengine; /* cached CMAC cipher engine */
28 static EVP_MAC_IMPL *cmac_new(void)
32 if ((cctx = OPENSSL_zalloc(sizeof(*cctx))) == NULL
33 || (cctx->ctx = CMAC_CTX_new()) == NULL) {
41 static void cmac_free(EVP_MAC_IMPL *cctx)
44 CMAC_CTX_free(cctx->ctx);
49 static int cmac_copy(EVP_MAC_IMPL *cdst, EVP_MAC_IMPL *csrc)
51 if (!CMAC_CTX_copy(cdst->ctx, csrc->ctx))
54 cdst->tmpengine = csrc->tmpengine;
55 cdst->tmpcipher = csrc->tmpcipher;
59 static size_t cmac_size(EVP_MAC_IMPL *cctx)
61 return EVP_CIPHER_CTX_block_size(CMAC_CTX_get0_cipher_ctx(cctx->ctx));
64 static int cmac_init(EVP_MAC_IMPL *cctx)
66 int rv = CMAC_Init(cctx->ctx, NULL, 0, cctx->tmpcipher,
67 (ENGINE *)cctx->tmpengine);
68 cctx->tmpcipher = NULL;
69 cctx->tmpengine = NULL;
74 static int cmac_update(EVP_MAC_IMPL *cctx, const unsigned char *data,
77 return CMAC_Update(cctx->ctx, data, datalen);
80 static int cmac_final(EVP_MAC_IMPL *cctx, unsigned char *out)
84 return CMAC_Final(cctx->ctx, out, &hlen);
87 static int cmac_ctrl(EVP_MAC_IMPL *cctx, int cmd, va_list args)
90 case EVP_MAC_CTRL_SET_KEY:
92 const unsigned char *key = va_arg(args, const unsigned char *);
93 size_t keylen = va_arg(args, size_t);
94 int rv = CMAC_Init(cctx->ctx, key, keylen, cctx->tmpcipher,
95 (ENGINE *)cctx->tmpengine);
97 cctx->tmpcipher = NULL;
98 cctx->tmpengine = NULL;
103 case EVP_MAC_CTRL_SET_CIPHER:
104 cctx->tmpcipher = va_arg(args, const EVP_CIPHER *);
106 case EVP_MAC_CTRL_SET_ENGINE:
107 cctx->tmpengine = va_arg(args, const ENGINE *);
115 static int cmac_ctrl_int(EVP_MAC_IMPL *hctx, int cmd, ...)
121 rv = cmac_ctrl(hctx, cmd, args);
127 static int cmac_ctrl_str_cb(void *hctx, int cmd, void *buf, size_t buflen)
129 return cmac_ctrl_int(hctx, cmd, buf, buflen);
132 static int cmac_ctrl_str(EVP_MAC_IMPL *cctx, const char *type,
137 if (strcmp(type, "cipher") == 0) {
138 const EVP_CIPHER *c = EVP_get_cipherbyname(value);
142 return cmac_ctrl_int(cctx, EVP_MAC_CTRL_SET_CIPHER, c);
144 if (strcmp(type, "key") == 0)
145 return EVP_str2ctrl(cmac_ctrl_str_cb, cctx, EVP_MAC_CTRL_SET_KEY,
147 if (strcmp(type, "hexkey") == 0)
148 return EVP_hex2ctrl(cmac_ctrl_str_cb, cctx, EVP_MAC_CTRL_SET_KEY,
153 const EVP_MAC cmac_meth = {