Exceptions raised during renaming in rotating file handlers are now passed to handleE...
[python.git] / Modules / _hashopenssl.c
blob9bdd274e43e7a9278b45d46ad8e2cf6f83e68f0d
1 /* Module that wraps all OpenSSL hash algorithms */
3 /*
4 * Copyright (C) 2005 Gregory P. Smith (greg@electricrain.com)
5 * Licensed to PSF under a Contributor Agreement.
7 * Derived from a skeleton of shamodule.c containing work performed by:
9 * Andrew Kuchling (amk@amk.ca)
10 * Greg Stein (gstein@lyra.org)
14 #include "Python.h"
15 #include "structmember.h"
17 /* EVP is the preferred interface to hashing in OpenSSL */
18 #include <openssl/evp.h>
21 #ifndef HASH_OBJ_CONSTRUCTOR
22 #define HASH_OBJ_CONSTRUCTOR 0
23 #endif
25 typedef struct {
26 PyObject_HEAD
27 PyObject *name; /* name of this hash algorithm */
28 EVP_MD_CTX ctx; /* OpenSSL message digest context */
29 } EVPobject;
32 static PyTypeObject EVPtype;
35 #define DEFINE_CONSTS_FOR_NEW(Name) \
36 static PyObject *CONST_ ## Name ## _name_obj; \
37 static EVP_MD_CTX CONST_new_ ## Name ## _ctx; \
38 static EVP_MD_CTX *CONST_new_ ## Name ## _ctx_p = NULL;
40 DEFINE_CONSTS_FOR_NEW(md5)
41 DEFINE_CONSTS_FOR_NEW(sha1)
42 DEFINE_CONSTS_FOR_NEW(sha224)
43 DEFINE_CONSTS_FOR_NEW(sha256)
44 DEFINE_CONSTS_FOR_NEW(sha384)
45 DEFINE_CONSTS_FOR_NEW(sha512)
48 static EVPobject *
49 newEVPobject(PyObject *name)
51 EVPobject *retval = (EVPobject *)PyObject_New(EVPobject, &EVPtype);
53 /* save the name for .name to return */
54 if (retval != NULL) {
55 Py_INCREF(name);
56 retval->name = name;
59 return retval;
62 /* Internal methods for a hash object */
64 static void
65 EVP_dealloc(PyObject *ptr)
67 EVP_MD_CTX_cleanup(&((EVPobject *)ptr)->ctx);
68 Py_XDECREF(((EVPobject *)ptr)->name);
69 PyObject_Del(ptr);
73 /* External methods for a hash object */
75 PyDoc_STRVAR(EVP_copy__doc__, "Return a copy of the hash object.");
77 static PyObject *
78 EVP_copy(EVPobject *self, PyObject *args)
80 EVPobject *newobj;
82 if (!PyArg_ParseTuple(args, ":copy"))
83 return NULL;
85 if ( (newobj = newEVPobject(self->name))==NULL)
86 return NULL;
88 EVP_MD_CTX_copy(&newobj->ctx, &self->ctx);
89 return (PyObject *)newobj;
92 PyDoc_STRVAR(EVP_digest__doc__,
93 "Return the digest value as a string of binary data.");
95 static PyObject *
96 EVP_digest(EVPobject *self, PyObject *args)
98 unsigned char digest[EVP_MAX_MD_SIZE];
99 EVP_MD_CTX temp_ctx;
100 PyObject *retval;
101 unsigned int digest_size;
103 if (!PyArg_ParseTuple(args, ":digest"))
104 return NULL;
106 EVP_MD_CTX_copy(&temp_ctx, &self->ctx);
107 digest_size = EVP_MD_CTX_size(&temp_ctx);
108 EVP_DigestFinal(&temp_ctx, digest, NULL);
110 retval = PyString_FromStringAndSize((const char *)digest, digest_size);
111 EVP_MD_CTX_cleanup(&temp_ctx);
112 return retval;
115 PyDoc_STRVAR(EVP_hexdigest__doc__,
116 "Return the digest value as a string of hexadecimal digits.");
118 static PyObject *
119 EVP_hexdigest(EVPobject *self, PyObject *args)
121 unsigned char digest[EVP_MAX_MD_SIZE];
122 EVP_MD_CTX temp_ctx;
123 PyObject *retval;
124 char *hex_digest;
125 unsigned int i, j, digest_size;
127 if (!PyArg_ParseTuple(args, ":hexdigest"))
128 return NULL;
130 /* Get the raw (binary) digest value */
131 EVP_MD_CTX_copy(&temp_ctx, &self->ctx);
132 digest_size = EVP_MD_CTX_size(&temp_ctx);
133 EVP_DigestFinal(&temp_ctx, digest, NULL);
135 EVP_MD_CTX_cleanup(&temp_ctx);
137 /* Create a new string */
138 /* NOTE: not thread safe! modifying an already created string object */
139 /* (not a problem because we hold the GIL by default) */
140 retval = PyString_FromStringAndSize(NULL, digest_size * 2);
141 if (!retval)
142 return NULL;
143 hex_digest = PyString_AsString(retval);
144 if (!hex_digest) {
145 Py_DECREF(retval);
146 return NULL;
149 /* Make hex version of the digest */
150 for(i=j=0; i<digest_size; i++) {
151 char c;
152 c = (digest[i] >> 4) & 0xf;
153 c = (c>9) ? c+'a'-10 : c + '0';
154 hex_digest[j++] = c;
155 c = (digest[i] & 0xf);
156 c = (c>9) ? c+'a'-10 : c + '0';
157 hex_digest[j++] = c;
159 return retval;
162 PyDoc_STRVAR(EVP_update__doc__,
163 "Update this hash object's state with the provided string.");
165 static PyObject *
166 EVP_update(EVPobject *self, PyObject *args)
168 unsigned char *cp;
169 int len;
171 if (!PyArg_ParseTuple(args, "s#:update", &cp, &len))
172 return NULL;
174 EVP_DigestUpdate(&self->ctx, cp, len);
176 Py_INCREF(Py_None);
177 return Py_None;
180 static PyMethodDef EVP_methods[] = {
181 {"update", (PyCFunction)EVP_update, METH_VARARGS, EVP_update__doc__},
182 {"digest", (PyCFunction)EVP_digest, METH_VARARGS, EVP_digest__doc__},
183 {"hexdigest", (PyCFunction)EVP_hexdigest, METH_VARARGS, EVP_hexdigest__doc__},
184 {"copy", (PyCFunction)EVP_copy, METH_VARARGS, EVP_copy__doc__},
185 {NULL, NULL} /* sentinel */
188 static PyObject *
189 EVP_get_block_size(EVPobject *self, void *closure)
191 return PyInt_FromLong(EVP_MD_CTX_block_size(&((EVPobject *)self)->ctx));
194 static PyObject *
195 EVP_get_digest_size(EVPobject *self, void *closure)
197 return PyInt_FromLong(EVP_MD_CTX_size(&((EVPobject *)self)->ctx));
200 static PyMemberDef EVP_members[] = {
201 {"name", T_OBJECT, offsetof(EVPobject, name), READONLY, PyDoc_STR("algorithm name.")},
202 {NULL} /* Sentinel */
205 static PyGetSetDef EVP_getseters[] = {
206 {"digest_size",
207 (getter)EVP_get_digest_size, NULL,
208 NULL,
209 NULL},
210 {"block_size",
211 (getter)EVP_get_block_size, NULL,
212 NULL,
213 NULL},
214 /* the old md5 and sha modules support 'digest_size' as in PEP 247.
215 * the old sha module also supported 'digestsize'. ugh. */
216 {"digestsize",
217 (getter)EVP_get_digest_size, NULL,
218 NULL,
219 NULL},
220 {NULL} /* Sentinel */
224 static PyObject *
225 EVP_repr(PyObject *self)
227 char buf[100];
228 PyOS_snprintf(buf, sizeof(buf), "<%s HASH object @ %p>",
229 PyString_AsString(((EVPobject *)self)->name), self);
230 return PyString_FromString(buf);
233 #if HASH_OBJ_CONSTRUCTOR
234 static int
235 EVP_tp_init(EVPobject *self, PyObject *args, PyObject *kwds)
237 static const char *kwlist[] = {"name", "string", NULL};
238 PyObject *name_obj = NULL;
239 char *nameStr;
240 unsigned char *cp = NULL;
241 unsigned int len;
242 const EVP_MD *digest;
244 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|s#:HASH", kwlist,
245 &name_obj, &cp, &len)) {
246 return -1;
249 if (!PyArg_Parse(name_obj, "s", &nameStr)) {
250 PyErr_SetString(PyExc_TypeError, "name must be a string");
251 return -1;
254 digest = EVP_get_digestbyname(nameStr);
255 if (!digest) {
256 PyErr_SetString(PyExc_ValueError, "unknown hash function");
257 return -1;
259 EVP_DigestInit(&self->ctx, digest);
261 self->name = name_obj;
262 Py_INCREF(self->name);
264 if (cp && len)
265 EVP_DigestUpdate(&self->ctx, cp, len);
267 return 0;
269 #endif
272 PyDoc_STRVAR(hashtype_doc,
273 "A hash represents the object used to calculate a checksum of a\n\
274 string of information.\n\
276 Methods:\n\
278 update() -- updates the current digest with an additional string\n\
279 digest() -- return the current digest value\n\
280 hexdigest() -- return the current digest as a string of hexadecimal digits\n\
281 copy() -- return a copy of the current hash object\n\
283 Attributes:\n\
285 name -- the hash algorithm being used by this object\n\
286 digest_size -- number of bytes in this hashes output\n");
288 static PyTypeObject EVPtype = {
289 PyObject_HEAD_INIT(NULL)
290 0, /*ob_size*/
291 "_hashlib.HASH", /*tp_name*/
292 sizeof(EVPobject), /*tp_basicsize*/
293 0, /*tp_itemsize*/
294 /* methods */
295 EVP_dealloc, /*tp_dealloc*/
296 0, /*tp_print*/
297 0, /*tp_getattr*/
298 0, /*tp_setattr*/
299 0, /*tp_compare*/
300 EVP_repr, /*tp_repr*/
301 0, /*tp_as_number*/
302 0, /*tp_as_sequence*/
303 0, /*tp_as_mapping*/
304 0, /*tp_hash*/
305 0, /*tp_call*/
306 0, /*tp_str*/
307 0, /*tp_getattro*/
308 0, /*tp_setattro*/
309 0, /*tp_as_buffer*/
310 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
311 hashtype_doc, /*tp_doc*/
312 0, /*tp_traverse*/
313 0, /*tp_clear*/
314 0, /*tp_richcompare*/
315 0, /*tp_weaklistoffset*/
316 0, /*tp_iter*/
317 0, /*tp_iternext*/
318 EVP_methods, /* tp_methods */
319 EVP_members, /* tp_members */
320 EVP_getseters, /* tp_getset */
321 #if 1
322 0, /* tp_base */
323 0, /* tp_dict */
324 0, /* tp_descr_get */
325 0, /* tp_descr_set */
326 0, /* tp_dictoffset */
327 #endif
328 #if HASH_OBJ_CONSTRUCTOR
329 (initproc)EVP_tp_init, /* tp_init */
330 #endif
333 static PyObject *
334 EVPnew(PyObject *name_obj,
335 const EVP_MD *digest, const EVP_MD_CTX *initial_ctx,
336 const unsigned char *cp, unsigned int len)
338 EVPobject *self;
340 if (!digest && !initial_ctx) {
341 PyErr_SetString(PyExc_ValueError, "unsupported hash type");
342 return NULL;
345 if ((self = newEVPobject(name_obj)) == NULL)
346 return NULL;
348 if (initial_ctx) {
349 EVP_MD_CTX_copy(&self->ctx, initial_ctx);
350 } else {
351 EVP_DigestInit(&self->ctx, digest);
354 if (cp && len)
355 EVP_DigestUpdate(&self->ctx, cp, len);
357 return (PyObject *)self;
361 /* The module-level function: new() */
363 PyDoc_STRVAR(EVP_new__doc__,
364 "Return a new hash object using the named algorithm.\n\
365 An optional string argument may be provided and will be\n\
366 automatically hashed.\n\
368 The MD5 and SHA1 algorithms are always supported.\n");
370 static PyObject *
371 EVP_new(PyObject *self, PyObject *args, PyObject *kwdict)
373 static const char *kwlist[] = {"name", "string", NULL};
374 PyObject *name_obj = NULL;
375 char *name;
376 const EVP_MD *digest;
377 unsigned char *cp = NULL;
378 unsigned int len;
380 if (!PyArg_ParseTupleAndKeywords(args, kwdict, "O|s#:new", kwlist,
381 &name_obj, &cp, &len)) {
382 return NULL;
385 if (!PyArg_Parse(name_obj, "s", &name)) {
386 PyErr_SetString(PyExc_TypeError, "name must be a string");
387 return NULL;
390 digest = EVP_get_digestbyname(name);
392 return EVPnew(name_obj, digest, NULL, cp, len);
396 * This macro generates constructor function definitions for specific
397 * hash algorithms. These constructors are much faster than calling
398 * the generic one passing it a python string and are noticably
399 * faster than calling a python new() wrapper. Thats important for
400 * code that wants to make hashes of a bunch of small strings.
402 #define GEN_CONSTRUCTOR(NAME) \
403 static PyObject * \
404 EVP_new_ ## NAME (PyObject *self, PyObject *args) \
406 unsigned char *cp = NULL; \
407 unsigned int len; \
409 if (!PyArg_ParseTuple(args, "|s#:" #NAME , &cp, &len)) { \
410 return NULL; \
413 return EVPnew( \
414 CONST_ ## NAME ## _name_obj, \
415 NULL, \
416 CONST_new_ ## NAME ## _ctx_p, \
417 cp, len); \
420 /* a PyMethodDef structure for the constructor */
421 #define CONSTRUCTOR_METH_DEF(NAME) \
422 {"openssl_" #NAME, (PyCFunction)EVP_new_ ## NAME, METH_VARARGS, \
423 PyDoc_STR("Returns a " #NAME \
424 " hash object; optionally initialized with a string") \
427 /* used in the init function to setup a constructor */
428 #define INIT_CONSTRUCTOR_CONSTANTS(NAME) do { \
429 CONST_ ## NAME ## _name_obj = PyString_FromString(#NAME); \
430 if (EVP_get_digestbyname(#NAME)) { \
431 CONST_new_ ## NAME ## _ctx_p = &CONST_new_ ## NAME ## _ctx; \
432 EVP_DigestInit(CONST_new_ ## NAME ## _ctx_p, EVP_get_digestbyname(#NAME)); \
434 } while (0);
436 GEN_CONSTRUCTOR(md5)
437 GEN_CONSTRUCTOR(sha1)
438 GEN_CONSTRUCTOR(sha224)
439 GEN_CONSTRUCTOR(sha256)
440 GEN_CONSTRUCTOR(sha384)
441 GEN_CONSTRUCTOR(sha512)
443 /* List of functions exported by this module */
445 static struct PyMethodDef EVP_functions[] = {
446 {"new", (PyCFunction)EVP_new, METH_VARARGS|METH_KEYWORDS, EVP_new__doc__},
447 CONSTRUCTOR_METH_DEF(md5),
448 CONSTRUCTOR_METH_DEF(sha1),
449 CONSTRUCTOR_METH_DEF(sha224),
450 CONSTRUCTOR_METH_DEF(sha256),
451 CONSTRUCTOR_METH_DEF(sha384),
452 CONSTRUCTOR_METH_DEF(sha512),
453 {NULL, NULL} /* Sentinel */
457 /* Initialize this module. */
459 PyMODINIT_FUNC
460 init_hashlib(void)
462 PyObject *m;
464 OpenSSL_add_all_digests();
466 /* TODO build EVP_functions openssl_* entries dynamically based
467 * on what hashes are supported rather than listing many
468 * but having some be unsupported. Only init appropriate
469 * constants. */
471 EVPtype.ob_type = &PyType_Type;
472 if (PyType_Ready(&EVPtype) < 0)
473 return;
475 m = Py_InitModule("_hashlib", EVP_functions);
476 if (m == NULL)
477 return;
479 #if HASH_OBJ_CONSTRUCTOR
480 Py_INCREF(&EVPtype);
481 PyModule_AddObject(m, "HASH", (PyObject *)&EVPtype);
482 #endif
484 /* these constants are used by the convenience constructors */
485 INIT_CONSTRUCTOR_CONSTANTS(md5);
486 INIT_CONSTRUCTOR_CONSTANTS(sha1);
487 INIT_CONSTRUCTOR_CONSTANTS(sha224);
488 INIT_CONSTRUCTOR_CONSTANTS(sha256);
489 INIT_CONSTRUCTOR_CONSTANTS(sha384);
490 INIT_CONSTRUCTOR_CONSTANTS(sha512);