You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

584 lines
15 KiB

  1. /* MD5 module */
  2. /* This module provides an interface to the MD5 algorithm */
  3. /* See below for information about the original code this module was
  4. based upon. Additional work performed by:
  5. Andrew Kuchling (amk@amk.ca)
  6. Greg Stein (gstein@lyra.org)
  7. Trevor Perrin (trevp@trevp.net)
  8. Copyright (C) 2005-2007 Gregory P. Smith (greg@krypto.org)
  9. Licensed to PSF under a Contributor Agreement.
  10. */
  11. /* MD5 objects */
  12. #include "Python.h"
  13. #include "hashlib.h"
  14. /* Some useful types */
  15. #if SIZEOF_INT == 4
  16. typedef unsigned int MD5_INT32; /* 32-bit integer */
  17. typedef PY_LONG_LONG MD5_INT64; /* 64-bit integer */
  18. #else
  19. /* not defined. compilation will die. */
  20. #endif
  21. /* The MD5 block size and message digest sizes, in bytes */
  22. #define MD5_BLOCKSIZE 64
  23. #define MD5_DIGESTSIZE 16
  24. /* The structure for storing MD5 info */
  25. struct md5_state {
  26. MD5_INT64 length;
  27. MD5_INT32 state[4], curlen;
  28. unsigned char buf[MD5_BLOCKSIZE];
  29. };
  30. typedef struct {
  31. PyObject_HEAD
  32. struct md5_state hash_state;
  33. } MD5object;
  34. /* ------------------------------------------------------------------------
  35. *
  36. * This code for the MD5 algorithm was noted as public domain. The
  37. * original headers are pasted below.
  38. *
  39. * Several changes have been made to make it more compatible with the
  40. * Python environment and desired interface.
  41. *
  42. */
  43. /* LibTomCrypt, modular cryptographic library -- Tom St Denis
  44. *
  45. * LibTomCrypt is a library that provides various cryptographic
  46. * algorithms in a highly modular and flexible manner.
  47. *
  48. * The library is free for all purposes without any express
  49. * guarantee it works.
  50. *
  51. * Tom St Denis, tomstdenis@gmail.com, http://libtom.org
  52. */
  53. /* rotate the hard way (platform optimizations could be done) */
  54. #define ROLc(x, y) ( (((unsigned long)(x)<<(unsigned long)((y)&31)) | (((unsigned long)(x)&0xFFFFFFFFUL)>>(unsigned long)(32-((y)&31)))) & 0xFFFFFFFFUL)
  55. /* Endian Neutral macros that work on all platforms */
  56. #define STORE32L(x, y) \
  57. { (y)[3] = (unsigned char)(((x)>>24)&255); (y)[2] = (unsigned char)(((x)>>16)&255); \
  58. (y)[1] = (unsigned char)(((x)>>8)&255); (y)[0] = (unsigned char)((x)&255); }
  59. #define LOAD32L(x, y) \
  60. { x = ((unsigned long)((y)[3] & 255)<<24) | \
  61. ((unsigned long)((y)[2] & 255)<<16) | \
  62. ((unsigned long)((y)[1] & 255)<<8) | \
  63. ((unsigned long)((y)[0] & 255)); }
  64. #define STORE64L(x, y) \
  65. { (y)[7] = (unsigned char)(((x)>>56)&255); (y)[6] = (unsigned char)(((x)>>48)&255); \
  66. (y)[5] = (unsigned char)(((x)>>40)&255); (y)[4] = (unsigned char)(((x)>>32)&255); \
  67. (y)[3] = (unsigned char)(((x)>>24)&255); (y)[2] = (unsigned char)(((x)>>16)&255); \
  68. (y)[1] = (unsigned char)(((x)>>8)&255); (y)[0] = (unsigned char)((x)&255); }
  69. #ifndef MIN
  70. #define MIN(x, y) ( ((x)<(y))?(x):(y) )
  71. #endif
  72. /* MD5 macros */
  73. #define F(x,y,z) (z ^ (x & (y ^ z)))
  74. #define G(x,y,z) (y ^ (z & (y ^ x)))
  75. #define H(x,y,z) (x^y^z)
  76. #define I(x,y,z) (y^(x|(~z)))
  77. #define FF(a,b,c,d,M,s,t) \
  78. a = (a + F(b,c,d) + M + t); a = ROLc(a, s) + b;
  79. #define GG(a,b,c,d,M,s,t) \
  80. a = (a + G(b,c,d) + M + t); a = ROLc(a, s) + b;
  81. #define HH(a,b,c,d,M,s,t) \
  82. a = (a + H(b,c,d) + M + t); a = ROLc(a, s) + b;
  83. #define II(a,b,c,d,M,s,t) \
  84. a = (a + I(b,c,d) + M + t); a = ROLc(a, s) + b;
  85. static void md5_compress(struct md5_state *md5, unsigned char *buf)
  86. {
  87. MD5_INT32 i, W[16], a, b, c, d;
  88. assert(md5 != NULL);
  89. assert(buf != NULL);
  90. /* copy the state into 512-bits into W[0..15] */
  91. for (i = 0; i < 16; i++) {
  92. LOAD32L(W[i], buf + (4*i));
  93. }
  94. /* copy state */
  95. a = md5->state[0];
  96. b = md5->state[1];
  97. c = md5->state[2];
  98. d = md5->state[3];
  99. FF(a,b,c,d,W[0],7,0xd76aa478UL)
  100. FF(d,a,b,c,W[1],12,0xe8c7b756UL)
  101. FF(c,d,a,b,W[2],17,0x242070dbUL)
  102. FF(b,c,d,a,W[3],22,0xc1bdceeeUL)
  103. FF(a,b,c,d,W[4],7,0xf57c0fafUL)
  104. FF(d,a,b,c,W[5],12,0x4787c62aUL)
  105. FF(c,d,a,b,W[6],17,0xa8304613UL)
  106. FF(b,c,d,a,W[7],22,0xfd469501UL)
  107. FF(a,b,c,d,W[8],7,0x698098d8UL)
  108. FF(d,a,b,c,W[9],12,0x8b44f7afUL)
  109. FF(c,d,a,b,W[10],17,0xffff5bb1UL)
  110. FF(b,c,d,a,W[11],22,0x895cd7beUL)
  111. FF(a,b,c,d,W[12],7,0x6b901122UL)
  112. FF(d,a,b,c,W[13],12,0xfd987193UL)
  113. FF(c,d,a,b,W[14],17,0xa679438eUL)
  114. FF(b,c,d,a,W[15],22,0x49b40821UL)
  115. GG(a,b,c,d,W[1],5,0xf61e2562UL)
  116. GG(d,a,b,c,W[6],9,0xc040b340UL)
  117. GG(c,d,a,b,W[11],14,0x265e5a51UL)
  118. GG(b,c,d,a,W[0],20,0xe9b6c7aaUL)
  119. GG(a,b,c,d,W[5],5,0xd62f105dUL)
  120. GG(d,a,b,c,W[10],9,0x02441453UL)
  121. GG(c,d,a,b,W[15],14,0xd8a1e681UL)
  122. GG(b,c,d,a,W[4],20,0xe7d3fbc8UL)
  123. GG(a,b,c,d,W[9],5,0x21e1cde6UL)
  124. GG(d,a,b,c,W[14],9,0xc33707d6UL)
  125. GG(c,d,a,b,W[3],14,0xf4d50d87UL)
  126. GG(b,c,d,a,W[8],20,0x455a14edUL)
  127. GG(a,b,c,d,W[13],5,0xa9e3e905UL)
  128. GG(d,a,b,c,W[2],9,0xfcefa3f8UL)
  129. GG(c,d,a,b,W[7],14,0x676f02d9UL)
  130. GG(b,c,d,a,W[12],20,0x8d2a4c8aUL)
  131. HH(a,b,c,d,W[5],4,0xfffa3942UL)
  132. HH(d,a,b,c,W[8],11,0x8771f681UL)
  133. HH(c,d,a,b,W[11],16,0x6d9d6122UL)
  134. HH(b,c,d,a,W[14],23,0xfde5380cUL)
  135. HH(a,b,c,d,W[1],4,0xa4beea44UL)
  136. HH(d,a,b,c,W[4],11,0x4bdecfa9UL)
  137. HH(c,d,a,b,W[7],16,0xf6bb4b60UL)
  138. HH(b,c,d,a,W[10],23,0xbebfbc70UL)
  139. HH(a,b,c,d,W[13],4,0x289b7ec6UL)
  140. HH(d,a,b,c,W[0],11,0xeaa127faUL)
  141. HH(c,d,a,b,W[3],16,0xd4ef3085UL)
  142. HH(b,c,d,a,W[6],23,0x04881d05UL)
  143. HH(a,b,c,d,W[9],4,0xd9d4d039UL)
  144. HH(d,a,b,c,W[12],11,0xe6db99e5UL)
  145. HH(c,d,a,b,W[15],16,0x1fa27cf8UL)
  146. HH(b,c,d,a,W[2],23,0xc4ac5665UL)
  147. II(a,b,c,d,W[0],6,0xf4292244UL)
  148. II(d,a,b,c,W[7],10,0x432aff97UL)
  149. II(c,d,a,b,W[14],15,0xab9423a7UL)
  150. II(b,c,d,a,W[5],21,0xfc93a039UL)
  151. II(a,b,c,d,W[12],6,0x655b59c3UL)
  152. II(d,a,b,c,W[3],10,0x8f0ccc92UL)
  153. II(c,d,a,b,W[10],15,0xffeff47dUL)
  154. II(b,c,d,a,W[1],21,0x85845dd1UL)
  155. II(a,b,c,d,W[8],6,0x6fa87e4fUL)
  156. II(d,a,b,c,W[15],10,0xfe2ce6e0UL)
  157. II(c,d,a,b,W[6],15,0xa3014314UL)
  158. II(b,c,d,a,W[13],21,0x4e0811a1UL)
  159. II(a,b,c,d,W[4],6,0xf7537e82UL)
  160. II(d,a,b,c,W[11],10,0xbd3af235UL)
  161. II(c,d,a,b,W[2],15,0x2ad7d2bbUL)
  162. II(b,c,d,a,W[9],21,0xeb86d391UL)
  163. md5->state[0] = md5->state[0] + a;
  164. md5->state[1] = md5->state[1] + b;
  165. md5->state[2] = md5->state[2] + c;
  166. md5->state[3] = md5->state[3] + d;
  167. }
  168. /**
  169. Initialize the hash state
  170. @param sha1 The hash state you wish to initialize
  171. */
  172. void md5_init(struct md5_state *md5)
  173. {
  174. assert(md5 != NULL);
  175. md5->state[0] = 0x67452301UL;
  176. md5->state[1] = 0xefcdab89UL;
  177. md5->state[2] = 0x98badcfeUL;
  178. md5->state[3] = 0x10325476UL;
  179. md5->curlen = 0;
  180. md5->length = 0;
  181. }
  182. /**
  183. Process a block of memory though the hash
  184. @param sha1 The hash state
  185. @param in The data to hash
  186. @param inlen The length of the data (octets)
  187. */
  188. void md5_process(struct md5_state *md5,
  189. const unsigned char *in, Py_ssize_t inlen)
  190. {
  191. Py_ssize_t n;
  192. assert(md5 != NULL);
  193. assert(in != NULL);
  194. assert(md5->curlen <= sizeof(md5->buf));
  195. while (inlen > 0) {
  196. if (md5->curlen == 0 && inlen >= MD5_BLOCKSIZE) {
  197. md5_compress(md5, (unsigned char *)in);
  198. md5->length += MD5_BLOCKSIZE * 8;
  199. in += MD5_BLOCKSIZE;
  200. inlen -= MD5_BLOCKSIZE;
  201. } else {
  202. n = MIN(inlen, (MD5_BLOCKSIZE - md5->curlen));
  203. memcpy(md5->buf + md5->curlen, in, (size_t)n);
  204. md5->curlen += n;
  205. in += n;
  206. inlen -= n;
  207. if (md5->curlen == MD5_BLOCKSIZE) {
  208. md5_compress(md5, md5->buf);
  209. md5->length += 8*MD5_BLOCKSIZE;
  210. md5->curlen = 0;
  211. }
  212. }
  213. }
  214. }
  215. /**
  216. Terminate the hash to get the digest
  217. @param sha1 The hash state
  218. @param out [out] The destination of the hash (16 bytes)
  219. */
  220. void md5_done(struct md5_state *md5, unsigned char *out)
  221. {
  222. int i;
  223. assert(md5 != NULL);
  224. assert(out != NULL);
  225. assert(md5->curlen < sizeof(md5->buf));
  226. /* increase the length of the message */
  227. md5->length += md5->curlen * 8;
  228. /* append the '1' bit */
  229. md5->buf[md5->curlen++] = (unsigned char)0x80;
  230. /* if the length is currently above 56 bytes we append zeros
  231. * then compress. Then we can fall back to padding zeros and length
  232. * encoding like normal.
  233. */
  234. if (md5->curlen > 56) {
  235. while (md5->curlen < 64) {
  236. md5->buf[md5->curlen++] = (unsigned char)0;
  237. }
  238. md5_compress(md5, md5->buf);
  239. md5->curlen = 0;
  240. }
  241. /* pad upto 56 bytes of zeroes */
  242. while (md5->curlen < 56) {
  243. md5->buf[md5->curlen++] = (unsigned char)0;
  244. }
  245. /* store length */
  246. STORE64L(md5->length, md5->buf+56);
  247. md5_compress(md5, md5->buf);
  248. /* copy output */
  249. for (i = 0; i < 4; i++) {
  250. STORE32L(md5->state[i], out+(4*i));
  251. }
  252. }
  253. /* .Source: /cvs/libtom/libtomcrypt/src/hashes/md5.c,v $ */
  254. /* .Revision: 1.10 $ */
  255. /* .Date: 2007/05/12 14:25:28 $ */
  256. /*
  257. * End of copied MD5 code.
  258. *
  259. * ------------------------------------------------------------------------
  260. */
  261. static PyTypeObject MD5type;
  262. static MD5object *
  263. newMD5object(void)
  264. {
  265. return (MD5object *)PyObject_New(MD5object, &MD5type);
  266. }
  267. /* Internal methods for a hash object */
  268. static void
  269. MD5_dealloc(PyObject *ptr)
  270. {
  271. PyObject_Del(ptr);
  272. }
  273. /* External methods for a hash object */
  274. PyDoc_STRVAR(MD5_copy__doc__, "Return a copy of the hash object.");
  275. static PyObject *
  276. MD5_copy(MD5object *self, PyObject *unused)
  277. {
  278. MD5object *newobj;
  279. if (Py_TYPE(self) == &MD5type) {
  280. if ( (newobj = newMD5object())==NULL)
  281. return NULL;
  282. } else {
  283. if ( (newobj = newMD5object())==NULL)
  284. return NULL;
  285. }
  286. newobj->hash_state = self->hash_state;
  287. return (PyObject *)newobj;
  288. }
  289. PyDoc_STRVAR(MD5_digest__doc__,
  290. "Return the digest value as a string of binary data.");
  291. static PyObject *
  292. MD5_digest(MD5object *self, PyObject *unused)
  293. {
  294. unsigned char digest[MD5_DIGESTSIZE];
  295. struct md5_state temp;
  296. temp = self->hash_state;
  297. md5_done(&temp, digest);
  298. return PyBytes_FromStringAndSize((const char *)digest, MD5_DIGESTSIZE);
  299. }
  300. PyDoc_STRVAR(MD5_hexdigest__doc__,
  301. "Return the digest value as a string of hexadecimal digits.");
  302. static PyObject *
  303. MD5_hexdigest(MD5object *self, PyObject *unused)
  304. {
  305. unsigned char digest[MD5_DIGESTSIZE];
  306. struct md5_state temp;
  307. PyObject *retval;
  308. Py_UNICODE *hex_digest;
  309. int i, j;
  310. /* Get the raw (binary) digest value */
  311. temp = self->hash_state;
  312. md5_done(&temp, digest);
  313. /* Create a new string */
  314. retval = PyUnicode_FromStringAndSize(NULL, MD5_DIGESTSIZE * 2);
  315. if (!retval)
  316. return NULL;
  317. hex_digest = PyUnicode_AS_UNICODE(retval);
  318. if (!hex_digest) {
  319. Py_DECREF(retval);
  320. return NULL;
  321. }
  322. /* Make hex version of the digest */
  323. for(i=j=0; i<MD5_DIGESTSIZE; i++) {
  324. char c;
  325. c = (digest[i] >> 4) & 0xf;
  326. c = (c>9) ? c+'a'-10 : c + '0';
  327. hex_digest[j++] = c;
  328. c = (digest[i] & 0xf);
  329. c = (c>9) ? c+'a'-10 : c + '0';
  330. hex_digest[j++] = c;
  331. }
  332. return retval;
  333. }
  334. PyDoc_STRVAR(MD5_update__doc__,
  335. "Update this hash object's state with the provided string.");
  336. static PyObject *
  337. MD5_update(MD5object *self, PyObject *args)
  338. {
  339. PyObject *obj;
  340. Py_buffer buf;
  341. if (!PyArg_ParseTuple(args, "O:update", &obj))
  342. return NULL;
  343. GET_BUFFER_VIEW_OR_ERROUT(obj, &buf);
  344. md5_process(&self->hash_state, buf.buf, buf.len);
  345. PyBuffer_Release(&buf);
  346. Py_INCREF(Py_None);
  347. return Py_None;
  348. }
  349. static PyMethodDef MD5_methods[] = {
  350. {"copy", (PyCFunction)MD5_copy, METH_NOARGS, MD5_copy__doc__},
  351. {"digest", (PyCFunction)MD5_digest, METH_NOARGS, MD5_digest__doc__},
  352. {"hexdigest", (PyCFunction)MD5_hexdigest, METH_NOARGS, MD5_hexdigest__doc__},
  353. {"update", (PyCFunction)MD5_update, METH_VARARGS, MD5_update__doc__},
  354. {NULL, NULL} /* sentinel */
  355. };
  356. static PyObject *
  357. MD5_get_block_size(PyObject *self, void *closure)
  358. {
  359. return PyLong_FromLong(MD5_BLOCKSIZE);
  360. }
  361. static PyObject *
  362. MD5_get_name(PyObject *self, void *closure)
  363. {
  364. return PyUnicode_FromStringAndSize("MD5", 3);
  365. }
  366. static PyObject *
  367. md5_get_digest_size(PyObject *self, void *closure)
  368. {
  369. return PyLong_FromLong(MD5_DIGESTSIZE);
  370. }
  371. static PyGetSetDef MD5_getseters[] = {
  372. {"block_size",
  373. (getter)MD5_get_block_size, NULL,
  374. NULL,
  375. NULL},
  376. {"name",
  377. (getter)MD5_get_name, NULL,
  378. NULL,
  379. NULL},
  380. {"digest_size",
  381. (getter)md5_get_digest_size, NULL,
  382. NULL,
  383. NULL},
  384. {NULL} /* Sentinel */
  385. };
  386. static PyTypeObject MD5type = {
  387. PyVarObject_HEAD_INIT(NULL, 0)
  388. "_md5.md5", /*tp_name*/
  389. sizeof(MD5object), /*tp_size*/
  390. 0, /*tp_itemsize*/
  391. /* methods */
  392. MD5_dealloc, /*tp_dealloc*/
  393. 0, /*tp_print*/
  394. 0, /*tp_getattr*/
  395. 0, /*tp_setattr*/
  396. 0, /*tp_reserved*/
  397. 0, /*tp_repr*/
  398. 0, /*tp_as_number*/
  399. 0, /*tp_as_sequence*/
  400. 0, /*tp_as_mapping*/
  401. 0, /*tp_hash*/
  402. 0, /*tp_call*/
  403. 0, /*tp_str*/
  404. 0, /*tp_getattro*/
  405. 0, /*tp_setattro*/
  406. 0, /*tp_as_buffer*/
  407. Py_TPFLAGS_DEFAULT, /*tp_flags*/
  408. 0, /*tp_doc*/
  409. 0, /*tp_traverse*/
  410. 0, /*tp_clear*/
  411. 0, /*tp_richcompare*/
  412. 0, /*tp_weaklistoffset*/
  413. 0, /*tp_iter*/
  414. 0, /*tp_iternext*/
  415. MD5_methods, /* tp_methods */
  416. NULL, /* tp_members */
  417. MD5_getseters, /* tp_getset */
  418. };
  419. /* The single module-level function: new() */
  420. PyDoc_STRVAR(MD5_new__doc__,
  421. "Return a new MD5 hash object; optionally initialized with a string.");
  422. static PyObject *
  423. MD5_new(PyObject *self, PyObject *args, PyObject *kwdict)
  424. {
  425. static char *kwlist[] = {"string", NULL};
  426. MD5object *new;
  427. PyObject *data_obj = NULL;
  428. Py_buffer buf;
  429. if (!PyArg_ParseTupleAndKeywords(args, kwdict, "|O:new", kwlist,
  430. &data_obj)) {
  431. return NULL;
  432. }
  433. if (data_obj)
  434. GET_BUFFER_VIEW_OR_ERROUT(data_obj, &buf);
  435. if ((new = newMD5object()) == NULL) {
  436. if (data_obj)
  437. PyBuffer_Release(&buf);
  438. return NULL;
  439. }
  440. md5_init(&new->hash_state);
  441. if (PyErr_Occurred()) {
  442. Py_DECREF(new);
  443. if (data_obj)
  444. PyBuffer_Release(&buf);
  445. return NULL;
  446. }
  447. if (data_obj) {
  448. md5_process(&new->hash_state, buf.buf, buf.len);
  449. PyBuffer_Release(&buf);
  450. }
  451. return (PyObject *)new;
  452. }
  453. /* List of functions exported by this module */
  454. static struct PyMethodDef MD5_functions[] = {
  455. {"md5", (PyCFunction)MD5_new, METH_VARARGS|METH_KEYWORDS, MD5_new__doc__},
  456. {NULL, NULL} /* Sentinel */
  457. };
  458. /* Initialize this module. */
  459. #define insint(n,v) { PyModule_AddIntConstant(m,n,v); }
  460. static struct PyModuleDef _md5module = {
  461. PyModuleDef_HEAD_INIT,
  462. "_md5",
  463. NULL,
  464. -1,
  465. MD5_functions,
  466. NULL,
  467. NULL,
  468. NULL,
  469. NULL
  470. };
  471. PyMODINIT_FUNC
  472. PyInit__md5(void)
  473. {
  474. Py_TYPE(&MD5type) = &PyType_Type;
  475. if (PyType_Ready(&MD5type) < 0)
  476. return NULL;
  477. return PyModule_Create(&_md5module);
  478. }