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/kernel.h> 17 #include <linux/module.h> 18 #include <linux/string.h> 19 20 /* 21 * If __DISABLE_EXPORTS is defined, then this file is being compiled for a 22 * pre-boot environment. In that case, ignore the kconfig options, pull the 23 * generic code into the same translation unit, and use that only. 24 */ 25 #ifdef __DISABLE_EXPORTS 26 #include "sha256-generic.c" 27 #endif 28 29 static inline bool sha256_purgatory(void) 30 { 31 return __is_defined(__DISABLE_EXPORTS); 32 } 33 34 static inline void sha256_blocks(u32 state[SHA256_STATE_WORDS], const u8 *data, 35 size_t nblocks) 36 { 37 sha256_choose_blocks(state, data, nblocks, sha256_purgatory(), false); 38 } 39 40 void sha256_update(struct sha256_state *sctx, const u8 *data, size_t len) 41 { 42 size_t partial = sctx->count % SHA256_BLOCK_SIZE; 43 44 sctx->count += len; 45 BLOCK_HASH_UPDATE_BLOCKS(sha256_blocks, sctx->ctx.state, data, len, 46 SHA256_BLOCK_SIZE, sctx->buf, partial); 47 } 48 EXPORT_SYMBOL(sha256_update); 49 50 static inline void __sha256_final(struct sha256_state *sctx, u8 *out, 51 size_t digest_size) 52 { 53 size_t partial = sctx->count % SHA256_BLOCK_SIZE; 54 55 sha256_finup(&sctx->ctx, sctx->buf, partial, out, digest_size, 56 sha256_purgatory(), false); 57 memzero_explicit(sctx, sizeof(*sctx)); 58 } 59 60 void sha256_final(struct sha256_state *sctx, u8 out[SHA256_DIGEST_SIZE]) 61 { 62 __sha256_final(sctx, out, SHA256_DIGEST_SIZE); 63 } 64 EXPORT_SYMBOL(sha256_final); 65 66 void sha224_final(struct sha256_state *sctx, u8 out[SHA224_DIGEST_SIZE]) 67 { 68 __sha256_final(sctx, out, SHA224_DIGEST_SIZE); 69 } 70 EXPORT_SYMBOL(sha224_final); 71 72 void sha256(const u8 *data, size_t len, u8 out[SHA256_DIGEST_SIZE]) 73 { 74 struct sha256_state sctx; 75 76 sha256_init(&sctx); 77 sha256_update(&sctx, data, len); 78 sha256_final(&sctx, out); 79 } 80 EXPORT_SYMBOL(sha256); 81 82 MODULE_DESCRIPTION("SHA-256 Algorithm"); 83 MODULE_LICENSE("GPL"); 84