Blocked revisions 79401 via svnmerge
[python/dscho.git] / Modules / md5module.c
blob6476bb73562f393a99694e3811c26b159e4da8d1
1 /* MD5 module */
3 /* This module provides an interface to the MD5 algorithm */
5 /* See below for information about the original code this module was
6 based upon. Additional work performed by:
8 Andrew Kuchling (amk@amk.ca)
9 Greg Stein (gstein@lyra.org)
10 Trevor Perrin (trevp@trevp.net)
12 Copyright (C) 2005-2007 Gregory P. Smith (greg@krypto.org)
13 Licensed to PSF under a Contributor Agreement.
17 /* MD5 objects */
19 #include "Python.h"
20 #include "hashlib.h"
23 /* Some useful types */
25 #if SIZEOF_INT == 4
26 typedef unsigned int MD5_INT32; /* 32-bit integer */
27 typedef PY_LONG_LONG MD5_INT64; /* 64-bit integer */
28 #else
29 /* not defined. compilation will die. */
30 #endif
32 /* The MD5 block size and message digest sizes, in bytes */
34 #define MD5_BLOCKSIZE 64
35 #define MD5_DIGESTSIZE 16
37 /* The structure for storing MD5 info */
39 struct md5_state {
40 MD5_INT64 length;
41 MD5_INT32 state[4], curlen;
42 unsigned char buf[MD5_BLOCKSIZE];
45 typedef struct {
46 PyObject_HEAD
48 struct md5_state hash_state;
49 } MD5object;
52 /* ------------------------------------------------------------------------
54 * This code for the MD5 algorithm was noted as public domain. The
55 * original headers are pasted below.
57 * Several changes have been made to make it more compatible with the
58 * Python environment and desired interface.
62 /* LibTomCrypt, modular cryptographic library -- Tom St Denis
64 * LibTomCrypt is a library that provides various cryptographic
65 * algorithms in a highly modular and flexible manner.
67 * The library is free for all purposes without any express
68 * guarantee it works.
70 * Tom St Denis, tomstdenis@gmail.com, http://libtom.org
73 /* rotate the hard way (platform optimizations could be done) */
74 #define ROLc(x, y) ( (((unsigned long)(x)<<(unsigned long)((y)&31)) | (((unsigned long)(x)&0xFFFFFFFFUL)>>(unsigned long)(32-((y)&31)))) & 0xFFFFFFFFUL)
76 /* Endian Neutral macros that work on all platforms */
78 #define STORE32L(x, y) \
79 { (y)[3] = (unsigned char)(((x)>>24)&255); (y)[2] = (unsigned char)(((x)>>16)&255); \
80 (y)[1] = (unsigned char)(((x)>>8)&255); (y)[0] = (unsigned char)((x)&255); }
82 #define LOAD32L(x, y) \
83 { x = ((unsigned long)((y)[3] & 255)<<24) | \
84 ((unsigned long)((y)[2] & 255)<<16) | \
85 ((unsigned long)((y)[1] & 255)<<8) | \
86 ((unsigned long)((y)[0] & 255)); }
88 #define STORE64L(x, y) \
89 { (y)[7] = (unsigned char)(((x)>>56)&255); (y)[6] = (unsigned char)(((x)>>48)&255); \
90 (y)[5] = (unsigned char)(((x)>>40)&255); (y)[4] = (unsigned char)(((x)>>32)&255); \
91 (y)[3] = (unsigned char)(((x)>>24)&255); (y)[2] = (unsigned char)(((x)>>16)&255); \
92 (y)[1] = (unsigned char)(((x)>>8)&255); (y)[0] = (unsigned char)((x)&255); }
94 #ifndef MIN
95 #define MIN(x, y) ( ((x)<(y))?(x):(y) )
96 #endif
99 /* MD5 macros */
101 #define F(x,y,z) (z ^ (x & (y ^ z)))
102 #define G(x,y,z) (y ^ (z & (y ^ x)))
103 #define H(x,y,z) (x^y^z)
104 #define I(x,y,z) (y^(x|(~z)))
106 #define FF(a,b,c,d,M,s,t) \
107 a = (a + F(b,c,d) + M + t); a = ROLc(a, s) + b;
109 #define GG(a,b,c,d,M,s,t) \
110 a = (a + G(b,c,d) + M + t); a = ROLc(a, s) + b;
112 #define HH(a,b,c,d,M,s,t) \
113 a = (a + H(b,c,d) + M + t); a = ROLc(a, s) + b;
115 #define II(a,b,c,d,M,s,t) \
116 a = (a + I(b,c,d) + M + t); a = ROLc(a, s) + b;
119 static void md5_compress(struct md5_state *md5, unsigned char *buf)
121 MD5_INT32 i, W[16], a, b, c, d;
123 assert(md5 != NULL);
124 assert(buf != NULL);
126 /* copy the state into 512-bits into W[0..15] */
127 for (i = 0; i < 16; i++) {
128 LOAD32L(W[i], buf + (4*i));
131 /* copy state */
132 a = md5->state[0];
133 b = md5->state[1];
134 c = md5->state[2];
135 d = md5->state[3];
137 FF(a,b,c,d,W[0],7,0xd76aa478UL)
138 FF(d,a,b,c,W[1],12,0xe8c7b756UL)
139 FF(c,d,a,b,W[2],17,0x242070dbUL)
140 FF(b,c,d,a,W[3],22,0xc1bdceeeUL)
141 FF(a,b,c,d,W[4],7,0xf57c0fafUL)
142 FF(d,a,b,c,W[5],12,0x4787c62aUL)
143 FF(c,d,a,b,W[6],17,0xa8304613UL)
144 FF(b,c,d,a,W[7],22,0xfd469501UL)
145 FF(a,b,c,d,W[8],7,0x698098d8UL)
146 FF(d,a,b,c,W[9],12,0x8b44f7afUL)
147 FF(c,d,a,b,W[10],17,0xffff5bb1UL)
148 FF(b,c,d,a,W[11],22,0x895cd7beUL)
149 FF(a,b,c,d,W[12],7,0x6b901122UL)
150 FF(d,a,b,c,W[13],12,0xfd987193UL)
151 FF(c,d,a,b,W[14],17,0xa679438eUL)
152 FF(b,c,d,a,W[15],22,0x49b40821UL)
153 GG(a,b,c,d,W[1],5,0xf61e2562UL)
154 GG(d,a,b,c,W[6],9,0xc040b340UL)
155 GG(c,d,a,b,W[11],14,0x265e5a51UL)
156 GG(b,c,d,a,W[0],20,0xe9b6c7aaUL)
157 GG(a,b,c,d,W[5],5,0xd62f105dUL)
158 GG(d,a,b,c,W[10],9,0x02441453UL)
159 GG(c,d,a,b,W[15],14,0xd8a1e681UL)
160 GG(b,c,d,a,W[4],20,0xe7d3fbc8UL)
161 GG(a,b,c,d,W[9],5,0x21e1cde6UL)
162 GG(d,a,b,c,W[14],9,0xc33707d6UL)
163 GG(c,d,a,b,W[3],14,0xf4d50d87UL)
164 GG(b,c,d,a,W[8],20,0x455a14edUL)
165 GG(a,b,c,d,W[13],5,0xa9e3e905UL)
166 GG(d,a,b,c,W[2],9,0xfcefa3f8UL)
167 GG(c,d,a,b,W[7],14,0x676f02d9UL)
168 GG(b,c,d,a,W[12],20,0x8d2a4c8aUL)
169 HH(a,b,c,d,W[5],4,0xfffa3942UL)
170 HH(d,a,b,c,W[8],11,0x8771f681UL)
171 HH(c,d,a,b,W[11],16,0x6d9d6122UL)
172 HH(b,c,d,a,W[14],23,0xfde5380cUL)
173 HH(a,b,c,d,W[1],4,0xa4beea44UL)
174 HH(d,a,b,c,W[4],11,0x4bdecfa9UL)
175 HH(c,d,a,b,W[7],16,0xf6bb4b60UL)
176 HH(b,c,d,a,W[10],23,0xbebfbc70UL)
177 HH(a,b,c,d,W[13],4,0x289b7ec6UL)
178 HH(d,a,b,c,W[0],11,0xeaa127faUL)
179 HH(c,d,a,b,W[3],16,0xd4ef3085UL)
180 HH(b,c,d,a,W[6],23,0x04881d05UL)
181 HH(a,b,c,d,W[9],4,0xd9d4d039UL)
182 HH(d,a,b,c,W[12],11,0xe6db99e5UL)
183 HH(c,d,a,b,W[15],16,0x1fa27cf8UL)
184 HH(b,c,d,a,W[2],23,0xc4ac5665UL)
185 II(a,b,c,d,W[0],6,0xf4292244UL)
186 II(d,a,b,c,W[7],10,0x432aff97UL)
187 II(c,d,a,b,W[14],15,0xab9423a7UL)
188 II(b,c,d,a,W[5],21,0xfc93a039UL)
189 II(a,b,c,d,W[12],6,0x655b59c3UL)
190 II(d,a,b,c,W[3],10,0x8f0ccc92UL)
191 II(c,d,a,b,W[10],15,0xffeff47dUL)
192 II(b,c,d,a,W[1],21,0x85845dd1UL)
193 II(a,b,c,d,W[8],6,0x6fa87e4fUL)
194 II(d,a,b,c,W[15],10,0xfe2ce6e0UL)
195 II(c,d,a,b,W[6],15,0xa3014314UL)
196 II(b,c,d,a,W[13],21,0x4e0811a1UL)
197 II(a,b,c,d,W[4],6,0xf7537e82UL)
198 II(d,a,b,c,W[11],10,0xbd3af235UL)
199 II(c,d,a,b,W[2],15,0x2ad7d2bbUL)
200 II(b,c,d,a,W[9],21,0xeb86d391UL)
202 md5->state[0] = md5->state[0] + a;
203 md5->state[1] = md5->state[1] + b;
204 md5->state[2] = md5->state[2] + c;
205 md5->state[3] = md5->state[3] + d;
210 Initialize the hash state
211 @param sha1 The hash state you wish to initialize
213 void md5_init(struct md5_state *md5)
215 assert(md5 != NULL);
216 md5->state[0] = 0x67452301UL;
217 md5->state[1] = 0xefcdab89UL;
218 md5->state[2] = 0x98badcfeUL;
219 md5->state[3] = 0x10325476UL;
220 md5->curlen = 0;
221 md5->length = 0;
225 Process a block of memory though the hash
226 @param sha1 The hash state
227 @param in The data to hash
228 @param inlen The length of the data (octets)
230 void md5_process(struct md5_state *md5,
231 const unsigned char *in, unsigned long inlen)
233 unsigned long n;
235 assert(md5 != NULL);
236 assert(in != NULL);
237 assert(md5->curlen <= sizeof(md5->buf));
239 while (inlen > 0) {
240 if (md5->curlen == 0 && inlen >= MD5_BLOCKSIZE) {
241 md5_compress(md5, (unsigned char *)in);
242 md5->length += MD5_BLOCKSIZE * 8;
243 in += MD5_BLOCKSIZE;
244 inlen -= MD5_BLOCKSIZE;
245 } else {
246 n = MIN(inlen, (MD5_BLOCKSIZE - md5->curlen));
247 memcpy(md5->buf + md5->curlen, in, (size_t)n);
248 md5->curlen += n;
249 in += n;
250 inlen -= n;
251 if (md5->curlen == MD5_BLOCKSIZE) {
252 md5_compress(md5, md5->buf);
253 md5->length += 8*MD5_BLOCKSIZE;
254 md5->curlen = 0;
261 Terminate the hash to get the digest
262 @param sha1 The hash state
263 @param out [out] The destination of the hash (16 bytes)
265 void md5_done(struct md5_state *md5, unsigned char *out)
267 int i;
269 assert(md5 != NULL);
270 assert(out != NULL);
271 assert(md5->curlen < sizeof(md5->buf));
273 /* increase the length of the message */
274 md5->length += md5->curlen * 8;
276 /* append the '1' bit */
277 md5->buf[md5->curlen++] = (unsigned char)0x80;
279 /* if the length is currently above 56 bytes we append zeros
280 * then compress. Then we can fall back to padding zeros and length
281 * encoding like normal.
283 if (md5->curlen > 56) {
284 while (md5->curlen < 64) {
285 md5->buf[md5->curlen++] = (unsigned char)0;
287 md5_compress(md5, md5->buf);
288 md5->curlen = 0;
291 /* pad upto 56 bytes of zeroes */
292 while (md5->curlen < 56) {
293 md5->buf[md5->curlen++] = (unsigned char)0;
296 /* store length */
297 STORE64L(md5->length, md5->buf+56);
298 md5_compress(md5, md5->buf);
300 /* copy output */
301 for (i = 0; i < 4; i++) {
302 STORE32L(md5->state[i], out+(4*i));
306 /* .Source: /cvs/libtom/libtomcrypt/src/hashes/md5.c,v $ */
307 /* .Revision: 1.10 $ */
308 /* .Date: 2007/05/12 14:25:28 $ */
311 * End of copied MD5 code.
313 * ------------------------------------------------------------------------
316 static PyTypeObject MD5type;
319 static MD5object *
320 newMD5object(void)
322 return (MD5object *)PyObject_New(MD5object, &MD5type);
326 /* Internal methods for a hash object */
328 static void
329 MD5_dealloc(PyObject *ptr)
331 PyObject_Del(ptr);
335 /* External methods for a hash object */
337 PyDoc_STRVAR(MD5_copy__doc__, "Return a copy of the hash object.");
339 static PyObject *
340 MD5_copy(MD5object *self, PyObject *unused)
342 MD5object *newobj;
344 if (Py_TYPE(self) == &MD5type) {
345 if ( (newobj = newMD5object())==NULL)
346 return NULL;
347 } else {
348 if ( (newobj = newMD5object())==NULL)
349 return NULL;
352 newobj->hash_state = self->hash_state;
353 return (PyObject *)newobj;
356 PyDoc_STRVAR(MD5_digest__doc__,
357 "Return the digest value as a string of binary data.");
359 static PyObject *
360 MD5_digest(MD5object *self, PyObject *unused)
362 unsigned char digest[MD5_DIGESTSIZE];
363 struct md5_state temp;
365 temp = self->hash_state;
366 md5_done(&temp, digest);
367 return PyBytes_FromStringAndSize((const char *)digest, MD5_DIGESTSIZE);
370 PyDoc_STRVAR(MD5_hexdigest__doc__,
371 "Return the digest value as a string of hexadecimal digits.");
373 static PyObject *
374 MD5_hexdigest(MD5object *self, PyObject *unused)
376 unsigned char digest[MD5_DIGESTSIZE];
377 struct md5_state temp;
378 PyObject *retval;
379 Py_UNICODE *hex_digest;
380 int i, j;
382 /* Get the raw (binary) digest value */
383 temp = self->hash_state;
384 md5_done(&temp, digest);
386 /* Create a new string */
387 retval = PyUnicode_FromStringAndSize(NULL, MD5_DIGESTSIZE * 2);
388 if (!retval)
389 return NULL;
390 hex_digest = PyUnicode_AS_UNICODE(retval);
391 if (!hex_digest) {
392 Py_DECREF(retval);
393 return NULL;
396 /* Make hex version of the digest */
397 for(i=j=0; i<MD5_DIGESTSIZE; i++) {
398 char c;
399 c = (digest[i] >> 4) & 0xf;
400 c = (c>9) ? c+'a'-10 : c + '0';
401 hex_digest[j++] = c;
402 c = (digest[i] & 0xf);
403 c = (c>9) ? c+'a'-10 : c + '0';
404 hex_digest[j++] = c;
406 return retval;
409 PyDoc_STRVAR(MD5_update__doc__,
410 "Update this hash object's state with the provided string.");
412 static PyObject *
413 MD5_update(MD5object *self, PyObject *args)
415 PyObject *obj;
416 Py_buffer buf;
418 if (!PyArg_ParseTuple(args, "O:update", &obj))
419 return NULL;
421 GET_BUFFER_VIEW_OR_ERROUT(obj, &buf);
423 md5_process(&self->hash_state, buf.buf, buf.len);
425 PyBuffer_Release(&buf);
426 Py_INCREF(Py_None);
427 return Py_None;
430 static PyMethodDef MD5_methods[] = {
431 {"copy", (PyCFunction)MD5_copy, METH_NOARGS, MD5_copy__doc__},
432 {"digest", (PyCFunction)MD5_digest, METH_NOARGS, MD5_digest__doc__},
433 {"hexdigest", (PyCFunction)MD5_hexdigest, METH_NOARGS, MD5_hexdigest__doc__},
434 {"update", (PyCFunction)MD5_update, METH_VARARGS, MD5_update__doc__},
435 {NULL, NULL} /* sentinel */
438 static PyObject *
439 MD5_get_block_size(PyObject *self, void *closure)
441 return PyLong_FromLong(MD5_BLOCKSIZE);
444 static PyObject *
445 MD5_get_name(PyObject *self, void *closure)
447 return PyUnicode_FromStringAndSize("MD5", 3);
450 static PyObject *
451 md5_get_digest_size(PyObject *self, void *closure)
453 return PyLong_FromLong(MD5_DIGESTSIZE);
457 static PyGetSetDef MD5_getseters[] = {
458 {"block_size",
459 (getter)MD5_get_block_size, NULL,
460 NULL,
461 NULL},
462 {"name",
463 (getter)MD5_get_name, NULL,
464 NULL,
465 NULL},
466 {"digest_size",
467 (getter)md5_get_digest_size, NULL,
468 NULL,
469 NULL},
470 {NULL} /* Sentinel */
473 static PyTypeObject MD5type = {
474 PyVarObject_HEAD_INIT(NULL, 0)
475 "_md5.md5", /*tp_name*/
476 sizeof(MD5object), /*tp_size*/
477 0, /*tp_itemsize*/
478 /* methods */
479 MD5_dealloc, /*tp_dealloc*/
480 0, /*tp_print*/
481 0, /*tp_getattr*/
482 0, /*tp_setattr*/
483 0, /*tp_reserved*/
484 0, /*tp_repr*/
485 0, /*tp_as_number*/
486 0, /*tp_as_sequence*/
487 0, /*tp_as_mapping*/
488 0, /*tp_hash*/
489 0, /*tp_call*/
490 0, /*tp_str*/
491 0, /*tp_getattro*/
492 0, /*tp_setattro*/
493 0, /*tp_as_buffer*/
494 Py_TPFLAGS_DEFAULT, /*tp_flags*/
495 0, /*tp_doc*/
496 0, /*tp_traverse*/
497 0, /*tp_clear*/
498 0, /*tp_richcompare*/
499 0, /*tp_weaklistoffset*/
500 0, /*tp_iter*/
501 0, /*tp_iternext*/
502 MD5_methods, /* tp_methods */
503 NULL, /* tp_members */
504 MD5_getseters, /* tp_getset */
508 /* The single module-level function: new() */
510 PyDoc_STRVAR(MD5_new__doc__,
511 "Return a new MD5 hash object; optionally initialized with a string.");
513 static PyObject *
514 MD5_new(PyObject *self, PyObject *args, PyObject *kwdict)
516 static char *kwlist[] = {"string", NULL};
517 MD5object *new;
518 PyObject *data_obj = NULL;
519 Py_buffer buf;
521 if (!PyArg_ParseTupleAndKeywords(args, kwdict, "|O:new", kwlist,
522 &data_obj)) {
523 return NULL;
526 if (data_obj)
527 GET_BUFFER_VIEW_OR_ERROUT(data_obj, &buf);
529 if ((new = newMD5object()) == NULL) {
530 if (data_obj)
531 PyBuffer_Release(&buf);
532 return NULL;
535 md5_init(&new->hash_state);
537 if (PyErr_Occurred()) {
538 Py_DECREF(new);
539 if (data_obj)
540 PyBuffer_Release(&buf);
541 return NULL;
543 if (data_obj) {
544 md5_process(&new->hash_state, buf.buf, buf.len);
545 PyBuffer_Release(&buf);
548 return (PyObject *)new;
552 /* List of functions exported by this module */
554 static struct PyMethodDef MD5_functions[] = {
555 {"md5", (PyCFunction)MD5_new, METH_VARARGS|METH_KEYWORDS, MD5_new__doc__},
556 {NULL, NULL} /* Sentinel */
560 /* Initialize this module. */
562 #define insint(n,v) { PyModule_AddIntConstant(m,n,v); }
565 static struct PyModuleDef _md5module = {
566 PyModuleDef_HEAD_INIT,
567 "_md5",
568 NULL,
570 MD5_functions,
571 NULL,
572 NULL,
573 NULL,
574 NULL
577 PyMODINIT_FUNC
578 PyInit__md5(void)
580 Py_TYPE(&MD5type) = &PyType_Type;
581 if (PyType_Ready(&MD5type) < 0)
582 return NULL;
583 return PyModule_Create(&_md5module);