2 * Copyright 2010-2016 The OpenSSL Project Authors. All Rights Reserved.
4 * Licensed under the OpenSSL license (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 /* The context structure and "key" is simply a CMAC_CTX */
20 static int pkey_cmac_init(EVP_PKEY_CTX *ctx)
22 ctx->data = CMAC_CTX_new();
23 if (ctx->data == NULL)
25 ctx->keygen_info_count = 0;
29 static int pkey_cmac_copy(EVP_PKEY_CTX *dst, EVP_PKEY_CTX *src)
31 if (!pkey_cmac_init(dst))
33 if (!CMAC_CTX_copy(dst->data, src->data))
38 static void pkey_cmac_cleanup(EVP_PKEY_CTX *ctx)
40 CMAC_CTX_free(ctx->data);
43 static int pkey_cmac_keygen(EVP_PKEY_CTX *ctx, EVP_PKEY *pkey)
45 CMAC_CTX *cmkey = CMAC_CTX_new();
46 CMAC_CTX *cmctx = ctx->data;
49 if (!CMAC_CTX_copy(cmkey, cmctx)) {
53 EVP_PKEY_assign(pkey, EVP_PKEY_CMAC, cmkey);
58 static int int_update(EVP_MD_CTX *ctx, const void *data, size_t count)
60 if (!CMAC_Update(EVP_MD_CTX_pkey_ctx(ctx)->data, data, count))
65 static int cmac_signctx_init(EVP_PKEY_CTX *ctx, EVP_MD_CTX *mctx)
67 EVP_MD_CTX_set_flags(mctx, EVP_MD_CTX_FLAG_NO_INIT);
68 EVP_MD_CTX_set_update_fn(mctx, int_update);
72 static int cmac_signctx(EVP_PKEY_CTX *ctx, unsigned char *sig, size_t *siglen,
75 return CMAC_Final(ctx->data, sig, siglen);
78 static int pkey_cmac_ctrl(EVP_PKEY_CTX *ctx, int type, int p1, void *p2)
80 CMAC_CTX *cmctx = ctx->data;
83 case EVP_PKEY_CTRL_SET_MAC_KEY:
86 if (!CMAC_Init(cmctx, p2, p1, NULL, NULL))
90 case EVP_PKEY_CTRL_CIPHER:
91 if (!CMAC_Init(cmctx, NULL, 0, p2, ctx->engine))
95 case EVP_PKEY_CTRL_MD:
96 if (ctx->pkey && !CMAC_CTX_copy(ctx->data,
97 (CMAC_CTX *)ctx->pkey->pkey.ptr))
99 if (!CMAC_Init(cmctx, NULL, 0, NULL, NULL))
110 static int pkey_cmac_ctrl_str(EVP_PKEY_CTX *ctx,
111 const char *type, const char *value)
116 if (strcmp(type, "cipher") == 0) {
118 c = EVP_get_cipherbyname(value);
121 return pkey_cmac_ctrl(ctx, EVP_PKEY_CTRL_CIPHER, -1, (void *)c);
123 if (strcmp(type, "key") == 0)
124 return EVP_PKEY_CTX_str2ctrl(ctx, EVP_PKEY_CTRL_SET_MAC_KEY, value);
125 if (strcmp(type, "hexkey") == 0)
126 return EVP_PKEY_CTX_hex2ctrl(ctx, EVP_PKEY_CTRL_SET_MAC_KEY, value);
130 const EVP_PKEY_METHOD cmac_pkey_meth = {
132 EVP_PKEY_FLAG_SIGCTX_CUSTOM,