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