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.

551 lines
14 KiB

  1. /* SHA1 module */
  2. /* This module provides an interface to the SHA1 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. /* SHA1 objects */
  12. #include "Python.h"
  13. #include "hashlib.h"
  14. /* Some useful types */
  15. #if SIZEOF_INT == 4
  16. typedef unsigned int SHA1_INT32; /* 32-bit integer */
  17. typedef PY_LONG_LONG SHA1_INT64; /* 64-bit integer */
  18. #else
  19. /* not defined. compilation will die. */
  20. #endif
  21. /* The SHA1 block size and message digest sizes, in bytes */
  22. #define SHA1_BLOCKSIZE 64
  23. #define SHA1_DIGESTSIZE 20
  24. /* The structure for storing SHA1 info */
  25. struct sha1_state {
  26. SHA1_INT64 length;
  27. SHA1_INT32 state[5], curlen;
  28. unsigned char buf[SHA1_BLOCKSIZE];
  29. };
  30. typedef struct {
  31. PyObject_HEAD
  32. struct sha1_state hash_state;
  33. } SHA1object;
  34. /* ------------------------------------------------------------------------
  35. *
  36. * This code for the SHA1 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 ROL(x, y) ( (((unsigned long)(x)<<(unsigned long)((y)&31)) | (((unsigned long)(x)&0xFFFFFFFFUL)>>(unsigned long)(32-((y)&31)))) & 0xFFFFFFFFUL)
  55. #define ROLc(x, y) ( (((unsigned long)(x)<<(unsigned long)((y)&31)) | (((unsigned long)(x)&0xFFFFFFFFUL)>>(unsigned long)(32-((y)&31)))) & 0xFFFFFFFFUL)
  56. /* Endian Neutral macros that work on all platforms */
  57. #define STORE32H(x, y) \
  58. { (y)[0] = (unsigned char)(((x)>>24)&255); (y)[1] = (unsigned char)(((x)>>16)&255); \
  59. (y)[2] = (unsigned char)(((x)>>8)&255); (y)[3] = (unsigned char)((x)&255); }
  60. #define LOAD32H(x, y) \
  61. { x = ((unsigned long)((y)[0] & 255)<<24) | \
  62. ((unsigned long)((y)[1] & 255)<<16) | \
  63. ((unsigned long)((y)[2] & 255)<<8) | \
  64. ((unsigned long)((y)[3] & 255)); }
  65. #define STORE64H(x, y) \
  66. { (y)[0] = (unsigned char)(((x)>>56)&255); (y)[1] = (unsigned char)(((x)>>48)&255); \
  67. (y)[2] = (unsigned char)(((x)>>40)&255); (y)[3] = (unsigned char)(((x)>>32)&255); \
  68. (y)[4] = (unsigned char)(((x)>>24)&255); (y)[5] = (unsigned char)(((x)>>16)&255); \
  69. (y)[6] = (unsigned char)(((x)>>8)&255); (y)[7] = (unsigned char)((x)&255); }
  70. /* SHA1 macros */
  71. #define F0(x,y,z) (z ^ (x & (y ^ z)))
  72. #define F1(x,y,z) (x ^ y ^ z)
  73. #define F2(x,y,z) ((x & y) | (z & (x | y)))
  74. #define F3(x,y,z) (x ^ y ^ z)
  75. static void sha1_compress(struct sha1_state *sha1, unsigned char *buf)
  76. {
  77. SHA1_INT32 a,b,c,d,e,W[80],i;
  78. /* copy the state into 512-bits into W[0..15] */
  79. for (i = 0; i < 16; i++) {
  80. LOAD32H(W[i], buf + (4*i));
  81. }
  82. /* copy state */
  83. a = sha1->state[0];
  84. b = sha1->state[1];
  85. c = sha1->state[2];
  86. d = sha1->state[3];
  87. e = sha1->state[4];
  88. /* expand it */
  89. for (i = 16; i < 80; i++) {
  90. W[i] = ROL(W[i-3] ^ W[i-8] ^ W[i-14] ^ W[i-16], 1);
  91. }
  92. /* compress */
  93. /* round one */
  94. #define FF_0(a,b,c,d,e,i) e = (ROLc(a, 5) + F0(b,c,d) + e + W[i] + 0x5a827999UL); b = ROLc(b, 30);
  95. #define FF_1(a,b,c,d,e,i) e = (ROLc(a, 5) + F1(b,c,d) + e + W[i] + 0x6ed9eba1UL); b = ROLc(b, 30);
  96. #define FF_2(a,b,c,d,e,i) e = (ROLc(a, 5) + F2(b,c,d) + e + W[i] + 0x8f1bbcdcUL); b = ROLc(b, 30);
  97. #define FF_3(a,b,c,d,e,i) e = (ROLc(a, 5) + F3(b,c,d) + e + W[i] + 0xca62c1d6UL); b = ROLc(b, 30);
  98. for (i = 0; i < 20; ) {
  99. FF_0(a,b,c,d,e,i++);
  100. FF_0(e,a,b,c,d,i++);
  101. FF_0(d,e,a,b,c,i++);
  102. FF_0(c,d,e,a,b,i++);
  103. FF_0(b,c,d,e,a,i++);
  104. }
  105. /* round two */
  106. for (; i < 40; ) {
  107. FF_1(a,b,c,d,e,i++);
  108. FF_1(e,a,b,c,d,i++);
  109. FF_1(d,e,a,b,c,i++);
  110. FF_1(c,d,e,a,b,i++);
  111. FF_1(b,c,d,e,a,i++);
  112. }
  113. /* round three */
  114. for (; i < 60; ) {
  115. FF_2(a,b,c,d,e,i++);
  116. FF_2(e,a,b,c,d,i++);
  117. FF_2(d,e,a,b,c,i++);
  118. FF_2(c,d,e,a,b,i++);
  119. FF_2(b,c,d,e,a,i++);
  120. }
  121. /* round four */
  122. for (; i < 80; ) {
  123. FF_3(a,b,c,d,e,i++);
  124. FF_3(e,a,b,c,d,i++);
  125. FF_3(d,e,a,b,c,i++);
  126. FF_3(c,d,e,a,b,i++);
  127. FF_3(b,c,d,e,a,i++);
  128. }
  129. #undef FF_0
  130. #undef FF_1
  131. #undef FF_2
  132. #undef FF_3
  133. /* store */
  134. sha1->state[0] = sha1->state[0] + a;
  135. sha1->state[1] = sha1->state[1] + b;
  136. sha1->state[2] = sha1->state[2] + c;
  137. sha1->state[3] = sha1->state[3] + d;
  138. sha1->state[4] = sha1->state[4] + e;
  139. }
  140. /**
  141. Initialize the hash state
  142. @param sha1 The hash state you wish to initialize
  143. */
  144. static void
  145. sha1_init(struct sha1_state *sha1)
  146. {
  147. assert(sha1 != NULL);
  148. sha1->state[0] = 0x67452301UL;
  149. sha1->state[1] = 0xefcdab89UL;
  150. sha1->state[2] = 0x98badcfeUL;
  151. sha1->state[3] = 0x10325476UL;
  152. sha1->state[4] = 0xc3d2e1f0UL;
  153. sha1->curlen = 0;
  154. sha1->length = 0;
  155. }
  156. /**
  157. Process a block of memory though the hash
  158. @param sha1 The hash state
  159. @param in The data to hash
  160. @param inlen The length of the data (octets)
  161. */
  162. static void
  163. sha1_process(struct sha1_state *sha1,
  164. const unsigned char *in, Py_ssize_t inlen)
  165. {
  166. Py_ssize_t n;
  167. assert(sha1 != NULL);
  168. assert(in != NULL);
  169. assert(sha1->curlen <= sizeof(sha1->buf));
  170. while (inlen > 0) {
  171. if (sha1->curlen == 0 && inlen >= SHA1_BLOCKSIZE) {
  172. sha1_compress(sha1, (unsigned char *)in);
  173. sha1->length += SHA1_BLOCKSIZE * 8;
  174. in += SHA1_BLOCKSIZE;
  175. inlen -= SHA1_BLOCKSIZE;
  176. } else {
  177. n = Py_MIN(inlen, (Py_ssize_t)(SHA1_BLOCKSIZE - sha1->curlen));
  178. memcpy(sha1->buf + sha1->curlen, in, (size_t)n);
  179. sha1->curlen += (SHA1_INT32)n;
  180. in += n;
  181. inlen -= n;
  182. if (sha1->curlen == SHA1_BLOCKSIZE) {
  183. sha1_compress(sha1, sha1->buf);
  184. sha1->length += 8*SHA1_BLOCKSIZE;
  185. sha1->curlen = 0;
  186. }
  187. }
  188. }
  189. }
  190. /**
  191. Terminate the hash to get the digest
  192. @param sha1 The hash state
  193. @param out [out] The destination of the hash (20 bytes)
  194. */
  195. static void
  196. sha1_done(struct sha1_state *sha1, unsigned char *out)
  197. {
  198. int i;
  199. assert(sha1 != NULL);
  200. assert(out != NULL);
  201. assert(sha1->curlen < sizeof(sha1->buf));
  202. /* increase the length of the message */
  203. sha1->length += sha1->curlen * 8;
  204. /* append the '1' bit */
  205. sha1->buf[sha1->curlen++] = (unsigned char)0x80;
  206. /* if the length is currently above 56 bytes we append zeros
  207. * then compress. Then we can fall back to padding zeros and length
  208. * encoding like normal.
  209. */
  210. if (sha1->curlen > 56) {
  211. while (sha1->curlen < 64) {
  212. sha1->buf[sha1->curlen++] = (unsigned char)0;
  213. }
  214. sha1_compress(sha1, sha1->buf);
  215. sha1->curlen = 0;
  216. }
  217. /* pad upto 56 bytes of zeroes */
  218. while (sha1->curlen < 56) {
  219. sha1->buf[sha1->curlen++] = (unsigned char)0;
  220. }
  221. /* store length */
  222. STORE64H(sha1->length, sha1->buf+56);
  223. sha1_compress(sha1, sha1->buf);
  224. /* copy output */
  225. for (i = 0; i < 5; i++) {
  226. STORE32H(sha1->state[i], out+(4*i));
  227. }
  228. }
  229. /* .Source: /cvs/libtom/libtomcrypt/src/hashes/sha1.c,v $ */
  230. /* .Revision: 1.10 $ */
  231. /* .Date: 2007/05/12 14:25:28 $ */
  232. /*
  233. * End of copied SHA1 code.
  234. *
  235. * ------------------------------------------------------------------------
  236. */
  237. static PyTypeObject SHA1type;
  238. static SHA1object *
  239. newSHA1object(void)
  240. {
  241. return (SHA1object *)PyObject_New(SHA1object, &SHA1type);
  242. }
  243. /* Internal methods for a hash object */
  244. static void
  245. SHA1_dealloc(PyObject *ptr)
  246. {
  247. PyObject_Del(ptr);
  248. }
  249. /* External methods for a hash object */
  250. PyDoc_STRVAR(SHA1_copy__doc__, "Return a copy of the hash object.");
  251. static PyObject *
  252. SHA1_copy(SHA1object *self, PyObject *unused)
  253. {
  254. SHA1object *newobj;
  255. if ((newobj = newSHA1object()) == NULL)
  256. return NULL;
  257. newobj->hash_state = self->hash_state;
  258. return (PyObject *)newobj;
  259. }
  260. PyDoc_STRVAR(SHA1_digest__doc__,
  261. "Return the digest value as a string of binary data.");
  262. static PyObject *
  263. SHA1_digest(SHA1object *self, PyObject *unused)
  264. {
  265. unsigned char digest[SHA1_DIGESTSIZE];
  266. struct sha1_state temp;
  267. temp = self->hash_state;
  268. sha1_done(&temp, digest);
  269. return PyBytes_FromStringAndSize((const char *)digest, SHA1_DIGESTSIZE);
  270. }
  271. PyDoc_STRVAR(SHA1_hexdigest__doc__,
  272. "Return the digest value as a string of hexadecimal digits.");
  273. static PyObject *
  274. SHA1_hexdigest(SHA1object *self, PyObject *unused)
  275. {
  276. unsigned char digest[SHA1_DIGESTSIZE];
  277. struct sha1_state temp;
  278. PyObject *retval;
  279. Py_UCS1 *hex_digest;
  280. int i, j;
  281. /* Get the raw (binary) digest value */
  282. temp = self->hash_state;
  283. sha1_done(&temp, digest);
  284. /* Create a new string */
  285. retval = PyUnicode_New(SHA1_DIGESTSIZE * 2, 127);
  286. if (!retval)
  287. return NULL;
  288. hex_digest = PyUnicode_1BYTE_DATA(retval);
  289. /* Make hex version of the digest */
  290. for(i=j=0; i<SHA1_DIGESTSIZE; i++) {
  291. unsigned char c;
  292. c = (digest[i] >> 4) & 0xf;
  293. hex_digest[j++] = Py_hexdigits[c];
  294. c = (digest[i] & 0xf);
  295. hex_digest[j++] = Py_hexdigits[c];
  296. }
  297. #ifdef Py_DEBUG
  298. assert(_PyUnicode_CheckConsistency(retval, 1));
  299. #endif
  300. return retval;
  301. }
  302. PyDoc_STRVAR(SHA1_update__doc__,
  303. "Update this hash object's state with the provided string.");
  304. static PyObject *
  305. SHA1_update(SHA1object *self, PyObject *args)
  306. {
  307. PyObject *obj;
  308. Py_buffer buf;
  309. if (!PyArg_ParseTuple(args, "O:update", &obj))
  310. return NULL;
  311. GET_BUFFER_VIEW_OR_ERROUT(obj, &buf);
  312. sha1_process(&self->hash_state, buf.buf, buf.len);
  313. PyBuffer_Release(&buf);
  314. Py_INCREF(Py_None);
  315. return Py_None;
  316. }
  317. static PyMethodDef SHA1_methods[] = {
  318. {"copy", (PyCFunction)SHA1_copy, METH_NOARGS, SHA1_copy__doc__},
  319. {"digest", (PyCFunction)SHA1_digest, METH_NOARGS, SHA1_digest__doc__},
  320. {"hexdigest", (PyCFunction)SHA1_hexdigest, METH_NOARGS, SHA1_hexdigest__doc__},
  321. {"update", (PyCFunction)SHA1_update, METH_VARARGS, SHA1_update__doc__},
  322. {NULL, NULL} /* sentinel */
  323. };
  324. static PyObject *
  325. SHA1_get_block_size(PyObject *self, void *closure)
  326. {
  327. return PyLong_FromLong(SHA1_BLOCKSIZE);
  328. }
  329. static PyObject *
  330. SHA1_get_name(PyObject *self, void *closure)
  331. {
  332. return PyUnicode_FromStringAndSize("sha1", 4);
  333. }
  334. static PyObject *
  335. sha1_get_digest_size(PyObject *self, void *closure)
  336. {
  337. return PyLong_FromLong(SHA1_DIGESTSIZE);
  338. }
  339. static PyGetSetDef SHA1_getseters[] = {
  340. {"block_size",
  341. (getter)SHA1_get_block_size, NULL,
  342. NULL,
  343. NULL},
  344. {"name",
  345. (getter)SHA1_get_name, NULL,
  346. NULL,
  347. NULL},
  348. {"digest_size",
  349. (getter)sha1_get_digest_size, NULL,
  350. NULL,
  351. NULL},
  352. {NULL} /* Sentinel */
  353. };
  354. static PyTypeObject SHA1type = {
  355. PyVarObject_HEAD_INIT(NULL, 0)
  356. "_sha1.sha1", /*tp_name*/
  357. sizeof(SHA1object), /*tp_size*/
  358. 0, /*tp_itemsize*/
  359. /* methods */
  360. SHA1_dealloc, /*tp_dealloc*/
  361. 0, /*tp_print*/
  362. 0, /*tp_getattr*/
  363. 0, /*tp_setattr*/
  364. 0, /*tp_reserved*/
  365. 0, /*tp_repr*/
  366. 0, /*tp_as_number*/
  367. 0, /*tp_as_sequence*/
  368. 0, /*tp_as_mapping*/
  369. 0, /*tp_hash*/
  370. 0, /*tp_call*/
  371. 0, /*tp_str*/
  372. 0, /*tp_getattro*/
  373. 0, /*tp_setattro*/
  374. 0, /*tp_as_buffer*/
  375. Py_TPFLAGS_DEFAULT, /*tp_flags*/
  376. 0, /*tp_doc*/
  377. 0, /*tp_traverse*/
  378. 0, /*tp_clear*/
  379. 0, /*tp_richcompare*/
  380. 0, /*tp_weaklistoffset*/
  381. 0, /*tp_iter*/
  382. 0, /*tp_iternext*/
  383. SHA1_methods, /* tp_methods */
  384. NULL, /* tp_members */
  385. SHA1_getseters, /* tp_getset */
  386. };
  387. /* The single module-level function: new() */
  388. PyDoc_STRVAR(SHA1_new__doc__,
  389. "Return a new SHA1 hash object; optionally initialized with a string.");
  390. static PyObject *
  391. SHA1_new(PyObject *self, PyObject *args, PyObject *kwdict)
  392. {
  393. static char *kwlist[] = {"string", NULL};
  394. SHA1object *new;
  395. PyObject *data_obj = NULL;
  396. Py_buffer buf;
  397. if (!PyArg_ParseTupleAndKeywords(args, kwdict, "|O:new", kwlist,
  398. &data_obj)) {
  399. return NULL;
  400. }
  401. if (data_obj)
  402. GET_BUFFER_VIEW_OR_ERROUT(data_obj, &buf);
  403. if ((new = newSHA1object()) == NULL) {
  404. if (data_obj)
  405. PyBuffer_Release(&buf);
  406. return NULL;
  407. }
  408. sha1_init(&new->hash_state);
  409. if (PyErr_Occurred()) {
  410. Py_DECREF(new);
  411. if (data_obj)
  412. PyBuffer_Release(&buf);
  413. return NULL;
  414. }
  415. if (data_obj) {
  416. sha1_process(&new->hash_state, buf.buf, buf.len);
  417. PyBuffer_Release(&buf);
  418. }
  419. return (PyObject *)new;
  420. }
  421. /* List of functions exported by this module */
  422. static struct PyMethodDef SHA1_functions[] = {
  423. {"sha1",(PyCFunction)SHA1_new, METH_VARARGS|METH_KEYWORDS,SHA1_new__doc__},
  424. {NULL, NULL} /* Sentinel */
  425. };
  426. /* Initialize this module. */
  427. #define insint(n,v) { PyModule_AddIntConstant(m,n,v); }
  428. static struct PyModuleDef _sha1module = {
  429. PyModuleDef_HEAD_INIT,
  430. "_sha1",
  431. NULL,
  432. -1,
  433. SHA1_functions,
  434. NULL,
  435. NULL,
  436. NULL,
  437. NULL
  438. };
  439. PyMODINIT_FUNC
  440. PyInit__sha1(void)
  441. {
  442. Py_TYPE(&SHA1type) = &PyType_Type;
  443. if (PyType_Ready(&SHA1type) < 0)
  444. return NULL;
  445. return PyModule_Create(&_sha1module);
  446. }