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