blob: 01f1671a8f50565134b983456e9c73e9b6c24515 [file] [log] [blame]
Gregory P. Smithf21a5f72005-08-21 18:45:59 +00001/* Module that wraps all OpenSSL hash algorithms */
2
3/*
Benjamin Peterson46a99002010-01-09 18:45:30 +00004 * Copyright (C) 2005-2010 Gregory P. Smith (greg@krypto.org)
Gregory P. Smithf21a5f72005-08-21 18:45:59 +00005 * Licensed to PSF under a Contributor Agreement.
6 *
7 * Derived from a skeleton of shamodule.c containing work performed by:
8 *
9 * Andrew Kuchling (amk@amk.ca)
10 * Greg Stein (gstein@lyra.org)
11 *
12 */
13
Thomas Wouters9bc844e2006-03-01 21:50:07 +000014#define PY_SSIZE_T_CLEAN
15
Gregory P. Smithf21a5f72005-08-21 18:45:59 +000016#include "Python.h"
17#include "structmember.h"
Gregory P. Smith365a1862009-02-12 07:35:29 +000018#include "hashlib.h"
Gregory P. Smith4dff6f62015-04-25 23:42:38 +000019#include "pystrhex.h"
Gregory P. Smithf21a5f72005-08-21 18:45:59 +000020
Antoine Pitroubcd5cbe2009-01-08 21:17:16 +000021
Gregory P. Smith3f61d612009-05-04 00:45:33 +000022/* EVP is the preferred interface to hashing in OpenSSL */
23#include <openssl/evp.h>
Gregory P. Smith13b55292010-09-06 08:30:23 +000024/* We use the object interface to discover what hashes OpenSSL supports. */
25#include <openssl/objects.h>
Christian Heimese92ef132013-10-13 00:52:43 +020026#include "openssl/err.h"
Gregory P. Smith3f61d612009-05-04 00:45:33 +000027
Christian Heimes39093e92016-09-06 20:22:28 +020028#include "clinic/_hashopenssl.c.h"
29/*[clinic input]
30module _hashlib
31[clinic start generated code]*/
32/*[clinic end generated code: output=da39a3ee5e6b4b0d input=c2b4ff081bac4be1]*/
33
Gregory P. Smith3f61d612009-05-04 00:45:33 +000034#define MUNCH_SIZE INT_MAX
35
Gregory P. Smith3f61d612009-05-04 00:45:33 +000036#ifndef HASH_OBJ_CONSTRUCTOR
37#define HASH_OBJ_CONSTRUCTOR 0
38#endif
39
Christian Heimes598894f2016-09-05 23:19:05 +020040#if (OPENSSL_VERSION_NUMBER < 0x10100000L) || defined(LIBRESSL_VERSION_NUMBER)
41/* OpenSSL < 1.1.0 */
42#define EVP_MD_CTX_new EVP_MD_CTX_create
43#define EVP_MD_CTX_free EVP_MD_CTX_destroy
44#define HAS_FAST_PKCS5_PBKDF2_HMAC 0
45#include <openssl/hmac.h>
46#else
47/* OpenSSL >= 1.1.0 */
48#define HAS_FAST_PKCS5_PBKDF2_HMAC 1
49#endif
50
Gregory P. Smith3f61d612009-05-04 00:45:33 +000051
Gregory P. Smithf21a5f72005-08-21 18:45:59 +000052typedef struct {
53 PyObject_HEAD
54 PyObject *name; /* name of this hash algorithm */
Christian Heimes598894f2016-09-05 23:19:05 +020055 EVP_MD_CTX *ctx; /* OpenSSL message digest context */
Antoine Pitroubcd5cbe2009-01-08 21:17:16 +000056 PyThread_type_lock lock; /* OpenSSL context lock */
Gregory P. Smithf21a5f72005-08-21 18:45:59 +000057} EVPobject;
58
59
60static PyTypeObject EVPtype;
61
62
63#define DEFINE_CONSTS_FOR_NEW(Name) \
Gregory P. Smithaded2e52013-02-01 17:05:29 -080064 static PyObject *CONST_ ## Name ## _name_obj = NULL; \
Gregory P. Smithf21a5f72005-08-21 18:45:59 +000065 static EVP_MD_CTX *CONST_new_ ## Name ## _ctx_p = NULL;
66
Neal Norwitzf0459142006-01-07 21:20:24 +000067DEFINE_CONSTS_FOR_NEW(md5)
68DEFINE_CONSTS_FOR_NEW(sha1)
69DEFINE_CONSTS_FOR_NEW(sha224)
70DEFINE_CONSTS_FOR_NEW(sha256)
71DEFINE_CONSTS_FOR_NEW(sha384)
72DEFINE_CONSTS_FOR_NEW(sha512)
Gregory P. Smithf21a5f72005-08-21 18:45:59 +000073
74
Christian Heimes598894f2016-09-05 23:19:05 +020075/* LCOV_EXCL_START */
76static PyObject *
77_setException(PyObject *exc)
78{
79 unsigned long errcode;
80 const char *lib, *func, *reason;
81
82 errcode = ERR_peek_last_error();
83 if (!errcode) {
84 PyErr_SetString(exc, "unknown reasons");
85 return NULL;
86 }
87 ERR_clear_error();
88
89 lib = ERR_lib_error_string(errcode);
90 func = ERR_func_error_string(errcode);
91 reason = ERR_reason_error_string(errcode);
92
93 if (lib && func) {
94 PyErr_Format(exc, "[%s: %s] %s", lib, func, reason);
95 }
96 else if (lib) {
97 PyErr_Format(exc, "[%s] %s", lib, reason);
98 }
99 else {
100 PyErr_SetString(exc, reason);
101 }
102 return NULL;
103}
104/* LCOV_EXCL_STOP */
105
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000106static EVPobject *
107newEVPobject(PyObject *name)
108{
109 EVPobject *retval = (EVPobject *)PyObject_New(EVPobject, &EVPtype);
Christian Heimes598894f2016-09-05 23:19:05 +0200110 if (retval == NULL) {
111 return NULL;
112 }
113
114 retval->ctx = EVP_MD_CTX_new();
115 if (retval->ctx == NULL) {
116 PyErr_NoMemory();
117 return NULL;
118 }
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000119
120 /* save the name for .name to return */
Christian Heimes598894f2016-09-05 23:19:05 +0200121 Py_INCREF(name);
122 retval->name = name;
Christian Heimes598894f2016-09-05 23:19:05 +0200123 retval->lock = NULL;
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000124
125 return retval;
126}
127
Antoine Pitroubcd5cbe2009-01-08 21:17:16 +0000128static void
129EVP_hash(EVPobject *self, const void *vp, Py_ssize_t len)
130{
131 unsigned int process;
132 const unsigned char *cp = (const unsigned char *)vp;
133 while (0 < len) {
134 if (len > (Py_ssize_t)MUNCH_SIZE)
135 process = MUNCH_SIZE;
136 else
137 process = Py_SAFE_DOWNCAST(len, Py_ssize_t, unsigned int);
Gregory P. Smith07244a82017-05-24 00:04:38 -0700138 if (!EVP_DigestUpdate(self->ctx, (const void*)cp, process)) {
139 _setException(PyExc_ValueError);
140 break;
141 }
Antoine Pitroubcd5cbe2009-01-08 21:17:16 +0000142 len -= process;
143 cp += process;
144 }
145}
146
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000147/* Internal methods for a hash object */
148
149static void
Antoine Pitroubcd5cbe2009-01-08 21:17:16 +0000150EVP_dealloc(EVPobject *self)
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000151{
Antoine Pitroubcd5cbe2009-01-08 21:17:16 +0000152 if (self->lock != NULL)
153 PyThread_free_lock(self->lock);
Christian Heimes598894f2016-09-05 23:19:05 +0200154 EVP_MD_CTX_free(self->ctx);
Antoine Pitroubcd5cbe2009-01-08 21:17:16 +0000155 Py_XDECREF(self->name);
156 PyObject_Del(self);
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000157}
158
Christian Heimes598894f2016-09-05 23:19:05 +0200159static int
160locked_EVP_MD_CTX_copy(EVP_MD_CTX *new_ctx_p, EVPobject *self)
Gregory P. Smith3f61d612009-05-04 00:45:33 +0000161{
Christian Heimes598894f2016-09-05 23:19:05 +0200162 int result;
Gregory P. Smith3f61d612009-05-04 00:45:33 +0000163 ENTER_HASHLIB(self);
Christian Heimes598894f2016-09-05 23:19:05 +0200164 result = EVP_MD_CTX_copy(new_ctx_p, self->ctx);
Gregory P. Smith3f61d612009-05-04 00:45:33 +0000165 LEAVE_HASHLIB(self);
Christian Heimes598894f2016-09-05 23:19:05 +0200166 return result;
Gregory P. Smith3f61d612009-05-04 00:45:33 +0000167}
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000168
169/* External methods for a hash object */
170
171PyDoc_STRVAR(EVP_copy__doc__, "Return a copy of the hash object.");
172
Gregory P. Smith3f61d612009-05-04 00:45:33 +0000173
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000174static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000175EVP_copy(EVPobject *self, PyObject *unused)
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000176{
177 EVPobject *newobj;
178
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000179 if ( (newobj = newEVPobject(self->name))==NULL)
180 return NULL;
181
Christian Heimes598894f2016-09-05 23:19:05 +0200182 if (!locked_EVP_MD_CTX_copy(newobj->ctx, self)) {
183 return _setException(PyExc_ValueError);
184 }
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000185 return (PyObject *)newobj;
186}
187
188PyDoc_STRVAR(EVP_digest__doc__,
189"Return the digest value as a string of binary data.");
190
191static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000192EVP_digest(EVPobject *self, PyObject *unused)
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000193{
194 unsigned char digest[EVP_MAX_MD_SIZE];
Christian Heimes598894f2016-09-05 23:19:05 +0200195 EVP_MD_CTX *temp_ctx;
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000196 PyObject *retval;
197 unsigned int digest_size;
198
Christian Heimes598894f2016-09-05 23:19:05 +0200199 temp_ctx = EVP_MD_CTX_new();
200 if (temp_ctx == NULL) {
201 PyErr_NoMemory();
202 return NULL;
203 }
204
205 if (!locked_EVP_MD_CTX_copy(temp_ctx, self)) {
206 return _setException(PyExc_ValueError);
207 }
208 digest_size = EVP_MD_CTX_size(temp_ctx);
Gregory P. Smith07244a82017-05-24 00:04:38 -0700209 if (!EVP_DigestFinal(temp_ctx, digest, NULL)) {
210 _setException(PyExc_ValueError);
211 return NULL;
212 }
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000213
Christian Heimes72b710a2008-05-26 13:28:38 +0000214 retval = PyBytes_FromStringAndSize((const char *)digest, digest_size);
Christian Heimes598894f2016-09-05 23:19:05 +0200215 EVP_MD_CTX_free(temp_ctx);
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000216 return retval;
217}
218
219PyDoc_STRVAR(EVP_hexdigest__doc__,
220"Return the digest value as a string of hexadecimal digits.");
221
222static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000223EVP_hexdigest(EVPobject *self, PyObject *unused)
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000224{
225 unsigned char digest[EVP_MAX_MD_SIZE];
Christian Heimes598894f2016-09-05 23:19:05 +0200226 EVP_MD_CTX *temp_ctx;
Gregory P. Smith4dff6f62015-04-25 23:42:38 +0000227 unsigned int digest_size;
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000228
Christian Heimes598894f2016-09-05 23:19:05 +0200229 temp_ctx = EVP_MD_CTX_new();
230 if (temp_ctx == NULL) {
231 PyErr_NoMemory();
232 return NULL;
233 }
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000234
Christian Heimes598894f2016-09-05 23:19:05 +0200235 /* Get the raw (binary) digest value */
236 if (!locked_EVP_MD_CTX_copy(temp_ctx, self)) {
237 return _setException(PyExc_ValueError);
238 }
239 digest_size = EVP_MD_CTX_size(temp_ctx);
Gregory P. Smith07244a82017-05-24 00:04:38 -0700240 if (!EVP_DigestFinal(temp_ctx, digest, NULL)) {
241 _setException(PyExc_ValueError);
242 return NULL;
243 }
Christian Heimes598894f2016-09-05 23:19:05 +0200244
245 EVP_MD_CTX_free(temp_ctx);
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000246
Gregory P. Smith4dff6f62015-04-25 23:42:38 +0000247 return _Py_strhex((const char *)digest, digest_size);
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000248}
249
250PyDoc_STRVAR(EVP_update__doc__,
251"Update this hash object's state with the provided string.");
252
253static PyObject *
254EVP_update(EVPobject *self, PyObject *args)
255{
Gregory P. Smith9406f5c2007-08-26 02:58:36 +0000256 PyObject *obj;
Travis E. Oliphant8ae62b62007-09-23 02:00:13 +0000257 Py_buffer view;
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000258
Gregory P. Smith9406f5c2007-08-26 02:58:36 +0000259 if (!PyArg_ParseTuple(args, "O:update", &obj))
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000260 return NULL;
261
Gregory P. Smith365a1862009-02-12 07:35:29 +0000262 GET_BUFFER_VIEW_OR_ERROUT(obj, &view);
Antoine Pitroubcd5cbe2009-01-08 21:17:16 +0000263
Antoine Pitroubcd5cbe2009-01-08 21:17:16 +0000264 if (self->lock == NULL && view.len >= HASHLIB_GIL_MINSIZE) {
265 self->lock = PyThread_allocate_lock();
Gregory P. Smith3f61d612009-05-04 00:45:33 +0000266 /* fail? lock = NULL and we fail over to non-threaded code. */
Benjamin Peterson78cb4912008-09-24 22:53:33 +0000267 }
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000268
Antoine Pitroubcd5cbe2009-01-08 21:17:16 +0000269 if (self->lock != NULL) {
270 Py_BEGIN_ALLOW_THREADS
271 PyThread_acquire_lock(self->lock, 1);
272 EVP_hash(self, view.buf, view.len);
273 PyThread_release_lock(self->lock);
274 Py_END_ALLOW_THREADS
275 } else {
276 EVP_hash(self, view.buf, view.len);
277 }
Antoine Pitroubcd5cbe2009-01-08 21:17:16 +0000278
279 PyBuffer_Release(&view);
280 Py_RETURN_NONE;
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000281}
282
283static PyMethodDef EVP_methods[] = {
Antoine Pitroubcd5cbe2009-01-08 21:17:16 +0000284 {"update", (PyCFunction)EVP_update, METH_VARARGS, EVP_update__doc__},
285 {"digest", (PyCFunction)EVP_digest, METH_NOARGS, EVP_digest__doc__},
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000286 {"hexdigest", (PyCFunction)EVP_hexdigest, METH_NOARGS, EVP_hexdigest__doc__},
Antoine Pitroubcd5cbe2009-01-08 21:17:16 +0000287 {"copy", (PyCFunction)EVP_copy, METH_NOARGS, EVP_copy__doc__},
288 {NULL, NULL} /* sentinel */
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000289};
290
291static PyObject *
292EVP_get_block_size(EVPobject *self, void *closure)
293{
Antoine Pitroubcd5cbe2009-01-08 21:17:16 +0000294 long block_size;
Christian Heimes598894f2016-09-05 23:19:05 +0200295 block_size = EVP_MD_CTX_block_size(self->ctx);
Antoine Pitroubcd5cbe2009-01-08 21:17:16 +0000296 return PyLong_FromLong(block_size);
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000297}
298
299static PyObject *
300EVP_get_digest_size(EVPobject *self, void *closure)
301{
Antoine Pitroubcd5cbe2009-01-08 21:17:16 +0000302 long size;
Christian Heimes598894f2016-09-05 23:19:05 +0200303 size = EVP_MD_CTX_size(self->ctx);
Antoine Pitroubcd5cbe2009-01-08 21:17:16 +0000304 return PyLong_FromLong(size);
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000305}
306
307static PyMemberDef EVP_members[] = {
308 {"name", T_OBJECT, offsetof(EVPobject, name), READONLY, PyDoc_STR("algorithm name.")},
309 {NULL} /* Sentinel */
310};
311
312static PyGetSetDef EVP_getseters[] = {
313 {"digest_size",
314 (getter)EVP_get_digest_size, NULL,
315 NULL,
316 NULL},
317 {"block_size",
318 (getter)EVP_get_block_size, NULL,
319 NULL,
320 NULL},
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000321 {NULL} /* Sentinel */
322};
323
324
325static PyObject *
Antoine Pitroubcd5cbe2009-01-08 21:17:16 +0000326EVP_repr(EVPobject *self)
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000327{
Victor Stinner3f1af5c2010-03-12 17:00:41 +0000328 return PyUnicode_FromFormat("<%U HASH object @ %p>", self->name, self);
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000329}
330
331#if HASH_OBJ_CONSTRUCTOR
332static int
333EVP_tp_init(EVPobject *self, PyObject *args, PyObject *kwds)
334{
Martin v. Löwis15e62742006-02-27 16:46:16 +0000335 static char *kwlist[] = {"name", "string", NULL};
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000336 PyObject *name_obj = NULL;
Gregory P. Smith9406f5c2007-08-26 02:58:36 +0000337 PyObject *data_obj = NULL;
Travis E. Oliphant8ae62b62007-09-23 02:00:13 +0000338 Py_buffer view;
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000339 char *nameStr;
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000340 const EVP_MD *digest;
341
Gregory P. Smith9406f5c2007-08-26 02:58:36 +0000342 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:HASH", kwlist,
343 &name_obj, &data_obj)) {
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000344 return -1;
345 }
346
Gregory P. Smith9406f5c2007-08-26 02:58:36 +0000347 if (data_obj)
Gregory P. Smith365a1862009-02-12 07:35:29 +0000348 GET_BUFFER_VIEW_OR_ERROUT(data_obj, &view);
Gregory P. Smith9406f5c2007-08-26 02:58:36 +0000349
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000350 if (!PyArg_Parse(name_obj, "s", &nameStr)) {
351 PyErr_SetString(PyExc_TypeError, "name must be a string");
Gregory P. Smith9406f5c2007-08-26 02:58:36 +0000352 if (data_obj)
Martin v. Löwis423be952008-08-13 15:53:07 +0000353 PyBuffer_Release(&view);
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000354 return -1;
355 }
356
357 digest = EVP_get_digestbyname(nameStr);
358 if (!digest) {
359 PyErr_SetString(PyExc_ValueError, "unknown hash function");
Gregory P. Smith9406f5c2007-08-26 02:58:36 +0000360 if (data_obj)
Martin v. Löwis423be952008-08-13 15:53:07 +0000361 PyBuffer_Release(&view);
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000362 return -1;
363 }
Gregory P. Smith07244a82017-05-24 00:04:38 -0700364 if (!EVP_DigestInit(self->ctx, digest)) {
365 _setException(PyExc_ValueError);
366 if (data_obj)
367 PyBuffer_Release(&view);
368 return -1;
369 }
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000370
371 self->name = name_obj;
372 Py_INCREF(self->name);
373
Gregory P. Smith9406f5c2007-08-26 02:58:36 +0000374 if (data_obj) {
Antoine Pitroubcd5cbe2009-01-08 21:17:16 +0000375 if (view.len >= HASHLIB_GIL_MINSIZE) {
376 Py_BEGIN_ALLOW_THREADS
377 EVP_hash(self, view.buf, view.len);
378 Py_END_ALLOW_THREADS
Benjamin Peterson78cb4912008-09-24 22:53:33 +0000379 } else {
Antoine Pitroubcd5cbe2009-01-08 21:17:16 +0000380 EVP_hash(self, view.buf, view.len);
Benjamin Peterson78cb4912008-09-24 22:53:33 +0000381 }
Martin v. Löwis423be952008-08-13 15:53:07 +0000382 PyBuffer_Release(&view);
Gregory P. Smith9406f5c2007-08-26 02:58:36 +0000383 }
Antoine Pitroubcd5cbe2009-01-08 21:17:16 +0000384
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000385 return 0;
386}
387#endif
388
389
390PyDoc_STRVAR(hashtype_doc,
391"A hash represents the object used to calculate a checksum of a\n\
392string of information.\n\
393\n\
394Methods:\n\
395\n\
396update() -- updates the current digest with an additional string\n\
397digest() -- return the current digest value\n\
398hexdigest() -- return the current digest as a string of hexadecimal digits\n\
399copy() -- return a copy of the current hash object\n\
400\n\
401Attributes:\n\
402\n\
403name -- the hash algorithm being used by this object\n\
404digest_size -- number of bytes in this hashes output\n");
405
406static PyTypeObject EVPtype = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000407 PyVarObject_HEAD_INIT(NULL, 0)
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000408 "_hashlib.HASH", /*tp_name*/
Antoine Pitroubcd5cbe2009-01-08 21:17:16 +0000409 sizeof(EVPobject), /*tp_basicsize*/
410 0, /*tp_itemsize*/
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000411 /* methods */
Antoine Pitroubcd5cbe2009-01-08 21:17:16 +0000412 (destructor)EVP_dealloc, /*tp_dealloc*/
413 0, /*tp_print*/
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000414 0, /*tp_getattr*/
415 0, /*tp_setattr*/
Mark Dickinsone94c6792009-02-02 20:36:42 +0000416 0, /*tp_reserved*/
Antoine Pitroubcd5cbe2009-01-08 21:17:16 +0000417 (reprfunc)EVP_repr, /*tp_repr*/
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000418 0, /*tp_as_number*/
419 0, /*tp_as_sequence*/
420 0, /*tp_as_mapping*/
421 0, /*tp_hash*/
422 0, /*tp_call*/
423 0, /*tp_str*/
424 0, /*tp_getattro*/
425 0, /*tp_setattro*/
426 0, /*tp_as_buffer*/
427 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
428 hashtype_doc, /*tp_doc*/
429 0, /*tp_traverse*/
Antoine Pitroubcd5cbe2009-01-08 21:17:16 +0000430 0, /*tp_clear*/
431 0, /*tp_richcompare*/
432 0, /*tp_weaklistoffset*/
433 0, /*tp_iter*/
434 0, /*tp_iternext*/
435 EVP_methods, /* tp_methods */
436 EVP_members, /* tp_members */
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000437 EVP_getseters, /* tp_getset */
438#if 1
439 0, /* tp_base */
440 0, /* tp_dict */
441 0, /* tp_descr_get */
442 0, /* tp_descr_set */
443 0, /* tp_dictoffset */
444#endif
445#if HASH_OBJ_CONSTRUCTOR
446 (initproc)EVP_tp_init, /* tp_init */
447#endif
448};
449
450static PyObject *
451EVPnew(PyObject *name_obj,
452 const EVP_MD *digest, const EVP_MD_CTX *initial_ctx,
Benjamin Peterson78cb4912008-09-24 22:53:33 +0000453 const unsigned char *cp, Py_ssize_t len)
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000454{
455 EVPobject *self;
456
457 if (!digest && !initial_ctx) {
458 PyErr_SetString(PyExc_ValueError, "unsupported hash type");
459 return NULL;
460 }
461
462 if ((self = newEVPobject(name_obj)) == NULL)
463 return NULL;
464
465 if (initial_ctx) {
Christian Heimes598894f2016-09-05 23:19:05 +0200466 EVP_MD_CTX_copy(self->ctx, initial_ctx);
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000467 } else {
Gregory P. Smith07244a82017-05-24 00:04:38 -0700468 if (!EVP_DigestInit(self->ctx, digest)) {
469 _setException(PyExc_ValueError);
470 Py_DECREF(self);
471 return NULL;
472 }
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000473 }
474
Benjamin Peterson78cb4912008-09-24 22:53:33 +0000475 if (cp && len) {
Antoine Pitroubcd5cbe2009-01-08 21:17:16 +0000476 if (len >= HASHLIB_GIL_MINSIZE) {
477 Py_BEGIN_ALLOW_THREADS
478 EVP_hash(self, cp, len);
479 Py_END_ALLOW_THREADS
Benjamin Peterson78cb4912008-09-24 22:53:33 +0000480 } else {
Antoine Pitroubcd5cbe2009-01-08 21:17:16 +0000481 EVP_hash(self, cp, len);
Benjamin Peterson78cb4912008-09-24 22:53:33 +0000482 }
483 }
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000484
485 return (PyObject *)self;
486}
487
488
489/* The module-level function: new() */
490
491PyDoc_STRVAR(EVP_new__doc__,
492"Return a new hash object using the named algorithm.\n\
493An optional string argument may be provided and will be\n\
494automatically hashed.\n\
495\n\
496The MD5 and SHA1 algorithms are always supported.\n");
497
498static PyObject *
499EVP_new(PyObject *self, PyObject *args, PyObject *kwdict)
500{
Martin v. Löwis15e62742006-02-27 16:46:16 +0000501 static char *kwlist[] = {"name", "string", NULL};
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000502 PyObject *name_obj = NULL;
Gregory P. Smith9406f5c2007-08-26 02:58:36 +0000503 PyObject *data_obj = NULL;
Travis E. Oliphant8ae62b62007-09-23 02:00:13 +0000504 Py_buffer view = { 0 };
Gregory P. Smith9406f5c2007-08-26 02:58:36 +0000505 PyObject *ret_obj;
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000506 char *name;
507 const EVP_MD *digest;
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000508
Gregory P. Smith9406f5c2007-08-26 02:58:36 +0000509 if (!PyArg_ParseTupleAndKeywords(args, kwdict, "O|O:new", kwlist,
510 &name_obj, &data_obj)) {
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000511 return NULL;
512 }
513
514 if (!PyArg_Parse(name_obj, "s", &name)) {
515 PyErr_SetString(PyExc_TypeError, "name must be a string");
516 return NULL;
517 }
518
Gregory P. Smith9406f5c2007-08-26 02:58:36 +0000519 if (data_obj)
Gregory P. Smith365a1862009-02-12 07:35:29 +0000520 GET_BUFFER_VIEW_OR_ERROUT(data_obj, &view);
Gregory P. Smith9406f5c2007-08-26 02:58:36 +0000521
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000522 digest = EVP_get_digestbyname(name);
523
Benjamin Peterson78cb4912008-09-24 22:53:33 +0000524 ret_obj = EVPnew(name_obj, digest, NULL, (unsigned char*)view.buf, view.len);
Gregory P. Smith9406f5c2007-08-26 02:58:36 +0000525
526 if (data_obj)
Martin v. Löwis423be952008-08-13 15:53:07 +0000527 PyBuffer_Release(&view);
Gregory P. Smith9406f5c2007-08-26 02:58:36 +0000528 return ret_obj;
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000529}
530
Christian Heimese7236222013-10-19 14:24:44 +0200531
532
Christian Heimes351f5392013-10-19 17:59:48 +0200533#if (OPENSSL_VERSION_NUMBER >= 0x10000000 && !defined(OPENSSL_NO_HMAC) \
534 && !defined(OPENSSL_NO_SHA))
Christian Heimese7236222013-10-19 14:24:44 +0200535
Christian Heimese92ef132013-10-13 00:52:43 +0200536#define PY_PBKDF2_HMAC 1
537
Christian Heimes598894f2016-09-05 23:19:05 +0200538#if !HAS_FAST_PKCS5_PBKDF2_HMAC
Christian Heimese7236222013-10-19 14:24:44 +0200539/* Improved implementation of PKCS5_PBKDF2_HMAC()
540 *
541 * PKCS5_PBKDF2_HMAC_fast() hashes the password exactly one time instead of
542 * `iter` times. Today (2013) the iteration count is typically 100,000 or
543 * more. The improved algorithm is not subject to a Denial-of-Service
544 * vulnerability with overly large passwords.
545 *
546 * Also OpenSSL < 1.0 don't provide PKCS5_PBKDF2_HMAC(), only
547 * PKCS5_PBKDF2_SHA1.
548 */
Christian Heimesc6564b92013-10-20 13:23:03 +0200549static int
550PKCS5_PBKDF2_HMAC_fast(const char *pass, int passlen,
551 const unsigned char *salt, int saltlen,
552 int iter, const EVP_MD *digest,
553 int keylen, unsigned char *out)
Christian Heimese7236222013-10-19 14:24:44 +0200554{
555 unsigned char digtmp[EVP_MAX_MD_SIZE], *p, itmp[4];
556 int cplen, j, k, tkeylen, mdlen;
557 unsigned long i = 1;
558 HMAC_CTX hctx_tpl, hctx;
559
560 mdlen = EVP_MD_size(digest);
561 if (mdlen < 0)
562 return 0;
563
564 HMAC_CTX_init(&hctx_tpl);
565 HMAC_CTX_init(&hctx);
566 p = out;
567 tkeylen = keylen;
Christian Heimese7236222013-10-19 14:24:44 +0200568 if (!HMAC_Init_ex(&hctx_tpl, pass, passlen, digest, NULL)) {
569 HMAC_CTX_cleanup(&hctx_tpl);
570 return 0;
571 }
Benjamin Peterson3c0769d2015-09-27 02:13:40 -0700572 while (tkeylen) {
573 if (tkeylen > mdlen)
Christian Heimese7236222013-10-19 14:24:44 +0200574 cplen = mdlen;
575 else
576 cplen = tkeylen;
577 /* We are unlikely to ever use more than 256 blocks (5120 bits!)
578 * but just in case...
579 */
580 itmp[0] = (unsigned char)((i >> 24) & 0xff);
581 itmp[1] = (unsigned char)((i >> 16) & 0xff);
582 itmp[2] = (unsigned char)((i >> 8) & 0xff);
583 itmp[3] = (unsigned char)(i & 0xff);
584 if (!HMAC_CTX_copy(&hctx, &hctx_tpl)) {
585 HMAC_CTX_cleanup(&hctx_tpl);
586 return 0;
587 }
588 if (!HMAC_Update(&hctx, salt, saltlen)
589 || !HMAC_Update(&hctx, itmp, 4)
590 || !HMAC_Final(&hctx, digtmp, NULL)) {
591 HMAC_CTX_cleanup(&hctx_tpl);
592 HMAC_CTX_cleanup(&hctx);
593 return 0;
594 }
Christian Heimes68531082013-11-06 17:25:17 +0100595 HMAC_CTX_cleanup(&hctx);
Christian Heimese7236222013-10-19 14:24:44 +0200596 memcpy(p, digtmp, cplen);
597 for (j = 1; j < iter; j++) {
598 if (!HMAC_CTX_copy(&hctx, &hctx_tpl)) {
599 HMAC_CTX_cleanup(&hctx_tpl);
600 return 0;
601 }
602 if (!HMAC_Update(&hctx, digtmp, mdlen)
603 || !HMAC_Final(&hctx, digtmp, NULL)) {
604 HMAC_CTX_cleanup(&hctx_tpl);
605 HMAC_CTX_cleanup(&hctx);
606 return 0;
607 }
608 HMAC_CTX_cleanup(&hctx);
609 for (k = 0; k < cplen; k++) {
610 p[k] ^= digtmp[k];
611 }
612 }
613 tkeylen-= cplen;
614 i++;
615 p+= cplen;
616 }
617 HMAC_CTX_cleanup(&hctx_tpl);
618 return 1;
619}
Christian Heimes598894f2016-09-05 23:19:05 +0200620#endif
Christian Heimese7236222013-10-19 14:24:44 +0200621
622
Christian Heimese92ef132013-10-13 00:52:43 +0200623PyDoc_STRVAR(pbkdf2_hmac__doc__,
624"pbkdf2_hmac(hash_name, password, salt, iterations, dklen=None) -> key\n\
625\n\
626Password based key derivation function 2 (PKCS #5 v2.0) with HMAC as\n\
627pseudorandom function.");
628
629static PyObject *
630pbkdf2_hmac(PyObject *self, PyObject *args, PyObject *kwdict)
631{
632 static char *kwlist[] = {"hash_name", "password", "salt", "iterations",
633 "dklen", NULL};
634 PyObject *key_obj = NULL, *dklen_obj = Py_None;
635 char *name, *key;
636 Py_buffer password, salt;
637 long iterations, dklen;
638 int retval;
639 const EVP_MD *digest;
640
641 if (!PyArg_ParseTupleAndKeywords(args, kwdict, "sy*y*l|O:pbkdf2_hmac",
642 kwlist, &name, &password, &salt,
643 &iterations, &dklen_obj)) {
644 return NULL;
645 }
646
647 digest = EVP_get_digestbyname(name);
648 if (digest == NULL) {
649 PyErr_SetString(PyExc_ValueError, "unsupported hash type");
650 goto end;
651 }
652
653 if (password.len > INT_MAX) {
654 PyErr_SetString(PyExc_OverflowError,
655 "password is too long.");
656 goto end;
657 }
658
659 if (salt.len > INT_MAX) {
660 PyErr_SetString(PyExc_OverflowError,
661 "salt is too long.");
662 goto end;
663 }
664
665 if (iterations < 1) {
666 PyErr_SetString(PyExc_ValueError,
667 "iteration value must be greater than 0.");
668 goto end;
669 }
670 if (iterations > INT_MAX) {
671 PyErr_SetString(PyExc_OverflowError,
672 "iteration value is too great.");
673 goto end;
674 }
675
676 if (dklen_obj == Py_None) {
677 dklen = EVP_MD_size(digest);
678 } else {
679 dklen = PyLong_AsLong(dklen_obj);
680 if ((dklen == -1) && PyErr_Occurred()) {
681 goto end;
682 }
683 }
684 if (dklen < 1) {
685 PyErr_SetString(PyExc_ValueError,
686 "key length must be greater than 0.");
687 goto end;
688 }
689 if (dklen > INT_MAX) {
690 /* INT_MAX is always smaller than dkLen max (2^32 - 1) * hLen */
691 PyErr_SetString(PyExc_OverflowError,
692 "key length is too great.");
693 goto end;
694 }
695
696 key_obj = PyBytes_FromStringAndSize(NULL, dklen);
697 if (key_obj == NULL) {
698 goto end;
699 }
700 key = PyBytes_AS_STRING(key_obj);
701
702 Py_BEGIN_ALLOW_THREADS
Christian Heimes598894f2016-09-05 23:19:05 +0200703#if HAS_FAST_PKCS5_PBKDF2_HMAC
704 retval = PKCS5_PBKDF2_HMAC((char*)password.buf, (int)password.len,
705 (unsigned char *)salt.buf, (int)salt.len,
706 iterations, digest, dklen,
707 (unsigned char *)key);
708#else
Victor Stinnerc1a57d32013-11-16 00:27:16 +0100709 retval = PKCS5_PBKDF2_HMAC_fast((char*)password.buf, (int)password.len,
Christian Heimescc6cdce2013-11-18 09:59:44 +0100710 (unsigned char *)salt.buf, (int)salt.len,
Christian Heimese7236222013-10-19 14:24:44 +0200711 iterations, digest, dklen,
712 (unsigned char *)key);
Christian Heimes598894f2016-09-05 23:19:05 +0200713#endif
Christian Heimese92ef132013-10-13 00:52:43 +0200714 Py_END_ALLOW_THREADS
715
716 if (!retval) {
717 Py_CLEAR(key_obj);
718 _setException(PyExc_ValueError);
719 goto end;
720 }
721
722 end:
723 PyBuffer_Release(&password);
724 PyBuffer_Release(&salt);
725 return key_obj;
726}
727
728#endif
Gregory P. Smith13b55292010-09-06 08:30:23 +0000729
Christian Heimes39093e92016-09-06 20:22:28 +0200730#if OPENSSL_VERSION_NUMBER > 0x10100000L && !defined(OPENSSL_NO_SCRYPT) && !defined(LIBRESSL_VERSION_NUMBER)
731#define PY_SCRYPT 1
732
733/*[clinic input]
734_hashlib.scrypt
735
736 password: Py_buffer
737 *
738 salt: Py_buffer = None
739 n as n_obj: object(subclass_of='&PyLong_Type') = None
740 r as r_obj: object(subclass_of='&PyLong_Type') = None
741 p as p_obj: object(subclass_of='&PyLong_Type') = None
742 maxmem: long = 0
743 dklen: long = 64
744
745
746scrypt password-based key derivation function.
747[clinic start generated code]*/
748
749static PyObject *
750_hashlib_scrypt_impl(PyObject *module, Py_buffer *password, Py_buffer *salt,
751 PyObject *n_obj, PyObject *r_obj, PyObject *p_obj,
752 long maxmem, long dklen)
753/*[clinic end generated code: output=14849e2aa2b7b46c input=48a7d63bf3f75c42]*/
754{
755 PyObject *key_obj = NULL;
756 char *key;
757 int retval;
758 unsigned long n, r, p;
759
760 if (password->len > INT_MAX) {
761 PyErr_SetString(PyExc_OverflowError,
762 "password is too long.");
763 return NULL;
764 }
765
766 if (salt->buf == NULL) {
767 PyErr_SetString(PyExc_TypeError,
768 "salt is required");
769 return NULL;
770 }
771 if (salt->len > INT_MAX) {
772 PyErr_SetString(PyExc_OverflowError,
773 "salt is too long.");
774 return NULL;
775 }
776
777 n = PyLong_AsUnsignedLong(n_obj);
778 if (n == (unsigned long) -1 && PyErr_Occurred()) {
779 PyErr_SetString(PyExc_TypeError,
780 "n is required and must be an unsigned int");
781 return NULL;
782 }
783 if (n < 2 || n & (n - 1)) {
784 PyErr_SetString(PyExc_ValueError,
785 "n must be a power of 2.");
786 return NULL;
787 }
788
789 r = PyLong_AsUnsignedLong(r_obj);
790 if (r == (unsigned long) -1 && PyErr_Occurred()) {
791 PyErr_SetString(PyExc_TypeError,
792 "r is required and must be an unsigned int");
793 return NULL;
794 }
795
796 p = PyLong_AsUnsignedLong(p_obj);
797 if (p == (unsigned long) -1 && PyErr_Occurred()) {
798 PyErr_SetString(PyExc_TypeError,
799 "p is required and must be an unsigned int");
800 return NULL;
801 }
802
803 if (maxmem < 0 || maxmem > INT_MAX) {
804 /* OpenSSL 1.1.0 restricts maxmem to 32MB. It may change in the
805 future. The maxmem constant is private to OpenSSL. */
806 PyErr_Format(PyExc_ValueError,
807 "maxmem must be positive and smaller than %d",
808 INT_MAX);
809 return NULL;
810 }
811
812 if (dklen < 1 || dklen > INT_MAX) {
813 PyErr_Format(PyExc_ValueError,
814 "dklen must be greater than 0 and smaller than %d",
815 INT_MAX);
816 return NULL;
817 }
818
819 /* let OpenSSL validate the rest */
820 retval = EVP_PBE_scrypt(NULL, 0, NULL, 0, n, r, p, maxmem, NULL, 0);
821 if (!retval) {
822 /* sorry, can't do much better */
823 PyErr_SetString(PyExc_ValueError,
824 "Invalid paramemter combination for n, r, p, maxmem.");
825 return NULL;
826 }
827
828 key_obj = PyBytes_FromStringAndSize(NULL, dklen);
829 if (key_obj == NULL) {
830 return NULL;
831 }
832 key = PyBytes_AS_STRING(key_obj);
833
834 Py_BEGIN_ALLOW_THREADS
835 retval = EVP_PBE_scrypt(
836 (const char*)password->buf, (size_t)password->len,
837 (const unsigned char *)salt->buf, (size_t)salt->len,
838 n, r, p, maxmem,
839 (unsigned char *)key, (size_t)dklen
840 );
841 Py_END_ALLOW_THREADS
842
843 if (!retval) {
844 Py_CLEAR(key_obj);
845 _setException(PyExc_ValueError);
846 return NULL;
847 }
848 return key_obj;
849}
850#endif
851
Gregory P. Smith13b55292010-09-06 08:30:23 +0000852/* State for our callback function so that it can accumulate a result. */
853typedef struct _internal_name_mapper_state {
854 PyObject *set;
855 int error;
856} _InternalNameMapperState;
857
858
859/* A callback function to pass to OpenSSL's OBJ_NAME_do_all(...) */
860static void
861_openssl_hash_name_mapper(const OBJ_NAME *openssl_obj_name, void *arg)
862{
863 _InternalNameMapperState *state = (_InternalNameMapperState *)arg;
864 PyObject *py_name;
865
866 assert(state != NULL);
867 if (openssl_obj_name == NULL)
868 return;
869 /* Ignore aliased names, they pollute the list and OpenSSL appears to
Martin Panter7462b6492015-11-02 03:37:02 +0000870 * have its own definition of alias as the resulting list still
Gregory P. Smith13b55292010-09-06 08:30:23 +0000871 * contains duplicate and alternate names for several algorithms. */
872 if (openssl_obj_name->alias)
873 return;
874
875 py_name = PyUnicode_FromString(openssl_obj_name->name);
876 if (py_name == NULL) {
877 state->error = 1;
878 } else {
879 if (PySet_Add(state->set, py_name) != 0) {
Gregory P. Smith13b55292010-09-06 08:30:23 +0000880 state->error = 1;
881 }
Christian Heimesdb816d62013-10-29 12:14:55 +0100882 Py_DECREF(py_name);
Gregory P. Smith13b55292010-09-06 08:30:23 +0000883 }
884}
885
886
887/* Ask OpenSSL for a list of supported ciphers, filling in a Python set. */
888static PyObject*
889generate_hash_name_list(void)
890{
891 _InternalNameMapperState state;
892 state.set = PyFrozenSet_New(NULL);
893 if (state.set == NULL)
894 return NULL;
895 state.error = 0;
896
897 OBJ_NAME_do_all(OBJ_NAME_TYPE_MD_METH, &_openssl_hash_name_mapper, &state);
898
899 if (state.error) {
900 Py_DECREF(state.set);
901 return NULL;
902 }
903 return state.set;
904}
905
906
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000907/*
908 * This macro generates constructor function definitions for specific
909 * hash algorithms. These constructors are much faster than calling
Raymond Hettinger15f44ab2016-08-30 10:47:49 -0700910 * the generic one passing it a python string and are noticeably
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000911 * faster than calling a python new() wrapper. Thats important for
912 * code that wants to make hashes of a bunch of small strings.
Gregory P. Smith07244a82017-05-24 00:04:38 -0700913 * The first call will lazy-initialize, which reports an exception
914 * if initialization fails.
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000915 */
916#define GEN_CONSTRUCTOR(NAME) \
917 static PyObject * \
Serhiy Storchaka7e601922017-07-10 11:25:34 +0300918 EVP_new_ ## NAME (PyObject *self, PyObject **args, Py_ssize_t nargs) \
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000919 { \
Gregory P. Smith9406f5c2007-08-26 02:58:36 +0000920 PyObject *data_obj = NULL; \
Travis E. Oliphant8ae62b62007-09-23 02:00:13 +0000921 Py_buffer view = { 0 }; \
Gregory P. Smith9406f5c2007-08-26 02:58:36 +0000922 PyObject *ret_obj; \
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000923 \
Sylvain96c7c062017-06-15 17:05:23 +0200924 if (!_PyArg_ParseStack(args, nargs, "|O:" #NAME , &data_obj)) { \
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000925 return NULL; \
926 } \
927 \
Gregory P. Smith07244a82017-05-24 00:04:38 -0700928 if (CONST_new_ ## NAME ## _ctx_p == NULL) { \
929 EVP_MD_CTX *ctx_p = EVP_MD_CTX_new(); \
930 if (!EVP_get_digestbyname(#NAME) || \
931 !EVP_DigestInit(ctx_p, EVP_get_digestbyname(#NAME))) { \
932 _setException(PyExc_ValueError); \
933 EVP_MD_CTX_free(ctx_p); \
934 return NULL; \
935 } \
936 CONST_new_ ## NAME ## _ctx_p = ctx_p; \
937 } \
938 \
Gregory P. Smith9406f5c2007-08-26 02:58:36 +0000939 if (data_obj) \
Gregory P. Smith365a1862009-02-12 07:35:29 +0000940 GET_BUFFER_VIEW_OR_ERROUT(data_obj, &view); \
Gregory P. Smith9406f5c2007-08-26 02:58:36 +0000941 \
942 ret_obj = EVPnew( \
943 CONST_ ## NAME ## _name_obj, \
944 NULL, \
945 CONST_new_ ## NAME ## _ctx_p, \
946 (unsigned char*)view.buf, \
Benjamin Peterson78cb4912008-09-24 22:53:33 +0000947 view.len); \
Gregory P. Smith9406f5c2007-08-26 02:58:36 +0000948 \
949 if (data_obj) \
Martin v. Löwis423be952008-08-13 15:53:07 +0000950 PyBuffer_Release(&view); \
Gregory P. Smith9406f5c2007-08-26 02:58:36 +0000951 return ret_obj; \
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000952 }
953
954/* a PyMethodDef structure for the constructor */
955#define CONSTRUCTOR_METH_DEF(NAME) \
Serhiy Storchaka7e601922017-07-10 11:25:34 +0300956 {"openssl_" #NAME, (PyCFunction)EVP_new_ ## NAME, METH_FASTCALL, \
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000957 PyDoc_STR("Returns a " #NAME \
958 " hash object; optionally initialized with a string") \
959 }
960
Gregory P. Smithaded2e52013-02-01 17:05:29 -0800961/* used in the init function to setup a constructor: initialize OpenSSL
962 constructor constants if they haven't been initialized already. */
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000963#define INIT_CONSTRUCTOR_CONSTANTS(NAME) do { \
Gregory P. Smithaded2e52013-02-01 17:05:29 -0800964 if (CONST_ ## NAME ## _name_obj == NULL) { \
965 CONST_ ## NAME ## _name_obj = PyUnicode_FromString(#NAME); \
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000966 } \
967} while (0);
968
969GEN_CONSTRUCTOR(md5)
970GEN_CONSTRUCTOR(sha1)
971GEN_CONSTRUCTOR(sha224)
972GEN_CONSTRUCTOR(sha256)
973GEN_CONSTRUCTOR(sha384)
974GEN_CONSTRUCTOR(sha512)
975
976/* List of functions exported by this module */
977
978static struct PyMethodDef EVP_functions[] = {
979 {"new", (PyCFunction)EVP_new, METH_VARARGS|METH_KEYWORDS, EVP_new__doc__},
Christian Heimese92ef132013-10-13 00:52:43 +0200980#ifdef PY_PBKDF2_HMAC
981 {"pbkdf2_hmac", (PyCFunction)pbkdf2_hmac, METH_VARARGS|METH_KEYWORDS,
982 pbkdf2_hmac__doc__},
983#endif
Christian Heimes39093e92016-09-06 20:22:28 +0200984 _HASHLIB_SCRYPT_METHODDEF
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000985 CONSTRUCTOR_METH_DEF(md5),
986 CONSTRUCTOR_METH_DEF(sha1),
987 CONSTRUCTOR_METH_DEF(sha224),
988 CONSTRUCTOR_METH_DEF(sha256),
989 CONSTRUCTOR_METH_DEF(sha384),
990 CONSTRUCTOR_METH_DEF(sha512),
Alexander Belopolskyf0f45142010-08-11 17:31:17 +0000991 {NULL, NULL} /* Sentinel */
Gregory P. Smithf21a5f72005-08-21 18:45:59 +0000992};
993
994
995/* Initialize this module. */
996
Martin v. Löwis1a214512008-06-11 05:26:20 +0000997
998static struct PyModuleDef _hashlibmodule = {
Antoine Pitroubcd5cbe2009-01-08 21:17:16 +0000999 PyModuleDef_HEAD_INIT,
1000 "_hashlib",
1001 NULL,
1002 -1,
1003 EVP_functions,
1004 NULL,
1005 NULL,
1006 NULL,
1007 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00001008};
1009
Gregory P. Smithf21a5f72005-08-21 18:45:59 +00001010PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00001011PyInit__hashlib(void)
Gregory P. Smithf21a5f72005-08-21 18:45:59 +00001012{
Gregory P. Smith13b55292010-09-06 08:30:23 +00001013 PyObject *m, *openssl_md_meth_names;
Gregory P. Smithf21a5f72005-08-21 18:45:59 +00001014
Christian Heimesc941e622017-09-05 15:47:11 +02001015#ifndef OPENSSL_VERSION_1_1
1016 /* Load all digest algorithms and initialize cpuid */
1017 OPENSSL_add_all_algorithms_noconf();
Christian Heimesb7ddbc82013-10-21 19:48:22 +02001018 ERR_load_crypto_strings();
Christian Heimesc941e622017-09-05 15:47:11 +02001019#endif
Gregory P. Smithf21a5f72005-08-21 18:45:59 +00001020
1021 /* TODO build EVP_functions openssl_* entries dynamically based
1022 * on what hashes are supported rather than listing many
1023 * but having some be unsupported. Only init appropriate
1024 * constants. */
1025
Christian Heimes90aa7642007-12-19 02:45:37 +00001026 Py_TYPE(&EVPtype) = &PyType_Type;
Gregory P. Smithf21a5f72005-08-21 18:45:59 +00001027 if (PyType_Ready(&EVPtype) < 0)
Martin v. Löwis1a214512008-06-11 05:26:20 +00001028 return NULL;
Gregory P. Smithf21a5f72005-08-21 18:45:59 +00001029
Martin v. Löwis1a214512008-06-11 05:26:20 +00001030 m = PyModule_Create(&_hashlibmodule);
Gregory P. Smithf21a5f72005-08-21 18:45:59 +00001031 if (m == NULL)
Martin v. Löwis1a214512008-06-11 05:26:20 +00001032 return NULL;
Gregory P. Smithf21a5f72005-08-21 18:45:59 +00001033
Gregory P. Smith13b55292010-09-06 08:30:23 +00001034 openssl_md_meth_names = generate_hash_name_list();
1035 if (openssl_md_meth_names == NULL) {
1036 Py_DECREF(m);
1037 return NULL;
1038 }
1039 if (PyModule_AddObject(m, "openssl_md_meth_names", openssl_md_meth_names)) {
1040 Py_DECREF(m);
1041 return NULL;
1042 }
1043
Christian Heimes327dd732013-10-22 15:05:23 +02001044 Py_INCREF((PyObject *)&EVPtype);
Gregory P. Smithf21a5f72005-08-21 18:45:59 +00001045 PyModule_AddObject(m, "HASH", (PyObject *)&EVPtype);
Gregory P. Smithf21a5f72005-08-21 18:45:59 +00001046
1047 /* these constants are used by the convenience constructors */
1048 INIT_CONSTRUCTOR_CONSTANTS(md5);
1049 INIT_CONSTRUCTOR_CONSTANTS(sha1);
1050 INIT_CONSTRUCTOR_CONSTANTS(sha224);
1051 INIT_CONSTRUCTOR_CONSTANTS(sha256);
1052 INIT_CONSTRUCTOR_CONSTANTS(sha384);
1053 INIT_CONSTRUCTOR_CONSTANTS(sha512);
Martin v. Löwis1a214512008-06-11 05:26:20 +00001054 return m;
Gregory P. Smithf21a5f72005-08-21 18:45:59 +00001055}