| 1 | /* SPDX-License-Identifier: GPL-2.0-only */ |
| 2 | /* |
| 3 | * sm3_base.h - core logic for SM3 implementations |
| 4 | * |
| 5 | * Copyright (C) 2017 ARM Limited or its affiliates. |
| 6 | * Written by Gilad Ben-Yossef <gilad@benyossef.com> |
| 7 | */ |
| 8 | |
| 9 | #ifndef _CRYPTO_SM3_BASE_H |
| 10 | #define _CRYPTO_SM3_BASE_H |
| 11 | |
| 12 | #include <crypto/internal/hash.h> |
| 13 | #include <crypto/sm3.h> |
| 14 | #include <linux/math.h> |
| 15 | #include <linux/module.h> |
| 16 | #include <linux/string.h> |
| 17 | #include <linux/types.h> |
| 18 | #include <linux/unaligned.h> |
| 19 | |
| 20 | typedef void (sm3_block_fn)(struct sm3_state *sst, u8 const *src, int blocks); |
| 21 | |
| 22 | static inline int sm3_base_init(struct shash_desc *desc) |
| 23 | { |
| 24 | sm3_init(sctx: shash_desc_ctx(desc)); |
| 25 | return 0; |
| 26 | } |
| 27 | |
| 28 | static inline int sm3_base_do_update_blocks(struct shash_desc *desc, |
| 29 | const u8 *data, unsigned int len, |
| 30 | sm3_block_fn *block_fn) |
| 31 | { |
| 32 | unsigned int remain = len - round_down(len, SM3_BLOCK_SIZE); |
| 33 | struct sm3_state *sctx = shash_desc_ctx(desc); |
| 34 | |
| 35 | sctx->count += len - remain; |
| 36 | block_fn(sctx, data, len / SM3_BLOCK_SIZE); |
| 37 | return remain; |
| 38 | } |
| 39 | |
| 40 | static inline int sm3_base_do_finup(struct shash_desc *desc, |
| 41 | const u8 *src, unsigned int len, |
| 42 | sm3_block_fn *block_fn) |
| 43 | { |
| 44 | unsigned int bit_offset = SM3_BLOCK_SIZE / 8 - 1; |
| 45 | struct sm3_state *sctx = shash_desc_ctx(desc); |
| 46 | union { |
| 47 | __be64 b64[SM3_BLOCK_SIZE / 4]; |
| 48 | u8 u8[SM3_BLOCK_SIZE * 2]; |
| 49 | } block = {}; |
| 50 | |
| 51 | if (len >= SM3_BLOCK_SIZE) { |
| 52 | int remain; |
| 53 | |
| 54 | remain = sm3_base_do_update_blocks(desc, data: src, len, block_fn); |
| 55 | src += len - remain; |
| 56 | len = remain; |
| 57 | } |
| 58 | |
| 59 | if (len >= bit_offset * 8) |
| 60 | bit_offset += SM3_BLOCK_SIZE / 8; |
| 61 | memcpy(&block, src, len); |
| 62 | block.u8[len] = 0x80; |
| 63 | sctx->count += len; |
| 64 | block.b64[bit_offset] = cpu_to_be64(sctx->count << 3); |
| 65 | block_fn(sctx, block.u8, (bit_offset + 1) * 8 / SM3_BLOCK_SIZE); |
| 66 | memzero_explicit(s: &block, count: sizeof(block)); |
| 67 | |
| 68 | return 0; |
| 69 | } |
| 70 | |
| 71 | static inline int sm3_base_finish(struct shash_desc *desc, u8 *out) |
| 72 | { |
| 73 | struct sm3_state *sctx = shash_desc_ctx(desc); |
| 74 | __be32 *digest = (__be32 *)out; |
| 75 | int i; |
| 76 | |
| 77 | for (i = 0; i < SM3_DIGEST_SIZE / sizeof(__be32); i++) |
| 78 | put_unaligned_be32(val: sctx->state[i], p: digest++); |
| 79 | return 0; |
| 80 | } |
| 81 | |
| 82 | #endif /* _CRYPTO_SM3_BASE_H */ |
| 83 | |