• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* SHA1 module */
2 
3 /* This module provides an interface to the SHA1 algorithm */
4 
5 /* See below for information about the original code this module was
6    based upon. Additional work performed by:
7 
8    Andrew Kuchling (amk@amk.ca)
9    Greg Stein (gstein@lyra.org)
10    Trevor Perrin (trevp@trevp.net)
11 
12    Copyright (C) 2005-2007   Gregory P. Smith (greg@krypto.org)
13    Licensed to PSF under a Contributor Agreement.
14 
15 */
16 
17 /* SHA1 objects */
18 
19 #include "Python.h"
20 #include "hashlib.h"
21 #include "pystrhex.h"
22 
23 /*[clinic input]
24 module _sha1
25 class SHA1Type "SHA1object *" "&PyType_Type"
26 [clinic start generated code]*/
27 /*[clinic end generated code: output=da39a3ee5e6b4b0d input=3dc9a20d1becb759]*/
28 
29 /* Some useful types */
30 
31 #if SIZEOF_INT == 4
32 typedef unsigned int SHA1_INT32;        /* 32-bit integer */
33 typedef long long SHA1_INT64;        /* 64-bit integer */
34 #else
35 /* not defined. compilation will die. */
36 #endif
37 
38 /* The SHA1 block size and message digest sizes, in bytes */
39 
40 #define SHA1_BLOCKSIZE    64
41 #define SHA1_DIGESTSIZE   20
42 
43 /* The structure for storing SHA1 info */
44 
45 struct sha1_state {
46     SHA1_INT64 length;
47     SHA1_INT32 state[5], curlen;
48     unsigned char buf[SHA1_BLOCKSIZE];
49 };
50 
51 typedef struct {
52     PyObject_HEAD
53 
54     struct sha1_state hash_state;
55 } SHA1object;
56 
57 #include "clinic/sha1module.c.h"
58 
59 /* ------------------------------------------------------------------------
60  *
61  * This code for the SHA1 algorithm was noted as public domain. The
62  * original headers are pasted below.
63  *
64  * Several changes have been made to make it more compatible with the
65  * Python environment and desired interface.
66  *
67  */
68 
69 /* LibTomCrypt, modular cryptographic library -- Tom St Denis
70  *
71  * LibTomCrypt is a library that provides various cryptographic
72  * algorithms in a highly modular and flexible manner.
73  *
74  * The library is free for all purposes without any express
75  * guarantee it works.
76  *
77  * Tom St Denis, tomstdenis@gmail.com, http://libtom.org
78  */
79 
80 /* rotate the hard way (platform optimizations could be done) */
81 #define ROL(x, y) ( (((unsigned long)(x)<<(unsigned long)((y)&31)) | (((unsigned long)(x)&0xFFFFFFFFUL)>>(unsigned long)(32-((y)&31)))) & 0xFFFFFFFFUL)
82 #define ROLc(x, y) ( (((unsigned long)(x)<<(unsigned long)((y)&31)) | (((unsigned long)(x)&0xFFFFFFFFUL)>>(unsigned long)(32-((y)&31)))) & 0xFFFFFFFFUL)
83 
84 /* Endian Neutral macros that work on all platforms */
85 
86 #define STORE32H(x, y)                                                                     \
87      { (y)[0] = (unsigned char)(((x)>>24)&255); (y)[1] = (unsigned char)(((x)>>16)&255);   \
88        (y)[2] = (unsigned char)(((x)>>8)&255); (y)[3] = (unsigned char)((x)&255); }
89 
90 #define LOAD32H(x, y)                            \
91      { x = ((unsigned long)((y)[0] & 255)<<24) | \
92            ((unsigned long)((y)[1] & 255)<<16) | \
93            ((unsigned long)((y)[2] & 255)<<8)  | \
94            ((unsigned long)((y)[3] & 255)); }
95 
96 #define STORE64H(x, y)                                                                     \
97    { (y)[0] = (unsigned char)(((x)>>56)&255); (y)[1] = (unsigned char)(((x)>>48)&255);     \
98      (y)[2] = (unsigned char)(((x)>>40)&255); (y)[3] = (unsigned char)(((x)>>32)&255);     \
99      (y)[4] = (unsigned char)(((x)>>24)&255); (y)[5] = (unsigned char)(((x)>>16)&255);     \
100      (y)[6] = (unsigned char)(((x)>>8)&255); (y)[7] = (unsigned char)((x)&255); }
101 
102 
103 /* SHA1 macros */
104 
105 #define F0(x,y,z)  (z ^ (x & (y ^ z)))
106 #define F1(x,y,z)  (x ^ y ^ z)
107 #define F2(x,y,z)  ((x & y) | (z & (x | y)))
108 #define F3(x,y,z)  (x ^ y ^ z)
109 
sha1_compress(struct sha1_state * sha1,unsigned char * buf)110 static void sha1_compress(struct sha1_state *sha1, unsigned char *buf)
111 {
112     SHA1_INT32 a,b,c,d,e,W[80],i;
113 
114     /* copy the state into 512-bits into W[0..15] */
115     for (i = 0; i < 16; i++) {
116         LOAD32H(W[i], buf + (4*i));
117     }
118 
119     /* copy state */
120     a = sha1->state[0];
121     b = sha1->state[1];
122     c = sha1->state[2];
123     d = sha1->state[3];
124     e = sha1->state[4];
125 
126     /* expand it */
127     for (i = 16; i < 80; i++) {
128         W[i] = ROL(W[i-3] ^ W[i-8] ^ W[i-14] ^ W[i-16], 1);
129     }
130 
131     /* compress */
132     /* round one */
133     #define FF_0(a,b,c,d,e,i) e = (ROLc(a, 5) + F0(b,c,d) + e + W[i] + 0x5a827999UL); b = ROLc(b, 30);
134     #define FF_1(a,b,c,d,e,i) e = (ROLc(a, 5) + F1(b,c,d) + e + W[i] + 0x6ed9eba1UL); b = ROLc(b, 30);
135     #define FF_2(a,b,c,d,e,i) e = (ROLc(a, 5) + F2(b,c,d) + e + W[i] + 0x8f1bbcdcUL); b = ROLc(b, 30);
136     #define FF_3(a,b,c,d,e,i) e = (ROLc(a, 5) + F3(b,c,d) + e + W[i] + 0xca62c1d6UL); b = ROLc(b, 30);
137 
138     for (i = 0; i < 20; ) {
139        FF_0(a,b,c,d,e,i++);
140        FF_0(e,a,b,c,d,i++);
141        FF_0(d,e,a,b,c,i++);
142        FF_0(c,d,e,a,b,i++);
143        FF_0(b,c,d,e,a,i++);
144     }
145 
146     /* round two */
147     for (; i < 40; )  {
148        FF_1(a,b,c,d,e,i++);
149        FF_1(e,a,b,c,d,i++);
150        FF_1(d,e,a,b,c,i++);
151        FF_1(c,d,e,a,b,i++);
152        FF_1(b,c,d,e,a,i++);
153     }
154 
155     /* round three */
156     for (; i < 60; )  {
157        FF_2(a,b,c,d,e,i++);
158        FF_2(e,a,b,c,d,i++);
159        FF_2(d,e,a,b,c,i++);
160        FF_2(c,d,e,a,b,i++);
161        FF_2(b,c,d,e,a,i++);
162     }
163 
164     /* round four */
165     for (; i < 80; )  {
166        FF_3(a,b,c,d,e,i++);
167        FF_3(e,a,b,c,d,i++);
168        FF_3(d,e,a,b,c,i++);
169        FF_3(c,d,e,a,b,i++);
170        FF_3(b,c,d,e,a,i++);
171     }
172 
173     #undef FF_0
174     #undef FF_1
175     #undef FF_2
176     #undef FF_3
177 
178     /* store */
179     sha1->state[0] = sha1->state[0] + a;
180     sha1->state[1] = sha1->state[1] + b;
181     sha1->state[2] = sha1->state[2] + c;
182     sha1->state[3] = sha1->state[3] + d;
183     sha1->state[4] = sha1->state[4] + e;
184 }
185 
186 /**
187    Initialize the hash state
188    @param sha1   The hash state you wish to initialize
189 */
190 static void
sha1_init(struct sha1_state * sha1)191 sha1_init(struct sha1_state *sha1)
192 {
193    assert(sha1 != NULL);
194    sha1->state[0] = 0x67452301UL;
195    sha1->state[1] = 0xefcdab89UL;
196    sha1->state[2] = 0x98badcfeUL;
197    sha1->state[3] = 0x10325476UL;
198    sha1->state[4] = 0xc3d2e1f0UL;
199    sha1->curlen = 0;
200    sha1->length = 0;
201 }
202 
203 /**
204    Process a block of memory though the hash
205    @param sha1   The hash state
206    @param in     The data to hash
207    @param inlen  The length of the data (octets)
208 */
209 static void
sha1_process(struct sha1_state * sha1,const unsigned char * in,Py_ssize_t inlen)210 sha1_process(struct sha1_state *sha1,
211                   const unsigned char *in, Py_ssize_t inlen)
212 {
213     Py_ssize_t n;
214 
215     assert(sha1 != NULL);
216     assert(in != NULL);
217     assert(sha1->curlen <= sizeof(sha1->buf));
218 
219     while (inlen > 0) {
220         if (sha1->curlen == 0 && inlen >= SHA1_BLOCKSIZE) {
221            sha1_compress(sha1, (unsigned char *)in);
222            sha1->length   += SHA1_BLOCKSIZE * 8;
223            in             += SHA1_BLOCKSIZE;
224            inlen          -= SHA1_BLOCKSIZE;
225         } else {
226            n = Py_MIN(inlen, (Py_ssize_t)(SHA1_BLOCKSIZE - sha1->curlen));
227            memcpy(sha1->buf + sha1->curlen, in, (size_t)n);
228            sha1->curlen   += (SHA1_INT32)n;
229            in             += n;
230            inlen          -= n;
231            if (sha1->curlen == SHA1_BLOCKSIZE) {
232               sha1_compress(sha1, sha1->buf);
233               sha1->length += 8*SHA1_BLOCKSIZE;
234               sha1->curlen = 0;
235            }
236        }
237     }
238 }
239 
240 /**
241    Terminate the hash to get the digest
242    @param sha1  The hash state
243    @param out [out] The destination of the hash (20 bytes)
244 */
245 static void
sha1_done(struct sha1_state * sha1,unsigned char * out)246 sha1_done(struct sha1_state *sha1, unsigned char *out)
247 {
248     int i;
249 
250     assert(sha1 != NULL);
251     assert(out != NULL);
252     assert(sha1->curlen < sizeof(sha1->buf));
253 
254     /* increase the length of the message */
255     sha1->length += sha1->curlen * 8;
256 
257     /* append the '1' bit */
258     sha1->buf[sha1->curlen++] = (unsigned char)0x80;
259 
260     /* if the length is currently above 56 bytes we append zeros
261      * then compress.  Then we can fall back to padding zeros and length
262      * encoding like normal.
263      */
264     if (sha1->curlen > 56) {
265         while (sha1->curlen < 64) {
266             sha1->buf[sha1->curlen++] = (unsigned char)0;
267         }
268         sha1_compress(sha1, sha1->buf);
269         sha1->curlen = 0;
270     }
271 
272     /* pad upto 56 bytes of zeroes */
273     while (sha1->curlen < 56) {
274         sha1->buf[sha1->curlen++] = (unsigned char)0;
275     }
276 
277     /* store length */
278     STORE64H(sha1->length, sha1->buf+56);
279     sha1_compress(sha1, sha1->buf);
280 
281     /* copy output */
282     for (i = 0; i < 5; i++) {
283         STORE32H(sha1->state[i], out+(4*i));
284     }
285 }
286 
287 
288 /* .Source: /cvs/libtom/libtomcrypt/src/hashes/sha1.c,v $ */
289 /* .Revision: 1.10 $ */
290 /* .Date: 2007/05/12 14:25:28 $ */
291 
292 /*
293  * End of copied SHA1 code.
294  *
295  * ------------------------------------------------------------------------
296  */
297 
298 static PyTypeObject SHA1type;
299 
300 
301 static SHA1object *
newSHA1object(void)302 newSHA1object(void)
303 {
304     return (SHA1object *)PyObject_New(SHA1object, &SHA1type);
305 }
306 
307 
308 /* Internal methods for a hash object */
309 
310 static void
SHA1_dealloc(PyObject * ptr)311 SHA1_dealloc(PyObject *ptr)
312 {
313     PyObject_Del(ptr);
314 }
315 
316 
317 /* External methods for a hash object */
318 
319 /*[clinic input]
320 SHA1Type.copy
321 
322 Return a copy of the hash object.
323 [clinic start generated code]*/
324 
325 static PyObject *
SHA1Type_copy_impl(SHA1object * self)326 SHA1Type_copy_impl(SHA1object *self)
327 /*[clinic end generated code: output=b4e001264620f02a input=b7eae10df6f89b36]*/
328 {
329     SHA1object *newobj;
330 
331     if ((newobj = newSHA1object()) == NULL)
332         return NULL;
333 
334     newobj->hash_state = self->hash_state;
335     return (PyObject *)newobj;
336 }
337 
338 /*[clinic input]
339 SHA1Type.digest
340 
341 Return the digest value as a bytes object.
342 [clinic start generated code]*/
343 
344 static PyObject *
SHA1Type_digest_impl(SHA1object * self)345 SHA1Type_digest_impl(SHA1object *self)
346 /*[clinic end generated code: output=2f05302a7aa2b5cb input=13824b35407444bd]*/
347 {
348     unsigned char digest[SHA1_DIGESTSIZE];
349     struct sha1_state temp;
350 
351     temp = self->hash_state;
352     sha1_done(&temp, digest);
353     return PyBytes_FromStringAndSize((const char *)digest, SHA1_DIGESTSIZE);
354 }
355 
356 /*[clinic input]
357 SHA1Type.hexdigest
358 
359 Return the digest value as a string of hexadecimal digits.
360 [clinic start generated code]*/
361 
362 static PyObject *
SHA1Type_hexdigest_impl(SHA1object * self)363 SHA1Type_hexdigest_impl(SHA1object *self)
364 /*[clinic end generated code: output=4161fd71e68c6659 input=97691055c0c74ab0]*/
365 {
366     unsigned char digest[SHA1_DIGESTSIZE];
367     struct sha1_state temp;
368 
369     /* Get the raw (binary) digest value */
370     temp = self->hash_state;
371     sha1_done(&temp, digest);
372 
373     return _Py_strhex((const char *)digest, SHA1_DIGESTSIZE);
374 }
375 
376 /*[clinic input]
377 SHA1Type.update
378 
379     obj: object
380     /
381 
382 Update this hash object's state with the provided string.
383 [clinic start generated code]*/
384 
385 static PyObject *
SHA1Type_update(SHA1object * self,PyObject * obj)386 SHA1Type_update(SHA1object *self, PyObject *obj)
387 /*[clinic end generated code: output=d9902f0e5015e9ae input=aad8e07812edbba3]*/
388 {
389     Py_buffer buf;
390 
391     GET_BUFFER_VIEW_OR_ERROUT(obj, &buf);
392 
393     sha1_process(&self->hash_state, buf.buf, buf.len);
394 
395     PyBuffer_Release(&buf);
396     Py_RETURN_NONE;
397 }
398 
399 static PyMethodDef SHA1_methods[] = {
400     SHA1TYPE_COPY_METHODDEF
401     SHA1TYPE_DIGEST_METHODDEF
402     SHA1TYPE_HEXDIGEST_METHODDEF
403     SHA1TYPE_UPDATE_METHODDEF
404     {NULL,        NULL}         /* sentinel */
405 };
406 
407 static PyObject *
SHA1_get_block_size(PyObject * self,void * closure)408 SHA1_get_block_size(PyObject *self, void *closure)
409 {
410     return PyLong_FromLong(SHA1_BLOCKSIZE);
411 }
412 
413 static PyObject *
SHA1_get_name(PyObject * self,void * closure)414 SHA1_get_name(PyObject *self, void *closure)
415 {
416     return PyUnicode_FromStringAndSize("sha1", 4);
417 }
418 
419 static PyObject *
sha1_get_digest_size(PyObject * self,void * closure)420 sha1_get_digest_size(PyObject *self, void *closure)
421 {
422     return PyLong_FromLong(SHA1_DIGESTSIZE);
423 }
424 
425 
426 static PyGetSetDef SHA1_getseters[] = {
427     {"block_size",
428      (getter)SHA1_get_block_size, NULL,
429      NULL,
430      NULL},
431     {"name",
432      (getter)SHA1_get_name, NULL,
433      NULL,
434      NULL},
435     {"digest_size",
436      (getter)sha1_get_digest_size, NULL,
437      NULL,
438      NULL},
439     {NULL}  /* Sentinel */
440 };
441 
442 static PyTypeObject SHA1type = {
443     PyVarObject_HEAD_INIT(NULL, 0)
444     "_sha1.sha1",               /*tp_name*/
445     sizeof(SHA1object), /*tp_basicsize*/
446     0,                  /*tp_itemsize*/
447     /* methods */
448     SHA1_dealloc,       /*tp_dealloc*/
449     0,                  /*tp_print*/
450     0,                  /*tp_getattr*/
451     0,                  /*tp_setattr*/
452     0,                  /*tp_reserved*/
453     0,                  /*tp_repr*/
454     0,                  /*tp_as_number*/
455     0,                  /*tp_as_sequence*/
456     0,                  /*tp_as_mapping*/
457     0,                  /*tp_hash*/
458     0,                  /*tp_call*/
459     0,                  /*tp_str*/
460     0,                  /*tp_getattro*/
461     0,                  /*tp_setattro*/
462     0,                  /*tp_as_buffer*/
463     Py_TPFLAGS_DEFAULT, /*tp_flags*/
464     0,                  /*tp_doc*/
465     0,                  /*tp_traverse*/
466     0,                  /*tp_clear*/
467     0,                  /*tp_richcompare*/
468     0,                  /*tp_weaklistoffset*/
469     0,                  /*tp_iter*/
470     0,                  /*tp_iternext*/
471     SHA1_methods,       /* tp_methods */
472     NULL,               /* tp_members */
473     SHA1_getseters,      /* tp_getset */
474 };
475 
476 
477 /* The single module-level function: new() */
478 
479 /*[clinic input]
480 _sha1.sha1
481 
482     string: object(c_default="NULL") = b''
483 
484 Return a new SHA1 hash object; optionally initialized with a string.
485 [clinic start generated code]*/
486 
487 static PyObject *
_sha1_sha1_impl(PyObject * module,PyObject * string)488 _sha1_sha1_impl(PyObject *module, PyObject *string)
489 /*[clinic end generated code: output=e5982830d1dece51 input=27ea54281d995ec2]*/
490 {
491     SHA1object *new;
492     Py_buffer buf;
493 
494     if (string)
495         GET_BUFFER_VIEW_OR_ERROUT(string, &buf);
496 
497     if ((new = newSHA1object()) == NULL) {
498         if (string)
499             PyBuffer_Release(&buf);
500         return NULL;
501     }
502 
503     sha1_init(&new->hash_state);
504 
505     if (PyErr_Occurred()) {
506         Py_DECREF(new);
507         if (string)
508             PyBuffer_Release(&buf);
509         return NULL;
510     }
511     if (string) {
512         sha1_process(&new->hash_state, buf.buf, buf.len);
513         PyBuffer_Release(&buf);
514     }
515 
516     return (PyObject *)new;
517 }
518 
519 
520 /* List of functions exported by this module */
521 
522 static struct PyMethodDef SHA1_functions[] = {
523     _SHA1_SHA1_METHODDEF
524     {NULL,      NULL}            /* Sentinel */
525 };
526 
527 
528 /* Initialize this module. */
529 
530 #define insint(n,v) { PyModule_AddIntConstant(m,n,v); }
531 
532 
533 static struct PyModuleDef _sha1module = {
534         PyModuleDef_HEAD_INIT,
535         "_sha1",
536         NULL,
537         -1,
538         SHA1_functions,
539         NULL,
540         NULL,
541         NULL,
542         NULL
543 };
544 
545 PyMODINIT_FUNC
PyInit__sha1(void)546 PyInit__sha1(void)
547 {
548     PyObject *m;
549 
550     Py_TYPE(&SHA1type) = &PyType_Type;
551     if (PyType_Ready(&SHA1type) < 0)
552         return NULL;
553 
554     m = PyModule_Create(&_sha1module);
555     if (m == NULL)
556         return NULL;
557 
558     Py_INCREF((PyObject *)&SHA1type);
559     PyModule_AddObject(m, "SHA1Type", (PyObject *)&SHA1type);
560     return m;
561 }
562