1 // Copyright (c) 2009 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
7 #include "base/basictypes.h"
11 // Implementation of SHA-1. Only handles data in byte-sized blocks,
12 // which simplifies the code a fair bit.
14 // This file also contains an HMAC implementation using SHA-1
16 // Identifier names follow notation in FIPS PUB 180-3, where you'll
17 // also find a description of the algorithm:
18 // http://csrc.nist.gov/publications/fips/fips180-3/fips180-3_final.pdf
22 // SecureHashAlgorithm sha;
23 // while(there is data to hash)
24 // sha.Update(moredata, size of data);
26 // memcpy(somewhere, sha.Digest(), 20);
28 // to reuse the instance of sha, call sha.Init();
30 // TODO(jhawkins): Replace this implementation with a per-platform
31 // implementation using each platform's crypto library.
33 class SecureHashAlgorithm
{
35 SecureHashAlgorithm() { Init(); }
37 static const int kDigestSizeBytes
;
40 void Update(const void* data
, size_t nbytes
);
43 // 20 bytes of message digest.
44 const unsigned char* Digest() const {
45 return reinterpret_cast<const unsigned char*>(H
);
65 static inline uint32
f(uint32 t
, uint32 B
, uint32 C
, uint32 D
) {
67 return (B
& C
) | ((~B
) & D
);
71 return (B
& C
) | (B
& D
) | (C
& D
);
77 static inline uint32
S(uint32 n
, uint32 X
) {
78 return (X
<< n
) | (X
>> (32-n
));
81 static inline uint32
K(uint32 t
) {
93 static inline void swapends(uint32
& t
) {
94 t
= ((t
& 0xff000000) >> 24) |
95 ((t
& 0xff0000) >> 8) |
100 const int SecureHashAlgorithm::kDigestSizeBytes
= 20;
102 void SecureHashAlgorithm::Init() {
112 void SecureHashAlgorithm::Final() {
116 for (int t
= 0; t
< 5; ++t
)
120 void SecureHashAlgorithm::Update(const void* data
, size_t nbytes
) {
121 const uint8
* d
= reinterpret_cast<const uint8
*>(data
);
130 void SecureHashAlgorithm::Pad() {
134 // pad out to next block
141 while (cursor
< 64-4)
144 M
[64-4] = (l
& 0xff000000) >> 24;
145 M
[64-3] = (l
& 0xff0000) >> 16;
146 M
[64-2] = (l
& 0xff00) >> 8;
147 M
[64-1] = (l
& 0xff);
150 void SecureHashAlgorithm::Process() {
153 // Each a...e corresponds to a section in the FIPS 180-3 algorithm.
157 // W and M are in a union, so no need to memcpy.
158 // memcpy(W, M, sizeof(M));
159 for (t
= 0; t
< 16; ++t
)
163 for (t
= 16; t
< 80; ++t
)
164 W
[t
] = S(1, W
[t
- 3] ^ W
[t
- 8] ^ W
[t
- 14] ^ W
[t
- 16]);
174 for (t
= 0; t
< 80; ++t
) {
175 uint32 TEMP
= S(5, A
) + f(t
, B
, C
, D
) + E
+ W
[t
] + K(t
);
193 std::string
SHA1HashString(const std::string
& str
) {
194 SecureHashAlgorithm sha
;
195 sha
.Update(str
.c_str(), str
.length());
197 std::string
out(reinterpret_cast<const char*>(sha
.Digest()),
198 SecureHashAlgorithm::kDigestSizeBytes
);