xref: /linux/lib/crypto/sha256.c (revision 02b35bab7e6c5bb2a843828316d528216b8cedc8)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * SHA-256, as specified in
4  * http://csrc.nist.gov/groups/STM/cavp/documents/shs/sha256-384-512.pdf
5  *
6  * SHA-256 code by Jean-Luc Cooke <jlcooke@certainkey.com>.
7  *
8  * Copyright (c) Jean-Luc Cooke <jlcooke@certainkey.com>
9  * Copyright (c) Andrew McDonald <andrew@mcdonald.org.uk>
10  * Copyright (c) 2002 James Morris <jmorris@intercode.com.au>
11  * Copyright (c) 2014 Red Hat Inc.
12  */
13 
14 #include <crypto/internal/blockhash.h>
15 #include <crypto/internal/sha2.h>
16 #include <linux/export.h>
17 #include <linux/kernel.h>
18 #include <linux/module.h>
19 #include <linux/string.h>
20 
21 /*
22  * If __DISABLE_EXPORTS is defined, then this file is being compiled for a
23  * pre-boot environment.  In that case, ignore the kconfig options, pull the
24  * generic code into the same translation unit, and use that only.
25  */
26 #ifdef __DISABLE_EXPORTS
27 #include "sha256-generic.c"
28 #endif
29 
30 static inline bool sha256_purgatory(void)
31 {
32 	return __is_defined(__DISABLE_EXPORTS);
33 }
34 
35 static inline void sha256_blocks(u32 state[SHA256_STATE_WORDS], const u8 *data,
36 				 size_t nblocks)
37 {
38 	sha256_choose_blocks(state, data, nblocks, sha256_purgatory(), false);
39 }
40 
41 void sha256_update(struct sha256_state *sctx, const u8 *data, size_t len)
42 {
43 	size_t partial = sctx->count % SHA256_BLOCK_SIZE;
44 
45 	sctx->count += len;
46 	BLOCK_HASH_UPDATE_BLOCKS(sha256_blocks, sctx->ctx.state, data, len,
47 				 SHA256_BLOCK_SIZE, sctx->buf, partial);
48 }
49 EXPORT_SYMBOL(sha256_update);
50 
51 static inline void __sha256_final(struct sha256_state *sctx, u8 *out,
52 				  size_t digest_size)
53 {
54 	size_t partial = sctx->count % SHA256_BLOCK_SIZE;
55 
56 	sha256_finup(&sctx->ctx, sctx->buf, partial, out, digest_size,
57 		     sha256_purgatory(), false);
58 	memzero_explicit(sctx, sizeof(*sctx));
59 }
60 
61 void sha256_final(struct sha256_state *sctx, u8 out[SHA256_DIGEST_SIZE])
62 {
63 	__sha256_final(sctx, out, SHA256_DIGEST_SIZE);
64 }
65 EXPORT_SYMBOL(sha256_final);
66 
67 void sha224_final(struct sha256_state *sctx, u8 out[SHA224_DIGEST_SIZE])
68 {
69 	__sha256_final(sctx, out, SHA224_DIGEST_SIZE);
70 }
71 EXPORT_SYMBOL(sha224_final);
72 
73 void sha256(const u8 *data, size_t len, u8 out[SHA256_DIGEST_SIZE])
74 {
75 	struct sha256_state sctx;
76 
77 	sha256_init(&sctx);
78 	sha256_update(&sctx, data, len);
79 	sha256_final(&sctx, out);
80 }
81 EXPORT_SYMBOL(sha256);
82 
83 MODULE_DESCRIPTION("SHA-256 Algorithm");
84 MODULE_LICENSE("GPL");
85