1 // Support for Calculation of SHA1 in SW
3 // Copyright (C) 2006-2011 IBM Corporation
6 // Stefan Berger <stefanb@linux.vnet.ibm.com>
8 // This file may be distributed under the terms of the GNU LGPLv3 license.
10 // See: http://www.itl.nist.gov/fipspubs/fip180-1.htm
11 // RFC3174, Wikipedia's SHA1 alogrithm description
15 #include "byteorder.h" // cpu_to_*, __swab64
16 #include "sha1.h" // sha1
17 #include "string.h" // memcpy
18 #include "x86.h" // rol
20 typedef struct _sha1_ctx {
26 sha1_block(u32 *w, sha1_ctx *ctx)
33 static const u32 sha_ko[4] = {
34 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xca62c1d6 };
36 /* change endianness of given data */
37 for (i = 0; i < 16; i++)
38 w[i] = be32_to_cpu(w[i]);
40 for (i = 16; i <= 79; i++) {
41 tmp = w[i-3] ^ w[i-8] ^ w[i-14] ^ w[i-16];
51 for (i = 0; i <= 79; i++) {
53 f = (b & c) | ((b ^ 0xffffffff) & d);
59 f = (b & c) | (b & d) | (c & d);
87 sha1_do(sha1_ctx *ctx, const u8 *data32, u32 length)
95 /* treat data in 64-byte chunks */
96 for (offset = 0; length - offset >= 64; offset += 64) {
97 memcpy(w, data32 + offset, 64);
98 sha1_block((u32 *)w, ctx);
102 /* last block with less than 64 bytes */
103 num = length - offset;
106 memcpy(w, data32 + offset, num);
107 ((u8 *)w)[num] = 0x80;
108 if (64 - (num + 1) > 0)
109 memset( &((u8 *)w)[num + 1], 0x0, 64 - (num + 1));
112 /* cannot append number of bits here */
113 sha1_block((u32 *)w, ctx);
117 /* write number of bits to end of block */
118 tmp = __swab64(bits);
119 memcpy(&w[14], &tmp, 8);
123 /* need to switch result's endianness */
124 for (num = 0; num < 5; num++)
125 ctx->h[num] = cpu_to_be32(ctx->h[num]);
130 sha1(const u8 *data, u32 length, u8 *hash)
143 sha1_do(&ctx, data, length);
144 memcpy(hash, &ctx.h[0], 20);