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