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.

555 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. void sha1_init(struct sha1_state *sha1)
  148. {
  149. assert(sha1 != NULL);
  150. sha1->state[0] = 0x67452301UL;
  151. sha1->state[1] = 0xefcdab89UL;
  152. sha1->state[2] = 0x98badcfeUL;
  153. sha1->state[3] = 0x10325476UL;
  154. sha1->state[4] = 0xc3d2e1f0UL;
  155. sha1->curlen = 0;
  156. sha1->length = 0;
  157. }
  158. /**
  159. Process a block of memory though the hash
  160. @param sha1 The hash state
  161. @param in The data to hash
  162. @param inlen The length of the data (octets)
  163. */
  164. void sha1_process(struct sha1_state *sha1,
  165. const unsigned char *in, Py_ssize_t inlen)
  166. {
  167. Py_ssize_t n;
  168. assert(sha1 != NULL);
  169. assert(in != NULL);
  170. assert(sha1->curlen <= sizeof(sha1->buf));
  171. while (inlen > 0) {
  172. if (sha1->curlen == 0 && inlen >= SHA1_BLOCKSIZE) {
  173. sha1_compress(sha1, (unsigned char *)in);
  174. sha1->length += SHA1_BLOCKSIZE * 8;
  175. in += SHA1_BLOCKSIZE;
  176. inlen -= SHA1_BLOCKSIZE;
  177. } else {
  178. n = MIN(inlen, (Py_ssize_t)(SHA1_BLOCKSIZE - sha1->curlen));
  179. memcpy(sha1->buf + sha1->curlen, in, (size_t)n);
  180. sha1->curlen += n;
  181. in += n;
  182. inlen -= n;
  183. if (sha1->curlen == SHA1_BLOCKSIZE) {
  184. sha1_compress(sha1, sha1->buf);
  185. sha1->length += 8*SHA1_BLOCKSIZE;
  186. sha1->curlen = 0;
  187. }
  188. }
  189. }
  190. }
  191. /**
  192. Terminate the hash to get the digest
  193. @param sha1 The hash state
  194. @param out [out] The destination of the hash (20 bytes)
  195. */
  196. void 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 (Py_TYPE(self) == &SHA1type) {
  256. if ( (newobj = newSHA1object())==NULL)
  257. return NULL;
  258. } else {
  259. if ( (newobj = newSHA1object())==NULL)
  260. return NULL;
  261. }
  262. newobj->hash_state = self->hash_state;
  263. return (PyObject *)newobj;
  264. }
  265. PyDoc_STRVAR(SHA1_digest__doc__,
  266. "Return the digest value as a string of binary data.");
  267. static PyObject *
  268. SHA1_digest(SHA1object *self, PyObject *unused)
  269. {
  270. unsigned char digest[SHA1_DIGESTSIZE];
  271. struct sha1_state temp;
  272. temp = self->hash_state;
  273. sha1_done(&temp, digest);
  274. return PyBytes_FromStringAndSize((const char *)digest, SHA1_DIGESTSIZE);
  275. }
  276. PyDoc_STRVAR(SHA1_hexdigest__doc__,
  277. "Return the digest value as a string of hexadecimal digits.");
  278. static PyObject *
  279. SHA1_hexdigest(SHA1object *self, PyObject *unused)
  280. {
  281. unsigned char digest[SHA1_DIGESTSIZE];
  282. struct sha1_state temp;
  283. PyObject *retval;
  284. Py_UCS1 *hex_digest;
  285. int i, j;
  286. /* Get the raw (binary) digest value */
  287. temp = self->hash_state;
  288. sha1_done(&temp, digest);
  289. /* Create a new string */
  290. retval = PyUnicode_New(SHA1_DIGESTSIZE * 2, 127);
  291. if (!retval)
  292. return NULL;
  293. hex_digest = PyUnicode_1BYTE_DATA(retval);
  294. /* Make hex version of the digest */
  295. for(i=j=0; i<SHA1_DIGESTSIZE; i++) {
  296. unsigned char c;
  297. c = (digest[i] >> 4) & 0xf;
  298. hex_digest[j++] = Py_hexdigits[c];
  299. c = (digest[i] & 0xf);
  300. hex_digest[j++] = Py_hexdigits[c];
  301. }
  302. assert(_PyUnicode_CheckConsistency(retval, 1));
  303. return retval;
  304. }
  305. PyDoc_STRVAR(SHA1_update__doc__,
  306. "Update this hash object's state with the provided string.");
  307. static PyObject *
  308. SHA1_update(SHA1object *self, PyObject *args)
  309. {
  310. PyObject *obj;
  311. Py_buffer buf;
  312. if (!PyArg_ParseTuple(args, "O:update", &obj))
  313. return NULL;
  314. GET_BUFFER_VIEW_OR_ERROUT(obj, &buf);
  315. sha1_process(&self->hash_state, buf.buf, buf.len);
  316. PyBuffer_Release(&buf);
  317. Py_INCREF(Py_None);
  318. return Py_None;
  319. }
  320. static PyMethodDef SHA1_methods[] = {
  321. {"copy", (PyCFunction)SHA1_copy, METH_NOARGS, SHA1_copy__doc__},
  322. {"digest", (PyCFunction)SHA1_digest, METH_NOARGS, SHA1_digest__doc__},
  323. {"hexdigest", (PyCFunction)SHA1_hexdigest, METH_NOARGS, SHA1_hexdigest__doc__},
  324. {"update", (PyCFunction)SHA1_update, METH_VARARGS, SHA1_update__doc__},
  325. {NULL, NULL} /* sentinel */
  326. };
  327. static PyObject *
  328. SHA1_get_block_size(PyObject *self, void *closure)
  329. {
  330. return PyLong_FromLong(SHA1_BLOCKSIZE);
  331. }
  332. static PyObject *
  333. SHA1_get_name(PyObject *self, void *closure)
  334. {
  335. return PyUnicode_FromStringAndSize("SHA1", 3);
  336. }
  337. static PyObject *
  338. sha1_get_digest_size(PyObject *self, void *closure)
  339. {
  340. return PyLong_FromLong(SHA1_DIGESTSIZE);
  341. }
  342. static PyGetSetDef SHA1_getseters[] = {
  343. {"block_size",
  344. (getter)SHA1_get_block_size, NULL,
  345. NULL,
  346. NULL},
  347. {"name",
  348. (getter)SHA1_get_name, NULL,
  349. NULL,
  350. NULL},
  351. {"digest_size",
  352. (getter)sha1_get_digest_size, NULL,
  353. NULL,
  354. NULL},
  355. {NULL} /* Sentinel */
  356. };
  357. static PyTypeObject SHA1type = {
  358. PyVarObject_HEAD_INIT(NULL, 0)
  359. "_sha1.sha1", /*tp_name*/
  360. sizeof(SHA1object), /*tp_size*/
  361. 0, /*tp_itemsize*/
  362. /* methods */
  363. SHA1_dealloc, /*tp_dealloc*/
  364. 0, /*tp_print*/
  365. 0, /*tp_getattr*/
  366. 0, /*tp_setattr*/
  367. 0, /*tp_reserved*/
  368. 0, /*tp_repr*/
  369. 0, /*tp_as_number*/
  370. 0, /*tp_as_sequence*/
  371. 0, /*tp_as_mapping*/
  372. 0, /*tp_hash*/
  373. 0, /*tp_call*/
  374. 0, /*tp_str*/
  375. 0, /*tp_getattro*/
  376. 0, /*tp_setattro*/
  377. 0, /*tp_as_buffer*/
  378. Py_TPFLAGS_DEFAULT, /*tp_flags*/
  379. 0, /*tp_doc*/
  380. 0, /*tp_traverse*/
  381. 0, /*tp_clear*/
  382. 0, /*tp_richcompare*/
  383. 0, /*tp_weaklistoffset*/
  384. 0, /*tp_iter*/
  385. 0, /*tp_iternext*/
  386. SHA1_methods, /* tp_methods */
  387. NULL, /* tp_members */
  388. SHA1_getseters, /* tp_getset */
  389. };
  390. /* The single module-level function: new() */
  391. PyDoc_STRVAR(SHA1_new__doc__,
  392. "Return a new SHA1 hash object; optionally initialized with a string.");
  393. static PyObject *
  394. SHA1_new(PyObject *self, PyObject *args, PyObject *kwdict)
  395. {
  396. static char *kwlist[] = {"string", NULL};
  397. SHA1object *new;
  398. PyObject *data_obj = NULL;
  399. Py_buffer buf;
  400. if (!PyArg_ParseTupleAndKeywords(args, kwdict, "|O:new", kwlist,
  401. &data_obj)) {
  402. return NULL;
  403. }
  404. if (data_obj)
  405. GET_BUFFER_VIEW_OR_ERROUT(data_obj, &buf);
  406. if ((new = newSHA1object()) == NULL) {
  407. if (data_obj)
  408. PyBuffer_Release(&buf);
  409. return NULL;
  410. }
  411. sha1_init(&new->hash_state);
  412. if (PyErr_Occurred()) {
  413. Py_DECREF(new);
  414. if (data_obj)
  415. PyBuffer_Release(&buf);
  416. return NULL;
  417. }
  418. if (data_obj) {
  419. sha1_process(&new->hash_state, buf.buf, buf.len);
  420. PyBuffer_Release(&buf);
  421. }
  422. return (PyObject *)new;
  423. }
  424. /* List of functions exported by this module */
  425. static struct PyMethodDef SHA1_functions[] = {
  426. {"sha1",(PyCFunction)SHA1_new, METH_VARARGS|METH_KEYWORDS,SHA1_new__doc__},
  427. {NULL, NULL} /* Sentinel */
  428. };
  429. /* Initialize this module. */
  430. #define insint(n,v) { PyModule_AddIntConstant(m,n,v); }
  431. static struct PyModuleDef _sha1module = {
  432. PyModuleDef_HEAD_INIT,
  433. "_sha1",
  434. NULL,
  435. -1,
  436. SHA1_functions,
  437. NULL,
  438. NULL,
  439. NULL,
  440. NULL
  441. };
  442. PyMODINIT_FUNC
  443. PyInit__sha1(void)
  444. {
  445. Py_TYPE(&SHA1type) = &PyType_Type;
  446. if (PyType_Ready(&SHA1type) < 0)
  447. return NULL;
  448. return PyModule_Create(&_sha1module);
  449. }