0001
0002
0003
0004
0005
0006
0007
0008
0009 #ifndef _CRYPTO_SM3_BASE_H
0010 #define _CRYPTO_SM3_BASE_H
0011
0012 #include <crypto/internal/hash.h>
0013 #include <crypto/sm3.h>
0014 #include <linux/crypto.h>
0015 #include <linux/module.h>
0016 #include <linux/string.h>
0017 #include <asm/unaligned.h>
0018
0019 typedef void (sm3_block_fn)(struct sm3_state *sst, u8 const *src, int blocks);
0020
0021 static inline int sm3_base_init(struct shash_desc *desc)
0022 {
0023 struct sm3_state *sctx = shash_desc_ctx(desc);
0024
0025 sctx->state[0] = SM3_IVA;
0026 sctx->state[1] = SM3_IVB;
0027 sctx->state[2] = SM3_IVC;
0028 sctx->state[3] = SM3_IVD;
0029 sctx->state[4] = SM3_IVE;
0030 sctx->state[5] = SM3_IVF;
0031 sctx->state[6] = SM3_IVG;
0032 sctx->state[7] = SM3_IVH;
0033 sctx->count = 0;
0034
0035 return 0;
0036 }
0037
0038 static inline int sm3_base_do_update(struct shash_desc *desc,
0039 const u8 *data,
0040 unsigned int len,
0041 sm3_block_fn *block_fn)
0042 {
0043 struct sm3_state *sctx = shash_desc_ctx(desc);
0044 unsigned int partial = sctx->count % SM3_BLOCK_SIZE;
0045
0046 sctx->count += len;
0047
0048 if (unlikely((partial + len) >= SM3_BLOCK_SIZE)) {
0049 int blocks;
0050
0051 if (partial) {
0052 int p = SM3_BLOCK_SIZE - partial;
0053
0054 memcpy(sctx->buffer + partial, data, p);
0055 data += p;
0056 len -= p;
0057
0058 block_fn(sctx, sctx->buffer, 1);
0059 }
0060
0061 blocks = len / SM3_BLOCK_SIZE;
0062 len %= SM3_BLOCK_SIZE;
0063
0064 if (blocks) {
0065 block_fn(sctx, data, blocks);
0066 data += blocks * SM3_BLOCK_SIZE;
0067 }
0068 partial = 0;
0069 }
0070 if (len)
0071 memcpy(sctx->buffer + partial, data, len);
0072
0073 return 0;
0074 }
0075
0076 static inline int sm3_base_do_finalize(struct shash_desc *desc,
0077 sm3_block_fn *block_fn)
0078 {
0079 const int bit_offset = SM3_BLOCK_SIZE - sizeof(__be64);
0080 struct sm3_state *sctx = shash_desc_ctx(desc);
0081 __be64 *bits = (__be64 *)(sctx->buffer + bit_offset);
0082 unsigned int partial = sctx->count % SM3_BLOCK_SIZE;
0083
0084 sctx->buffer[partial++] = 0x80;
0085 if (partial > bit_offset) {
0086 memset(sctx->buffer + partial, 0x0, SM3_BLOCK_SIZE - partial);
0087 partial = 0;
0088
0089 block_fn(sctx, sctx->buffer, 1);
0090 }
0091
0092 memset(sctx->buffer + partial, 0x0, bit_offset - partial);
0093 *bits = cpu_to_be64(sctx->count << 3);
0094 block_fn(sctx, sctx->buffer, 1);
0095
0096 return 0;
0097 }
0098
0099 static inline int sm3_base_finish(struct shash_desc *desc, u8 *out)
0100 {
0101 struct sm3_state *sctx = shash_desc_ctx(desc);
0102 __be32 *digest = (__be32 *)out;
0103 int i;
0104
0105 for (i = 0; i < SM3_DIGEST_SIZE / sizeof(__be32); i++)
0106 put_unaligned_be32(sctx->state[i], digest++);
0107
0108 memzero_explicit(sctx, sizeof(*sctx));
0109 return 0;
0110 }
0111
0112 #endif