xref: /optee_os/core/lib/libtomcrypt/cmac.c (revision 5b25c76ac40f830867e3d60800120ffd7874e8dc)
1 // SPDX-License-Identifier: BSD-2-Clause
2 /*
3  * Copyright (c) 2014-2019, Linaro Limited
4  */
5 
6 #include <assert.h>
7 #include <crypto/crypto.h>
8 #include <crypto/crypto_impl.h>
9 #include <stdlib.h>
10 #include <string.h>
11 #include <tee_api_types.h>
12 #include <tomcrypt_private.h>
13 #include <utee_defines.h>
14 #include <util.h>
15 
16 struct ltc_omac_ctx {
17 	struct crypto_mac_ctx ctx;
18 	int cipher_idx;
19 	omac_state state;
20 };
21 
22 static const struct crypto_mac_ops ltc_omac_ops;
23 
24 static struct ltc_omac_ctx *to_omac_ctx(struct crypto_mac_ctx *ctx)
25 {
26 	assert(ctx && ctx->ops == &ltc_omac_ops);
27 
28 	return container_of(ctx, struct ltc_omac_ctx, ctx);
29 }
30 
31 static TEE_Result ltc_omac_init(struct crypto_mac_ctx *ctx, const uint8_t *key,
32 				size_t len)
33 {
34 	struct ltc_omac_ctx *hc = to_omac_ctx(ctx);
35 
36 	if (omac_init(&hc->state, hc->cipher_idx, key, len) == CRYPT_OK)
37 		return TEE_SUCCESS;
38 	else
39 		return TEE_ERROR_BAD_STATE;
40 }
41 
42 static TEE_Result ltc_omac_update(struct crypto_mac_ctx *ctx,
43 				  const uint8_t *data, size_t len)
44 {
45 	if (omac_process(&to_omac_ctx(ctx)->state, data, len) == CRYPT_OK)
46 		return TEE_SUCCESS;
47 	else
48 		return TEE_ERROR_BAD_STATE;
49 }
50 
51 static TEE_Result ltc_omac_final(struct crypto_mac_ctx *ctx, uint8_t *digest,
52 				 size_t len)
53 {
54 	unsigned long l = len;
55 
56 	if (omac_done(&to_omac_ctx(ctx)->state, digest, &l) == CRYPT_OK)
57 		return TEE_SUCCESS;
58 	else
59 		return TEE_ERROR_BAD_STATE;
60 }
61 
62 static void ltc_omac_free_ctx(struct crypto_mac_ctx *ctx)
63 {
64 	free(to_omac_ctx(ctx));
65 }
66 
67 static void ltc_omac_copy_state(struct crypto_mac_ctx *dst_ctx,
68 				struct crypto_mac_ctx *src_ctx)
69 {
70 	struct ltc_omac_ctx *src = to_omac_ctx(src_ctx);
71 	struct ltc_omac_ctx *dst = to_omac_ctx(dst_ctx);
72 
73 	assert(src->cipher_idx == dst->cipher_idx);
74 	dst->state = src->state;
75 }
76 
77 static const struct crypto_mac_ops ltc_omac_ops = {
78 	.init = ltc_omac_init,
79 	.update = ltc_omac_update,
80 	.final = ltc_omac_final,
81 	.free_ctx = ltc_omac_free_ctx,
82 	.copy_state = ltc_omac_copy_state,
83 };
84 
85 TEE_Result crypto_aes_cmac_alloc_ctx(struct crypto_mac_ctx **ctx_ret)
86 {
87 	struct ltc_omac_ctx *ctx = NULL;
88 	int cipher_idx = find_cipher("aes");
89 
90 	if (cipher_idx < 0)
91 		return TEE_ERROR_NOT_SUPPORTED;
92 
93 	ctx = calloc(1, sizeof(*ctx));
94 	if (!ctx)
95 		return TEE_ERROR_OUT_OF_MEMORY;
96 
97 	ctx->ctx.ops = &ltc_omac_ops;
98 	ctx->cipher_idx = cipher_idx;
99 	*ctx_ret = &ctx->ctx;
100 
101 	return TEE_SUCCESS;
102 }
103