1 // SPDX-License-Identifier: BSD-2-Clause 2 /* 3 * Copyright (C) 2018, ARM Limited 4 * Copyright (C) 2019, Linaro Limited 5 */ 6 7 #include <assert.h> 8 #include <compiler.h> 9 #include <crypto/crypto.h> 10 #include <crypto/crypto_impl.h> 11 #include <kernel/panic.h> 12 #include <mbedtls/md.h> 13 #include <stdlib.h> 14 #include <string.h> 15 #include <string_ext.h> 16 #include <tee_api_types.h> 17 #include <utee_defines.h> 18 #include <util.h> 19 20 #include "sm3.h" 21 22 struct sm3_hmac_ctx { 23 struct crypto_mac_ctx mac_ctx; 24 struct sm3_context sm3_ctx; 25 }; 26 27 static const struct crypto_mac_ops sm3_hmac_ops; 28 29 static struct sm3_hmac_ctx *to_hmac_ctx(struct crypto_mac_ctx *ctx) 30 { 31 assert(ctx && ctx->ops == &sm3_hmac_ops); 32 33 return container_of(ctx, struct sm3_hmac_ctx, mac_ctx); 34 } 35 36 static TEE_Result op_sm3_hmac_init(struct crypto_mac_ctx *ctx, 37 const uint8_t *key, size_t len) 38 { 39 sm3_hmac_init(&to_hmac_ctx(ctx)->sm3_ctx, key, len); 40 41 return TEE_SUCCESS; 42 } 43 44 static TEE_Result op_sm3_hmac_update(struct crypto_mac_ctx *ctx, 45 const uint8_t *data, size_t len) 46 { 47 sm3_hmac_update(&to_hmac_ctx(ctx)->sm3_ctx, data, len); 48 49 return TEE_SUCCESS; 50 } 51 52 static TEE_Result op_sm3_hmac_final(struct crypto_mac_ctx *ctx, uint8_t *digest, 53 size_t len) 54 { 55 struct sm3_hmac_ctx *c = to_hmac_ctx(ctx); 56 size_t hmac_size = TEE_SM3_HASH_SIZE; 57 uint8_t block_digest[TEE_SM3_HASH_SIZE] = { 0 }; 58 uint8_t *tmp_digest = NULL; 59 60 if (len == 0) 61 return TEE_ERROR_BAD_PARAMETERS; 62 63 if (hmac_size > len) 64 tmp_digest = block_digest; /* use a tempory buffer */ 65 else 66 tmp_digest = digest; 67 68 sm3_hmac_final(&c->sm3_ctx, tmp_digest); 69 70 if (hmac_size > len) 71 memcpy(digest, tmp_digest, len); 72 73 return TEE_SUCCESS; 74 } 75 76 static void op_sm3_hmac_free_ctx(struct crypto_mac_ctx *ctx) 77 { 78 struct sm3_hmac_ctx *c = to_hmac_ctx(ctx); 79 80 memzero_explicit(&c->sm3_ctx, sizeof(c->sm3_ctx)); 81 free(c); 82 } 83 84 static void op_sm3_hmac_copy_state(struct crypto_mac_ctx *dst_ctx, 85 struct crypto_mac_ctx *src_ctx) 86 { 87 struct sm3_hmac_ctx *src = to_hmac_ctx(src_ctx); 88 struct sm3_hmac_ctx *dst = to_hmac_ctx(dst_ctx); 89 90 dst->sm3_ctx = src->sm3_ctx; 91 } 92 93 static const struct crypto_mac_ops sm3_hmac_ops = { 94 .init = op_sm3_hmac_init, 95 .update = op_sm3_hmac_update, 96 .final = op_sm3_hmac_final, 97 .free_ctx = op_sm3_hmac_free_ctx, 98 .copy_state = op_sm3_hmac_copy_state, 99 }; 100 101 TEE_Result crypto_hmac_sm3_alloc_ctx(struct crypto_mac_ctx **ctx) 102 { 103 struct sm3_hmac_ctx *c = NULL; 104 105 c = calloc(1, sizeof(*c)); 106 if (!c) 107 return TEE_ERROR_OUT_OF_MEMORY; 108 109 c->mac_ctx.ops = &sm3_hmac_ops; 110 111 *ctx = &c->mac_ctx; 112 113 return TEE_SUCCESS; 114 } 115