| 1 | #define PY_SSIZE_T_CLEAN |
| 2 | |
| 3 | #include <Python.h> |
| 4 | #include <openssl/crypto.h> |
| 5 | |
| 6 | #if PY_MAJOR_VERSION >= 3 |
| 7 | static PyObject* SecureString_clearmem(PyObject *self, PyObject *args) { |
| 8 | char *buffer; |
| 9 | Py_ssize_t length; |
| 10 | |
| 11 | if(!PyArg_ParseTuple(args, "s#", &buffer, &length)) { |
| 12 | return NULL; |
| 13 | } |
| 14 | OPENSSL_cleanse(buffer, length); |
| 15 | return Py_BuildValue(""); |
| 16 | } |
| 17 | #else |
| 18 | static PyObject* SecureString_clearmem(PyObject *self, PyObject *str) { |
| 19 | char *buffer; |
| 20 | Py_ssize_t length; |
| 21 | |
| 22 | if (PyString_AsStringAndSize(str, &buffer, &length) != -1) { |
| 23 | OPENSSL_cleanse(buffer, length); |
| 24 | } |
| 25 | return Py_BuildValue(""); |
| 26 | } |
| 27 | #endif |
| 28 | |
| 29 | #if PY_MAJOR_VERSION >= 3 |
| 30 | static PyMethodDef SecureStringMethods[] = { |
| 31 | {"clearmem", SecureString_clearmem, METH_VARARGS, "clear the memory of the string"}, |
| 32 | {NULL, NULL, 0, NULL}, |
| 33 | }; |
| 34 | #else |
| 35 | static PyMethodDef SecureStringMethods[] = { |
| 36 | {"clearmem", SecureString_clearmem, METH_O, |
| 37 | PyDoc_STR("clear the memory of the string")}, |
| 38 | {NULL, NULL, 0, NULL}, |
| 39 | }; |
| 40 | #endif |
| 41 | |
| 42 | #if PY_MAJOR_VERSION >= 3 |
| 43 | static struct PyModuleDef SecureStringDef = { |
| 44 | PyModuleDef_HEAD_INIT, |
| 45 | "SecureString", |
| 46 | NULL, |
| 47 | -1, |
| 48 | SecureStringMethods, |
| 49 | }; |
| 50 | #endif |
| 51 | |
| 52 | #if PY_MAJOR_VERSION >= 3 |
| 53 | PyMODINIT_FUNC PyInit_SecureString(void) { |
| 54 | return PyModule_Create(&SecureStringDef); |
| 55 | } |
| 56 | #else |
| 57 | PyMODINIT_FUNC initSecureString(void) |
| 58 | { |
| 59 | (void) Py_InitModule("SecureString", SecureStringMethods); |
| 60 | } |
| 61 | #endif |