1 /* Module that wraps all OpenSSL hash algorithms */
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)
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
27 PyObject
*name
; /* name of this hash algorithm */
28 EVP_MD_CTX ctx
; /* OpenSSL message digest context */
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
)
49 newEVPobject(PyObject
*name
)
51 EVPobject
*retval
= (EVPobject
*)PyObject_New(EVPobject
, &EVPtype
);
53 /* save the name for .name to return */
62 /* Internal methods for a hash object */
65 EVP_dealloc(PyObject
*ptr
)
67 EVP_MD_CTX_cleanup(&((EVPobject
*)ptr
)->ctx
);
68 Py_XDECREF(((EVPobject
*)ptr
)->name
);
73 /* External methods for a hash object */
75 PyDoc_STRVAR(EVP_copy__doc__
, "Return a copy of the hash object.");
78 EVP_copy(EVPobject
*self
, PyObject
*args
)
82 if (!PyArg_ParseTuple(args
, ":copy"))
85 if ( (newobj
= newEVPobject(self
->name
))==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.");
96 EVP_digest(EVPobject
*self
, PyObject
*args
)
98 unsigned char digest
[EVP_MAX_MD_SIZE
];
101 unsigned int digest_size
;
103 if (!PyArg_ParseTuple(args
, ":digest"))
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
);
115 PyDoc_STRVAR(EVP_hexdigest__doc__
,
116 "Return the digest value as a string of hexadecimal digits.");
119 EVP_hexdigest(EVPobject
*self
, PyObject
*args
)
121 unsigned char digest
[EVP_MAX_MD_SIZE
];
125 unsigned int i
, j
, digest_size
;
127 if (!PyArg_ParseTuple(args
, ":hexdigest"))
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);
143 hex_digest
= PyString_AsString(retval
);
149 /* Make hex version of the digest */
150 for(i
=j
=0; i
<digest_size
; i
++) {
152 c
= (digest
[i
] >> 4) & 0xf;
153 c
= (c
>9) ? c
+'a'-10 : c
+ '0';
155 c
= (digest
[i
] & 0xf);
156 c
= (c
>9) ? c
+'a'-10 : c
+ '0';
162 PyDoc_STRVAR(EVP_update__doc__
,
163 "Update this hash object's state with the provided string.");
166 EVP_update(EVPobject
*self
, PyObject
*args
)
171 if (!PyArg_ParseTuple(args
, "s#:update", &cp
, &len
))
174 EVP_DigestUpdate(&self
->ctx
, cp
, len
);
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 */
189 EVP_get_block_size(EVPobject
*self
, void *closure
)
191 return PyInt_FromLong(EVP_MD_CTX_block_size(&((EVPobject
*)self
)->ctx
));
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
[] = {
207 (getter
)EVP_get_digest_size
, NULL
,
211 (getter
)EVP_get_block_size
, NULL
,
214 /* the old md5 and sha modules support 'digest_size' as in PEP 247.
215 * the old sha module also supported 'digestsize'. ugh. */
217 (getter
)EVP_get_digest_size
, NULL
,
220 {NULL
} /* Sentinel */
225 EVP_repr(PyObject
*self
)
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
235 EVP_tp_init(EVPobject
*self
, PyObject
*args
, PyObject
*kwds
)
237 static const char *kwlist
[] = {"name", "string", NULL
};
238 PyObject
*name_obj
= NULL
;
240 unsigned char *cp
= NULL
;
242 const EVP_MD
*digest
;
244 if (!PyArg_ParseTupleAndKeywords(args
, kwds
, "O|s#:HASH", kwlist
,
245 &name_obj
, &cp
, &len
)) {
249 if (!PyArg_Parse(name_obj
, "s", &nameStr
)) {
250 PyErr_SetString(PyExc_TypeError
, "name must be a string");
254 digest
= EVP_get_digestbyname(nameStr
);
256 PyErr_SetString(PyExc_ValueError
, "unknown hash function");
259 EVP_DigestInit(&self
->ctx
, digest
);
261 self
->name
= name_obj
;
262 Py_INCREF(self
->name
);
265 EVP_DigestUpdate(&self
->ctx
, cp
, len
);
272 PyDoc_STRVAR(hashtype_doc
,
273 "A hash represents the object used to calculate a checksum of a\n\
274 string of information.\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\
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
)
291 "_hashlib.HASH", /*tp_name*/
292 sizeof(EVPobject
), /*tp_basicsize*/
295 EVP_dealloc
, /*tp_dealloc*/
300 EVP_repr
, /*tp_repr*/
302 0, /*tp_as_sequence*/
310 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_BASETYPE
, /*tp_flags*/
311 hashtype_doc
, /*tp_doc*/
314 0, /*tp_richcompare*/
315 0, /*tp_weaklistoffset*/
318 EVP_methods
, /* tp_methods */
319 EVP_members
, /* tp_members */
320 EVP_getseters
, /* tp_getset */
324 0, /* tp_descr_get */
325 0, /* tp_descr_set */
326 0, /* tp_dictoffset */
328 #if HASH_OBJ_CONSTRUCTOR
329 (initproc
)EVP_tp_init
, /* tp_init */
334 EVPnew(PyObject
*name_obj
,
335 const EVP_MD
*digest
, const EVP_MD_CTX
*initial_ctx
,
336 const unsigned char *cp
, unsigned int len
)
340 if (!digest
&& !initial_ctx
) {
341 PyErr_SetString(PyExc_ValueError
, "unsupported hash type");
345 if ((self
= newEVPobject(name_obj
)) == NULL
)
349 EVP_MD_CTX_copy(&self
->ctx
, initial_ctx
);
351 EVP_DigestInit(&self
->ctx
, digest
);
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");
371 EVP_new(PyObject
*self
, PyObject
*args
, PyObject
*kwdict
)
373 static const char *kwlist
[] = {"name", "string", NULL
};
374 PyObject
*name_obj
= NULL
;
376 const EVP_MD
*digest
;
377 unsigned char *cp
= NULL
;
380 if (!PyArg_ParseTupleAndKeywords(args
, kwdict
, "O|s#:new", kwlist
,
381 &name_obj
, &cp
, &len
)) {
385 if (!PyArg_Parse(name_obj
, "s", &name
)) {
386 PyErr_SetString(PyExc_TypeError
, "name must be a string");
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) \
404 EVP_new_ ## NAME (PyObject *self, PyObject *args) \
406 unsigned char *cp = NULL; \
409 if (!PyArg_ParseTuple(args, "|s#:" #NAME , &cp, &len)) { \
414 CONST_ ## NAME ## _name_obj, \
416 CONST_new_ ## NAME ## _ctx_p, \
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)); \
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. */
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
471 EVPtype
.ob_type
= &PyType_Type
;
472 if (PyType_Ready(&EVPtype
) < 0)
475 m
= Py_InitModule("_hashlib", EVP_functions
);
479 #if HASH_OBJ_CONSTRUCTOR
481 PyModule_AddObject(m
, "HASH", (PyObject
*)&EVPtype
);
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
);