blob: 0504fad5d3b3d09284667a95c3bd8200f8f7737a [file] [log] [blame]
Guido van Rossum29d2acc1999-03-24 19:03:59 +00001/***********************************************************
2Copyright 1999 by Stichting Mathematisch Centrum, Amsterdam,
3The Netherlands.
4
5 All Rights Reserved
6
7Permission to use, copy, modify, and distribute this software and its
8documentation for any purpose and without fee is hereby granted,
9provided that the above copyright notice appear in all copies and that
10both that copyright notice and this permission notice appear in
11supporting documentation, and that the names of Stichting Mathematisch
12Centrum or CWI or Corporation for National Research Initiatives or
13CNRI not be used in advertising or publicity pertaining to
14distribution of the software without specific, written prior
15permission.
16
17While CWI is the initial source for this software, a modified version
18is made available by the Corporation for National Research Initiatives
19(CNRI) at the Internet address ftp://ftp.python.org.
20
21STICHTING MATHEMATISCH CENTRUM AND CNRI DISCLAIM ALL WARRANTIES WITH
22REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF
23MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH
24CENTRUM OR CNRI BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL
25DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
26PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
27TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
28PERFORMANCE OF THIS SOFTWARE.
29
30******************************************************************/
31
32/* SHA module */
33
34/* This module provides an interface to NIST's Secure Hash Algorithm */
35
36/* See below for information about the original code this module was
37 based upon. Additional work performed by:
38
39 Andrew Kuchling (amk1@erols.com)
40 Greg Stein (gstein@lyra.org)
41*/
42
43/* SHA objects */
44
45#include "Python.h"
46
47
48/* Endianness testing and definitions */
49#define TestEndianness(variable) {int i=1; variable=PCT_BIG_ENDIAN;\
50 if (*((char*)&i)==1) variable=PCT_LITTLE_ENDIAN;}
51
52#define PCT_LITTLE_ENDIAN 1
53#define PCT_BIG_ENDIAN 0
54
55/* Some useful types */
56
57typedef unsigned char SHA_BYTE;
58
59#if SIZEOF_INT == 4
60typedef unsigned int SHA_INT32; /* 32-bit integer */
61#else
62/* not defined. compilation will die. */
63#endif
64
65/* The SHA block size and message digest sizes, in bytes */
66
67#define SHA_BLOCKSIZE 64
68#define SHA_DIGESTSIZE 20
69
70/* The structure for storing SHS info */
71
72typedef struct {
73 PyObject_HEAD
74 SHA_INT32 digest[5]; /* Message digest */
75 SHA_INT32 count_lo, count_hi; /* 64-bit bit count */
76 SHA_BYTE data[SHA_BLOCKSIZE]; /* SHA data buffer */
77 int Endianness;
78 int local; /* unprocessed amount in data */
79} SHAobject;
80
81/* When run on a little-endian CPU we need to perform byte reversal on an
82 array of longwords. */
83
84static void longReverse(buffer, byteCount, Endianness)
85 SHA_INT32 *buffer;
86 int byteCount, Endianness;
87{
88 SHA_INT32 value;
89
90 if ( Endianness == PCT_BIG_ENDIAN )
91 return;
92
93 byteCount /= sizeof(*buffer);
94 while( byteCount-- )
95 {
96 value = *buffer;
97 value = ( ( value & 0xFF00FF00L ) >> 8 ) | \
98 ( ( value & 0x00FF00FFL ) << 8 );
99 *buffer++ = ( value << 16 ) | ( value >> 16 );
100 }
101}
102
103static void SHAcopy(src, dest)
104 SHAobject *src, *dest;
105{
106 dest->Endianness = src->Endianness;
107 dest->local = src->local;
108 dest->count_lo = src->count_lo;
109 dest->count_hi = src->count_hi;
110 memcpy(dest->digest, src->digest, sizeof(src->digest));
111 memcpy(dest->data, src->data, sizeof(src->data));
112}
113
114
115/* ------------------------------------------------------------------------
116 *
117 * This code for the SHA algorithm was noted as public domain. The original
118 * headers are pasted below.
119 *
120 * Several changes have been made to make it more compatible with the
121 * Python environment and desired interface.
122 *
123 */
124
125/* NIST Secure Hash Algorithm */
126/* heavily modified by Uwe Hollerbach <uh@alumni.caltech edu> */
127/* from Peter C. Gutmann's implementation as found in */
128/* Applied Cryptography by Bruce Schneier */
129/* Further modifications to include the "UNRAVEL" stuff, below */
130
131/* This code is in the public domain */
132
133/* UNRAVEL should be fastest & biggest */
134/* UNROLL_LOOPS should be just as big, but slightly slower */
135/* both undefined should be smallest and slowest */
136
137#define UNRAVEL
138/* #define UNROLL_LOOPS */
139
140/* The SHA f()-functions. The f1 and f3 functions can be optimized to
141 save one boolean operation each - thanks to Rich Schroeppel,
142 rcs@cs.arizona.edu for discovering this */
143
144/*#define f1(x,y,z) ((x & y) | (~x & z)) // Rounds 0-19 */
145#define f1(x,y,z) (z ^ (x & (y ^ z))) /* Rounds 0-19 */
146#define f2(x,y,z) (x ^ y ^ z) /* Rounds 20-39 */
147/*#define f3(x,y,z) ((x & y) | (x & z) | (y & z)) // Rounds 40-59 */
148#define f3(x,y,z) ((x & y) | (z & (x | y))) /* Rounds 40-59 */
149#define f4(x,y,z) (x ^ y ^ z) /* Rounds 60-79 */
150
151/* SHA constants */
152
153#define CONST1 0x5a827999L /* Rounds 0-19 */
154#define CONST2 0x6ed9eba1L /* Rounds 20-39 */
155#define CONST3 0x8f1bbcdcL /* Rounds 40-59 */
156#define CONST4 0xca62c1d6L /* Rounds 60-79 */
157
158/* 32-bit rotate */
159
160#define R32(x,n) ((x << n) | (x >> (32 - n)))
161
162/* the generic case, for when the overall rotation is not unraveled */
163
164#define FG(n) \
165 T = R32(A,5) + f##n(B,C,D) + E + *WP++ + CONST##n; \
166 E = D; D = C; C = R32(B,30); B = A; A = T
167
168/* specific cases, for when the overall rotation is unraveled */
169
170#define FA(n) \
171 T = R32(A,5) + f##n(B,C,D) + E + *WP++ + CONST##n; B = R32(B,30)
172
173#define FB(n) \
174 E = R32(T,5) + f##n(A,B,C) + D + *WP++ + CONST##n; A = R32(A,30)
175
176#define FC(n) \
177 D = R32(E,5) + f##n(T,A,B) + C + *WP++ + CONST##n; T = R32(T,30)
178
179#define FD(n) \
180 C = R32(D,5) + f##n(E,T,A) + B + *WP++ + CONST##n; E = R32(E,30)
181
182#define FE(n) \
183 B = R32(C,5) + f##n(D,E,T) + A + *WP++ + CONST##n; D = R32(D,30)
184
185#define FT(n) \
186 A = R32(B,5) + f##n(C,D,E) + T + *WP++ + CONST##n; C = R32(C,30)
187
188/* do SHA transformation */
189
190static void
191sha_transform(sha_info)
192 SHAobject *sha_info;
193{
194 int i;
195 SHA_INT32 T, A, B, C, D, E, W[80], *WP;
196
197 memcpy(W, sha_info->data, sizeof(sha_info->data));
Guido van Rossumff1ccbf1999-04-10 15:48:23 +0000198 longReverse(W, (int)sizeof(sha_info->data), sha_info->Endianness);
Guido van Rossum29d2acc1999-03-24 19:03:59 +0000199
200 for (i = 16; i < 80; ++i) {
201 W[i] = W[i-3] ^ W[i-8] ^ W[i-14] ^ W[i-16];
202
203 /* extra rotation fix */
204 W[i] = R32(W[i], 1);
205 }
206 A = sha_info->digest[0];
207 B = sha_info->digest[1];
208 C = sha_info->digest[2];
209 D = sha_info->digest[3];
210 E = sha_info->digest[4];
211 WP = W;
212#ifdef UNRAVEL
213 FA(1); FB(1); FC(1); FD(1); FE(1); FT(1); FA(1); FB(1); FC(1); FD(1);
214 FE(1); FT(1); FA(1); FB(1); FC(1); FD(1); FE(1); FT(1); FA(1); FB(1);
215 FC(2); FD(2); FE(2); FT(2); FA(2); FB(2); FC(2); FD(2); FE(2); FT(2);
216 FA(2); FB(2); FC(2); FD(2); FE(2); FT(2); FA(2); FB(2); FC(2); FD(2);
217 FE(3); FT(3); FA(3); FB(3); FC(3); FD(3); FE(3); FT(3); FA(3); FB(3);
218 FC(3); FD(3); FE(3); FT(3); FA(3); FB(3); FC(3); FD(3); FE(3); FT(3);
219 FA(4); FB(4); FC(4); FD(4); FE(4); FT(4); FA(4); FB(4); FC(4); FD(4);
220 FE(4); FT(4); FA(4); FB(4); FC(4); FD(4); FE(4); FT(4); FA(4); FB(4);
221 sha_info->digest[0] += E;
222 sha_info->digest[1] += T;
223 sha_info->digest[2] += A;
224 sha_info->digest[3] += B;
225 sha_info->digest[4] += C;
226#else /* !UNRAVEL */
227#ifdef UNROLL_LOOPS
228 FG(1); FG(1); FG(1); FG(1); FG(1); FG(1); FG(1); FG(1); FG(1); FG(1);
229 FG(1); FG(1); FG(1); FG(1); FG(1); FG(1); FG(1); FG(1); FG(1); FG(1);
230 FG(2); FG(2); FG(2); FG(2); FG(2); FG(2); FG(2); FG(2); FG(2); FG(2);
231 FG(2); FG(2); FG(2); FG(2); FG(2); FG(2); FG(2); FG(2); FG(2); FG(2);
232 FG(3); FG(3); FG(3); FG(3); FG(3); FG(3); FG(3); FG(3); FG(3); FG(3);
233 FG(3); FG(3); FG(3); FG(3); FG(3); FG(3); FG(3); FG(3); FG(3); FG(3);
234 FG(4); FG(4); FG(4); FG(4); FG(4); FG(4); FG(4); FG(4); FG(4); FG(4);
235 FG(4); FG(4); FG(4); FG(4); FG(4); FG(4); FG(4); FG(4); FG(4); FG(4);
236#else /* !UNROLL_LOOPS */
237 for (i = 0; i < 20; ++i) { FG(1); }
238 for (i = 20; i < 40; ++i) { FG(2); }
239 for (i = 40; i < 60; ++i) { FG(3); }
240 for (i = 60; i < 80; ++i) { FG(4); }
241#endif /* !UNROLL_LOOPS */
242 sha_info->digest[0] += A;
243 sha_info->digest[1] += B;
244 sha_info->digest[2] += C;
245 sha_info->digest[3] += D;
246 sha_info->digest[4] += E;
247#endif /* !UNRAVEL */
248}
249
250/* initialize the SHA digest */
251
252static void
253sha_init(sha_info)
254 SHAobject *sha_info;
255{
256 TestEndianness(sha_info->Endianness)
257
258 sha_info->digest[0] = 0x67452301L;
259 sha_info->digest[1] = 0xefcdab89L;
260 sha_info->digest[2] = 0x98badcfeL;
261 sha_info->digest[3] = 0x10325476L;
262 sha_info->digest[4] = 0xc3d2e1f0L;
263 sha_info->count_lo = 0L;
264 sha_info->count_hi = 0L;
265 sha_info->local = 0;
266}
267
268/* update the SHA digest */
269
270static void
271sha_update(sha_info, buffer, count)
272 SHAobject *sha_info;
273 SHA_BYTE *buffer;
274 int count;
275{
276 int i;
277 SHA_INT32 clo;
278
279 clo = sha_info->count_lo + ((SHA_INT32) count << 3);
280 if (clo < sha_info->count_lo) {
281 ++sha_info->count_hi;
282 }
283 sha_info->count_lo = clo;
284 sha_info->count_hi += (SHA_INT32) count >> 29;
285 if (sha_info->local) {
286 i = SHA_BLOCKSIZE - sha_info->local;
287 if (i > count) {
288 i = count;
289 }
290 memcpy(((SHA_BYTE *) sha_info->data) + sha_info->local,
291 buffer, i);
292 count -= i;
293 buffer += i;
294 sha_info->local += i;
295 if (sha_info->local == SHA_BLOCKSIZE) {
296 sha_transform(sha_info);
297 } else {
298 return;
299 }
300 }
301 while (count >= SHA_BLOCKSIZE) {
302 memcpy(sha_info->data, buffer, SHA_BLOCKSIZE);
303 buffer += SHA_BLOCKSIZE;
304 count -= SHA_BLOCKSIZE;
305 sha_transform(sha_info);
306 }
307 memcpy(sha_info->data, buffer, count);
308 sha_info->local = count;
309}
310
311/* finish computing the SHA digest */
312
313static void
314sha_final(digest, sha_info)
315 unsigned char digest[20];
316 SHAobject *sha_info;
317{
318 int count;
319 SHA_INT32 lo_bit_count, hi_bit_count;
320
321 lo_bit_count = sha_info->count_lo;
322 hi_bit_count = sha_info->count_hi;
323 count = (int) ((lo_bit_count >> 3) & 0x3f);
324 ((SHA_BYTE *) sha_info->data)[count++] = 0x80;
325 if (count > SHA_BLOCKSIZE - 8)
326 {
327 memset(((SHA_BYTE *) sha_info->data) + count, 0,
328 SHA_BLOCKSIZE - count);
329 sha_transform(sha_info);
330 memset((SHA_BYTE *) sha_info->data, 0, SHA_BLOCKSIZE - 8);
331 }
332 else
333 {
334 memset(((SHA_BYTE *) sha_info->data) + count, 0,
335 SHA_BLOCKSIZE - 8 - count);
336 }
337
338 /* GJS: note that we add the hi/lo in big-endian. sha_transform will
339 swap these values into host-order. */
340 sha_info->data[56] = (hi_bit_count >> 24) & 0xff;
341 sha_info->data[57] = (hi_bit_count >> 16) & 0xff;
342 sha_info->data[58] = (hi_bit_count >> 8) & 0xff;
343 sha_info->data[59] = (hi_bit_count >> 0) & 0xff;
344 sha_info->data[60] = (lo_bit_count >> 24) & 0xff;
345 sha_info->data[61] = (lo_bit_count >> 16) & 0xff;
346 sha_info->data[62] = (lo_bit_count >> 8) & 0xff;
347 sha_info->data[63] = (lo_bit_count >> 0) & 0xff;
348 sha_transform(sha_info);
349 digest[ 0] = (unsigned char) ((sha_info->digest[0] >> 24) & 0xff);
350 digest[ 1] = (unsigned char) ((sha_info->digest[0] >> 16) & 0xff);
351 digest[ 2] = (unsigned char) ((sha_info->digest[0] >> 8) & 0xff);
352 digest[ 3] = (unsigned char) ((sha_info->digest[0] ) & 0xff);
353 digest[ 4] = (unsigned char) ((sha_info->digest[1] >> 24) & 0xff);
354 digest[ 5] = (unsigned char) ((sha_info->digest[1] >> 16) & 0xff);
355 digest[ 6] = (unsigned char) ((sha_info->digest[1] >> 8) & 0xff);
356 digest[ 7] = (unsigned char) ((sha_info->digest[1] ) & 0xff);
357 digest[ 8] = (unsigned char) ((sha_info->digest[2] >> 24) & 0xff);
358 digest[ 9] = (unsigned char) ((sha_info->digest[2] >> 16) & 0xff);
359 digest[10] = (unsigned char) ((sha_info->digest[2] >> 8) & 0xff);
360 digest[11] = (unsigned char) ((sha_info->digest[2] ) & 0xff);
361 digest[12] = (unsigned char) ((sha_info->digest[3] >> 24) & 0xff);
362 digest[13] = (unsigned char) ((sha_info->digest[3] >> 16) & 0xff);
363 digest[14] = (unsigned char) ((sha_info->digest[3] >> 8) & 0xff);
364 digest[15] = (unsigned char) ((sha_info->digest[3] ) & 0xff);
365 digest[16] = (unsigned char) ((sha_info->digest[4] >> 24) & 0xff);
366 digest[17] = (unsigned char) ((sha_info->digest[4] >> 16) & 0xff);
367 digest[18] = (unsigned char) ((sha_info->digest[4] >> 8) & 0xff);
368 digest[19] = (unsigned char) ((sha_info->digest[4] ) & 0xff);
369}
370
371/*
372 * End of copied SHA code.
373 *
374 * ------------------------------------------------------------------------
375 */
376
377staticforward PyTypeObject SHAtype;
378
379
380static SHAobject *
381newSHAobject()
382{
383 return (SHAobject *)PyObject_NEW(SHAobject, &SHAtype);
384}
385
386/* Internal methods for a hashing object */
387
388static void
389SHA_dealloc(ptr)
390 PyObject *ptr;
391{
392 PyMem_DEL(ptr);
393}
394
395
396/* External methods for a hashing object */
397
398static char SHA_copy__doc__[] =
399"Return a copy of the hashing object.";
400
401static PyObject *
402SHA_copy(self, args)
403 SHAobject *self;
404 PyObject *args;
405{
406 SHAobject *newobj;
407
408 if (!PyArg_NoArgs(args)) {
409 return NULL;
410 }
411
412 if ( (newobj = newSHAobject())==NULL)
413 return NULL;
414
415 SHAcopy(self, newobj);
416 return (PyObject *)newobj;
417}
418
419static char SHA_digest__doc__[] =
420"Return the digest value as a string of binary data.";
421
422static PyObject *
423SHA_digest(self, args)
424 SHAobject *self;
425 PyObject *args;
426{
427 unsigned char digest[SHA_DIGESTSIZE];
428 SHAobject temp;
429
430 if (!PyArg_NoArgs(args))
431 return NULL;
432
433 SHAcopy(self, &temp);
434 sha_final(digest, &temp);
Guido van Rossumcf95b0f1999-03-29 14:57:59 +0000435 return PyString_FromStringAndSize((const char *)digest, sizeof(digest));
Guido van Rossum29d2acc1999-03-24 19:03:59 +0000436}
437
438static char SHA_hexdigest__doc__[] =
439"Return the digest value as a string of hexadecimal digits.";
440
441static PyObject *
442SHA_hexdigest(self, args)
443 SHAobject *self;
444 PyObject *args;
445{
446 unsigned char digest[SHA_DIGESTSIZE];
447 SHAobject temp;
448 PyObject *retval;
449 char *hex_digest;
450 int i, j;
451
452 if (!PyArg_NoArgs(args))
453 return NULL;
454
455 /* Get the raw (binary) digest value */
456 SHAcopy(self, &temp);
457 sha_final(digest, &temp);
458
459 /* Create a new string */
460 retval = PyString_FromStringAndSize(NULL, sizeof(digest) * 2);
461 hex_digest = PyString_AsString(retval);
462
463 /* Make hex version of the digest */
464 for(i=j=0; i<sizeof(digest); i++)
465 {
466 char c;
467 c = digest[i] / 16; c = (c>9) ? c+'a'-10 : c + '0';
468 hex_digest[j++] = c;
469 c = digest[i] % 16; c = (c>9) ? c+'a'-10 : c + '0';
470 hex_digest[j++] = c;
471 }
472
473 return retval;
474}
475
476static char SHA_update__doc__[] =
477"Update this hashing object's state with the provided string.";
478
479static PyObject *
480SHA_update(self, args)
481 SHAobject *self;
482 PyObject *args;
483{
484 unsigned char *cp;
485 int len;
486
487 if (!PyArg_Parse(args, "s#", &cp, &len))
488 return NULL;
489
490 sha_update(self, cp, len);
491
492 Py_INCREF(Py_None);
493 return Py_None;
494}
495
496static PyMethodDef SHA_methods[] = {
497 {"copy", (PyCFunction)SHA_copy, 0, SHA_copy__doc__},
498 {"digest", (PyCFunction)SHA_digest, 0, SHA_digest__doc__},
499 {"hexdigest", (PyCFunction)SHA_hexdigest, 0, SHA_hexdigest__doc__},
500 {"update", (PyCFunction)SHA_update, 0, SHA_update__doc__},
501 {NULL, NULL} /* sentinel */
502};
503
504static PyObject *
505SHA_getattr(self, name)
Guido van Rossumcf95b0f1999-03-29 14:57:59 +0000506 PyObject *self;
Guido van Rossum29d2acc1999-03-24 19:03:59 +0000507 char *name;
508{
509 if (strcmp(name, "blocksize")==0)
510 return PyInt_FromLong(1);
511 if (strcmp(name, "digestsize")==0)
512 return PyInt_FromLong(20);
513
Guido van Rossumcf95b0f1999-03-29 14:57:59 +0000514 return Py_FindMethod(SHA_methods, self, name);
Guido van Rossum29d2acc1999-03-24 19:03:59 +0000515}
516
517static PyTypeObject SHAtype = {
518 PyObject_HEAD_INIT(NULL)
519 0, /*ob_size*/
520 "SHA", /*tp_name*/
521 sizeof(SHAobject), /*tp_size*/
522 0, /*tp_itemsize*/
523 /* methods */
524 SHA_dealloc, /*tp_dealloc*/
525 0, /*tp_print*/
526 SHA_getattr, /*tp_getattr*/
527};
528
529
530/* The single module-level function: new() */
531
532static char SHA_new__doc__[] =
533 "Return a new SHA hashing object. An optional string "
534 "argument may be provided; if present, this string will be "
535 " automatically hashed.";
536
537static PyObject *
538SHA_new(self, args, kwdict)
539 PyObject *self;
540 PyObject *args;
541 PyObject *kwdict;
542{
543 static char *kwlist[] = {"string", NULL};
544 SHAobject *new;
545 unsigned char *cp = NULL;
546 int len;
547
548 if ((new = newSHAobject()) == NULL)
549 return NULL;
550
Guido van Rossum43713e52000-02-29 13:59:29 +0000551 if (!PyArg_ParseTupleAndKeywords(args, kwdict, "|s#:new", kwlist,
Guido van Rossum29d2acc1999-03-24 19:03:59 +0000552 &cp, &len)) {
553 Py_DECREF(new);
554 return NULL;
555 }
556
557 sha_init(new);
558
559 if (PyErr_Occurred()) {
560 Py_DECREF(new);
561 return NULL;
562 }
563 if (cp)
564 sha_update(new, cp, len);
565
566 return (PyObject *)new;
567}
568
569
570/* List of functions exported by this module */
571
572static struct PyMethodDef SHA_functions[] = {
573 {"new", (PyCFunction)SHA_new, METH_VARARGS|METH_KEYWORDS, SHA_new__doc__},
574 {"sha", (PyCFunction)SHA_new, METH_VARARGS|METH_KEYWORDS, SHA_new__doc__},
575 {NULL, NULL} /* Sentinel */
576};
577
578
579/* Initialize this module. */
580
581#define insint(n,v) { PyObject *o=PyInt_FromLong(v); \
582 if (o!=NULL) PyDict_SetItemString(d,n,o); \
583 Py_XDECREF(o); }
584
585void
586initsha()
587{
588 PyObject *d, *m;
589
590 SHAtype.ob_type = &PyType_Type;
591 m = Py_InitModule("sha", SHA_functions);
592
593 /* Add some symbolic constants to the module */
594 d = PyModule_GetDict(m);
595 insint("blocksize", 1); /* For future use, in case some hash
596 functions require an integral number of
597 blocks */
598 insint("digestsize", 20);
599
600 /* Check for errors */
601 if (PyErr_Occurred())
602 Py_FatalError("can't initialize module SHA");
603}
604