8 static inline uint32_t rol32(const uint32_t x
, const unsigned int n
)
10 return (x
<< n
) | (x
>> (32 - n
));
13 static inline uint32_t F(const uint32_t X
, const uint32_t Y
, const uint32_t Z
)
15 return (X
& Y
) | (~X
& Z
);
18 static inline uint32_t G(const uint32_t X
, const uint32_t Y
, const uint32_t Z
)
23 static inline uint32_t H(const uint32_t X
, const uint32_t Y
, const uint32_t Z
)
25 return (X
& Y
) ^ (X
& Z
) ^ (Y
& Z
);
29 uint32_t A
, B
, C
, D
, E
;
30 uint64_t len
; /* in bits */
35 static void __sha1_update(void *_ctx
, const uint8_t *m
)
37 struct sha1_context
*ctx
= _ctx
;
38 uint32_t A
, B
, C
, D
, E
;
48 for (i
= 0; i
< 16; i
++)
49 W
[i
] = be32toh(*(uint32_t *)(m
+ i
* sizeof(uint32_t)));
50 for (i
= 16; i
< 80; i
++)
51 W
[i
] = rol32(W
[i
- 3] ^ W
[i
- 8] ^ W
[i
- 14] ^ W
[i
- 16], 1);
53 for (i
= 0; i
<= 19; i
++) {
56 T
= rol32(A
, 5) + F(B
, C
, D
) + E
+ 0x5a827999 + W
[i
];
63 for (i
= 20; i
<= 39; i
++) {
66 T
= rol32(A
, 5) + G(B
, C
, D
) + E
+ 0x6ed9eba1 + W
[i
];
73 for (i
= 40; i
<= 59; i
++) {
76 T
= rol32(A
, 5) + H(B
, C
, D
) + E
+ 0x8f1bbcdc + W
[i
];
83 for (i
= 60; i
<= 79; i
++) {
86 T
= rol32(A
, 5) + G(B
, C
, D
) + E
+ 0xca62c1d6 + W
[i
];
101 void sha1_update(void *_ctx
, const uint8_t *m
)
103 struct sha1_context
*ctx
= _ctx
;
105 __sha1_update(ctx
, m
);
109 void _sha1_update(void *_ctx
, const uint8_t *m
, unsigned int len
)
111 struct sha1_context
*ctx
= _ctx
;
114 ctx
->m
[ctx
->m_len
] = *m
;
120 if (ctx
->m_len
== 64) {
121 __sha1_update(ctx
, ctx
->m
);
127 void *sha1_init_context(void)
129 struct sha1_context
*ctx
;
131 ctx
= malloc(sizeof(struct sha1_context
));
142 memset(ctx
->m
, 0, 64);
148 void sha1_fini_context(void *_ctx
)
150 struct sha1_context
*ctx
= _ctx
;
152 memset(ctx
, 0, sizeof(struct sha1_context
));
156 void sha1_fini(void *_ctx
)
158 struct sha1_context
*ctx
= _ctx
;
160 ctx
->m
[ctx
->m_len
] = 0x80;
162 if (ctx
->m_len
<= 64 - 8) {
163 while (ctx
->m_len
<= 64 - 8) {
164 ctx
->m
[ctx
->m_len
] = 0;
168 while (ctx
->m_len
< 64) {
169 ctx
->m
[ctx
->m_len
] = 0;
172 __sha1_update(ctx
, ctx
->m
);
173 memset(ctx
->m
, 0, 64 - 8);
175 *(uint64_t *)&ctx
->m
[64 - 8] = htobe64(ctx
->len
);
176 __sha1_update(ctx
, ctx
->m
);
179 void sha1_digest(void *_ctx
, uint8_t *digest
)
181 struct sha1_context
*ctx
= _ctx
;
183 *(uint32_t *)&digest
[0] = htobe32(ctx
->A
);
184 *(uint32_t *)&digest
[4] = htobe32(ctx
->B
);
185 *(uint32_t *)&digest
[8] = htobe32(ctx
->C
);
186 *(uint32_t *)&digest
[12] = htobe32(ctx
->D
);
187 *(uint32_t *)&digest
[16] = htobe32(ctx
->E
);