3 * The sha1 hash function.
4 * Defined by http://www.itl.nist.gov/fipspubs/fip180-1.htm.
7 /* nettle, low-level cryptographics library
9 * Copyright (C) 2001 Peter Gutmann, Andrew Kuchling, Niels Möller
11 * The nettle library is free software; you can redistribute it and/or modify
12 * it under the terms of the GNU Lesser General Public License as published by
13 * the Free Software Foundation; either version 2.1 of the License, or (at your
14 * option) any later version.
16 * The nettle library is distributed in the hope that it will be useful, but
17 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
18 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
19 * License for more details.
21 * You should have received a copy of the GNU Lesser General Public License
22 * along with the nettle library; see the file COPYING.LIB. If not, write to
23 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
27 /* Here's the first paragraph of Peter Gutmann's posting,
28 * <30ajo5$oe8@ccu2.auckland.ac.nz>:
30 * The following is my SHA (FIPS 180) code updated to allow use of the "fixed"
31 * SHA, thanks to Jim Gillogly and an anonymous contributor for the information on
32 * what's changed in the new version. The fix is a simple change which involves
33 * adding a single rotate in the initial expansion function. It is unknown
34 * whether this is an optimal solution to the problem which was discovered in the
35 * SHA or whether it's simply a bandaid which fixes the problem with a minimum of
36 * effort (for example the reengineering of a great many Capstone chips).
50 #include "nettle-write.h"
52 /* Initialize the SHA values */
54 sha1_init(struct sha1_ctx
*ctx
)
56 /* FIXME: Put the buffer last in the struct, and arrange so that we
57 can initialize with a single memcpy. */
58 static const uint32_t iv
[_SHA1_DIGEST_LENGTH
] =
60 /* SHA initial values */
68 memcpy(ctx
->state
, iv
, sizeof(ctx
->state
));
69 ctx
->count_low
= ctx
->count_high
= 0;
71 /* Initialize buffer */
75 #define COMPRESS(ctx, data) (_nettle_sha1_compress((ctx)->state, data))
78 sha1_update(struct sha1_ctx
*ctx
,
79 unsigned length
, const uint8_t *data
)
81 MD_UPDATE (ctx
, length
, data
, COMPRESS
, MD_INCR(ctx
));
85 sha1_digest(struct sha1_ctx
*ctx
,
91 assert(length
<= SHA1_DIGEST_SIZE
);
93 MD_PAD(ctx
, 8, COMPRESS
);
95 /* There are 512 = 2^9 bits in one block */
96 high
= (ctx
->count_high
<< 9) | (ctx
->count_low
>> 23);
97 low
= (ctx
->count_low
<< 9) | (ctx
->index
<< 3);
99 /* append the 64 bit count */
100 WRITE_UINT32(ctx
->block
+ (SHA1_DATA_SIZE
- 8), high
);
101 WRITE_UINT32(ctx
->block
+ (SHA1_DATA_SIZE
- 4), low
);
102 _nettle_sha1_compress(ctx
->state
, ctx
->block
);
104 _nettle_write_be32(length
, digest
, ctx
->state
);