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.

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