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.

583 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. static void
  173. md5_init(struct md5_state *md5)
  174. {
  175. assert(md5 != NULL);
  176. md5->state[0] = 0x67452301UL;
  177. md5->state[1] = 0xefcdab89UL;
  178. md5->state[2] = 0x98badcfeUL;
  179. md5->state[3] = 0x10325476UL;
  180. md5->curlen = 0;
  181. md5->length = 0;
  182. }
  183. /**
  184. Process a block of memory though the hash
  185. @param sha1 The hash state
  186. @param in The data to hash
  187. @param inlen The length of the data (octets)
  188. */
  189. static void
  190. md5_process(struct md5_state *md5, const unsigned char *in, Py_ssize_t inlen)
  191. {
  192. Py_ssize_t n;
  193. assert(md5 != NULL);
  194. assert(in != NULL);
  195. assert(md5->curlen <= sizeof(md5->buf));
  196. while (inlen > 0) {
  197. if (md5->curlen == 0 && inlen >= MD5_BLOCKSIZE) {
  198. md5_compress(md5, (unsigned char *)in);
  199. md5->length += MD5_BLOCKSIZE * 8;
  200. in += MD5_BLOCKSIZE;
  201. inlen -= MD5_BLOCKSIZE;
  202. } else {
  203. n = MIN(inlen, (Py_ssize_t)(MD5_BLOCKSIZE - md5->curlen));
  204. memcpy(md5->buf + md5->curlen, in, (size_t)n);
  205. md5->curlen += n;
  206. in += n;
  207. inlen -= n;
  208. if (md5->curlen == MD5_BLOCKSIZE) {
  209. md5_compress(md5, md5->buf);
  210. md5->length += 8*MD5_BLOCKSIZE;
  211. md5->curlen = 0;
  212. }
  213. }
  214. }
  215. }
  216. /**
  217. Terminate the hash to get the digest
  218. @param sha1 The hash state
  219. @param out [out] The destination of the hash (16 bytes)
  220. */
  221. static void
  222. md5_done(struct md5_state *md5, unsigned char *out)
  223. {
  224. int i;
  225. assert(md5 != NULL);
  226. assert(out != NULL);
  227. assert(md5->curlen < sizeof(md5->buf));
  228. /* increase the length of the message */
  229. md5->length += md5->curlen * 8;
  230. /* append the '1' bit */
  231. md5->buf[md5->curlen++] = (unsigned char)0x80;
  232. /* if the length is currently above 56 bytes we append zeros
  233. * then compress. Then we can fall back to padding zeros and length
  234. * encoding like normal.
  235. */
  236. if (md5->curlen > 56) {
  237. while (md5->curlen < 64) {
  238. md5->buf[md5->curlen++] = (unsigned char)0;
  239. }
  240. md5_compress(md5, md5->buf);
  241. md5->curlen = 0;
  242. }
  243. /* pad upto 56 bytes of zeroes */
  244. while (md5->curlen < 56) {
  245. md5->buf[md5->curlen++] = (unsigned char)0;
  246. }
  247. /* store length */
  248. STORE64L(md5->length, md5->buf+56);
  249. md5_compress(md5, md5->buf);
  250. /* copy output */
  251. for (i = 0; i < 4; i++) {
  252. STORE32L(md5->state[i], out+(4*i));
  253. }
  254. }
  255. /* .Source: /cvs/libtom/libtomcrypt/src/hashes/md5.c,v $ */
  256. /* .Revision: 1.10 $ */
  257. /* .Date: 2007/05/12 14:25:28 $ */
  258. /*
  259. * End of copied MD5 code.
  260. *
  261. * ------------------------------------------------------------------------
  262. */
  263. static PyTypeObject MD5type;
  264. static MD5object *
  265. newMD5object(void)
  266. {
  267. return (MD5object *)PyObject_New(MD5object, &MD5type);
  268. }
  269. /* Internal methods for a hash object */
  270. static void
  271. MD5_dealloc(PyObject *ptr)
  272. {
  273. PyObject_Del(ptr);
  274. }
  275. /* External methods for a hash object */
  276. PyDoc_STRVAR(MD5_copy__doc__, "Return a copy of the hash object.");
  277. static PyObject *
  278. MD5_copy(MD5object *self, PyObject *unused)
  279. {
  280. MD5object *newobj;
  281. if (Py_TYPE(self) == &MD5type) {
  282. if ( (newobj = newMD5object())==NULL)
  283. return NULL;
  284. } else {
  285. if ( (newobj = newMD5object())==NULL)
  286. return NULL;
  287. }
  288. newobj->hash_state = self->hash_state;
  289. return (PyObject *)newobj;
  290. }
  291. PyDoc_STRVAR(MD5_digest__doc__,
  292. "Return the digest value as a string of binary data.");
  293. static PyObject *
  294. MD5_digest(MD5object *self, PyObject *unused)
  295. {
  296. unsigned char digest[MD5_DIGESTSIZE];
  297. struct md5_state temp;
  298. temp = self->hash_state;
  299. md5_done(&temp, digest);
  300. return PyBytes_FromStringAndSize((const char *)digest, MD5_DIGESTSIZE);
  301. }
  302. PyDoc_STRVAR(MD5_hexdigest__doc__,
  303. "Return the digest value as a string of hexadecimal digits.");
  304. static PyObject *
  305. MD5_hexdigest(MD5object *self, PyObject *unused)
  306. {
  307. unsigned char digest[MD5_DIGESTSIZE];
  308. struct md5_state temp;
  309. PyObject *retval;
  310. Py_UCS1 *hex_digest;
  311. int i, j;
  312. /* Get the raw (binary) digest value */
  313. temp = self->hash_state;
  314. md5_done(&temp, digest);
  315. /* Create a new string */
  316. retval = PyUnicode_New(MD5_DIGESTSIZE * 2, 127);
  317. if (!retval)
  318. return NULL;
  319. hex_digest = PyUnicode_1BYTE_DATA(retval);
  320. /* Make hex version of the digest */
  321. for(i=j=0; i<MD5_DIGESTSIZE; i++) {
  322. unsigned char c;
  323. c = (digest[i] >> 4) & 0xf;
  324. hex_digest[j++] = Py_hexdigits[c];
  325. c = (digest[i] & 0xf);
  326. hex_digest[j++] = Py_hexdigits[c];
  327. }
  328. #ifdef Py_DEBUG
  329. assert(_PyUnicode_CheckConsistency(retval, 1));
  330. #endif
  331. return retval;
  332. }
  333. PyDoc_STRVAR(MD5_update__doc__,
  334. "Update this hash object's state with the provided string.");
  335. static PyObject *
  336. MD5_update(MD5object *self, PyObject *args)
  337. {
  338. PyObject *obj;
  339. Py_buffer buf;
  340. if (!PyArg_ParseTuple(args, "O:update", &obj))
  341. return NULL;
  342. GET_BUFFER_VIEW_OR_ERROUT(obj, &buf);
  343. md5_process(&self->hash_state, buf.buf, buf.len);
  344. PyBuffer_Release(&buf);
  345. Py_INCREF(Py_None);
  346. return Py_None;
  347. }
  348. static PyMethodDef MD5_methods[] = {
  349. {"copy", (PyCFunction)MD5_copy, METH_NOARGS, MD5_copy__doc__},
  350. {"digest", (PyCFunction)MD5_digest, METH_NOARGS, MD5_digest__doc__},
  351. {"hexdigest", (PyCFunction)MD5_hexdigest, METH_NOARGS, MD5_hexdigest__doc__},
  352. {"update", (PyCFunction)MD5_update, METH_VARARGS, MD5_update__doc__},
  353. {NULL, NULL} /* sentinel */
  354. };
  355. static PyObject *
  356. MD5_get_block_size(PyObject *self, void *closure)
  357. {
  358. return PyLong_FromLong(MD5_BLOCKSIZE);
  359. }
  360. static PyObject *
  361. MD5_get_name(PyObject *self, void *closure)
  362. {
  363. return PyUnicode_FromStringAndSize("MD5", 3);
  364. }
  365. static PyObject *
  366. md5_get_digest_size(PyObject *self, void *closure)
  367. {
  368. return PyLong_FromLong(MD5_DIGESTSIZE);
  369. }
  370. static PyGetSetDef MD5_getseters[] = {
  371. {"block_size",
  372. (getter)MD5_get_block_size, NULL,
  373. NULL,
  374. NULL},
  375. {"name",
  376. (getter)MD5_get_name, NULL,
  377. NULL,
  378. NULL},
  379. {"digest_size",
  380. (getter)md5_get_digest_size, NULL,
  381. NULL,
  382. NULL},
  383. {NULL} /* Sentinel */
  384. };
  385. static PyTypeObject MD5type = {
  386. PyVarObject_HEAD_INIT(NULL, 0)
  387. "_md5.md5", /*tp_name*/
  388. sizeof(MD5object), /*tp_size*/
  389. 0, /*tp_itemsize*/
  390. /* methods */
  391. MD5_dealloc, /*tp_dealloc*/
  392. 0, /*tp_print*/
  393. 0, /*tp_getattr*/
  394. 0, /*tp_setattr*/
  395. 0, /*tp_reserved*/
  396. 0, /*tp_repr*/
  397. 0, /*tp_as_number*/
  398. 0, /*tp_as_sequence*/
  399. 0, /*tp_as_mapping*/
  400. 0, /*tp_hash*/
  401. 0, /*tp_call*/
  402. 0, /*tp_str*/
  403. 0, /*tp_getattro*/
  404. 0, /*tp_setattro*/
  405. 0, /*tp_as_buffer*/
  406. Py_TPFLAGS_DEFAULT, /*tp_flags*/
  407. 0, /*tp_doc*/
  408. 0, /*tp_traverse*/
  409. 0, /*tp_clear*/
  410. 0, /*tp_richcompare*/
  411. 0, /*tp_weaklistoffset*/
  412. 0, /*tp_iter*/
  413. 0, /*tp_iternext*/
  414. MD5_methods, /* tp_methods */
  415. NULL, /* tp_members */
  416. MD5_getseters, /* tp_getset */
  417. };
  418. /* The single module-level function: new() */
  419. PyDoc_STRVAR(MD5_new__doc__,
  420. "Return a new MD5 hash object; optionally initialized with a string.");
  421. static PyObject *
  422. MD5_new(PyObject *self, PyObject *args, PyObject *kwdict)
  423. {
  424. static char *kwlist[] = {"string", NULL};
  425. MD5object *new;
  426. PyObject *data_obj = NULL;
  427. Py_buffer buf;
  428. if (!PyArg_ParseTupleAndKeywords(args, kwdict, "|O:new", kwlist,
  429. &data_obj)) {
  430. return NULL;
  431. }
  432. if (data_obj)
  433. GET_BUFFER_VIEW_OR_ERROUT(data_obj, &buf);
  434. if ((new = newMD5object()) == NULL) {
  435. if (data_obj)
  436. PyBuffer_Release(&buf);
  437. return NULL;
  438. }
  439. md5_init(&new->hash_state);
  440. if (PyErr_Occurred()) {
  441. Py_DECREF(new);
  442. if (data_obj)
  443. PyBuffer_Release(&buf);
  444. return NULL;
  445. }
  446. if (data_obj) {
  447. md5_process(&new->hash_state, buf.buf, buf.len);
  448. PyBuffer_Release(&buf);
  449. }
  450. return (PyObject *)new;
  451. }
  452. /* List of functions exported by this module */
  453. static struct PyMethodDef MD5_functions[] = {
  454. {"md5", (PyCFunction)MD5_new, METH_VARARGS|METH_KEYWORDS, MD5_new__doc__},
  455. {NULL, NULL} /* Sentinel */
  456. };
  457. /* Initialize this module. */
  458. #define insint(n,v) { PyModule_AddIntConstant(m,n,v); }
  459. static struct PyModuleDef _md5module = {
  460. PyModuleDef_HEAD_INIT,
  461. "_md5",
  462. NULL,
  463. -1,
  464. MD5_functions,
  465. NULL,
  466. NULL,
  467. NULL,
  468. NULL
  469. };
  470. PyMODINIT_FUNC
  471. PyInit__md5(void)
  472. {
  473. Py_TYPE(&MD5type) = &PyType_Type;
  474. if (PyType_Ready(&MD5type) < 0)
  475. return NULL;
  476. return PyModule_Create(&_md5module);
  477. }