1 // see copyright notice in sha1.h
4 void SHA1::addBytes(const uint8_t* input, size_t length)
7 m_buffer[m_cursor++] = *input++;
9 if (m_cursor == 64) processBlock();
13 void SHA1::computeHash(uint8_t *digest)
16 memset(digest, 0, 20);
17 for (size_t i = 0; i < 5; ++i) {
18 // Treat hashValue as a big-endian value.
19 uint32_t hashValue = m_hash[i];
20 for (int j = 0; j < 4; ++j) {
21 digest[4*i + (3-j)] = hashValue & 0xFF;
31 m_buffer[m_cursor++] = 0x80;
33 while (m_cursor < 64) m_buffer[m_cursor++] = 0x00;
37 for (size_t i = m_cursor; i < 56; ++i)
40 uint64_t bits = m_totalBytes*8;
41 for (int i = 0; i < 8; ++i) {
42 m_buffer[56 + (7-i)] = bits & 0xFF;
49 void SHA1::processBlock()
51 uint32_t w[80] = { 0 };
52 for (int t = 0; t < 16; ++t)
53 w[t] = (m_buffer[t*4] << 24) |
54 (m_buffer[t*4 + 1] << 16) |
55 (m_buffer[t*4 + 2] << 8) |
57 for (int t = 16; t < 80; ++t)
58 w[t] = rotateLeft(1, w[t-3] ^ w[t-8] ^ w[t-14] ^ w[t-16]);
60 uint32_t a = m_hash[0], b = m_hash[1];
61 uint32_t c = m_hash[2], d = m_hash[3];
62 uint32_t e = m_hash[4];
64 for (int t = 0; t < 80; ++t) {
65 uint32_t temp = rotateLeft(5, a) + f(t, b, c, d) + e + w[t] + k(t);
67 c = rotateLeft(30, b);
71 m_hash[0] += a; m_hash[1] += b;
72 m_hash[2] += c; m_hash[3] += d;
82 m_hash[0] = 0x67452301; m_hash[1] = 0xefcdab89;
83 m_hash[2] = 0x98badcfe; m_hash[3] = 0x10325476;
84 m_hash[4] = 0xc3d2e1f0;
85 memset(m_buffer, 0, sizeof(m_buffer));
89 static void expectSHA1(const char *input, int repeat, const char *expected)
92 const uint8_t *inp = (const uint8_t *)input;
93 int len = strlen(input);
94 for (int i = 0; i < repeat; ++i) sha1.addBytes(inp, len);
95 uint8_t digest[20]; sha1.computeHash(digest);
96 char actual[64], *buffer = actual;
97 for (size_t i = 0; i < 20; ++i) {
98 snprintf(buffer, 3, "%02X", digest[i]);
101 if( !strcmp(actual, expected) ) return;
102 printf("input: %s, repeat: %d, actual: %s, expected: %s\n",
103 input, repeat, actual, expected);
106 int main(int ac, char **av)
108 // Examples taken from sample code in RFC 3174.
109 expectSHA1("abc", 1, "A9993E364706816ABA3E25717850C26C9CD0D89D");
110 expectSHA1("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq",
111 1, "84983E441C3BD26EBAAE4AA1F95129E5E54670F1");
113 1000000, "34AA973CD4C4DAA4F61EEB2BDBAD27316534016F");
114 expectSHA1("0123456701234567012345670123456701234567012345670123456701234567",
115 10, "DEA356A2CDDD90C7A7ECEDC5EBB563934F460452");