_cryptmodule.c 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. /* cryptmodule.c - by Steve Majewski
  2. */
  3. #include "Python.h"
  4. #include <sys/types.h>
  5. #ifdef HAVE_CRYPT_H
  6. #include <crypt.h>
  7. #endif
  8. /* Module crypt */
  9. /*[clinic input]
  10. module crypt
  11. [clinic start generated code]*/
  12. /*[clinic end generated code: output=da39a3ee5e6b4b0d input=c6252cf4f2f2ae81]*/
  13. #include "clinic/_cryptmodule.c.h"
  14. /*[clinic input]
  15. crypt.crypt
  16. word: str
  17. salt: str
  18. /
  19. Hash a *word* with the given *salt* and return the hashed password.
  20. *word* will usually be a user's password. *salt* (either a random 2 or 16
  21. character string, possibly prefixed with $digit$ to indicate the method)
  22. will be used to perturb the encryption algorithm and produce distinct
  23. results for a given *word*.
  24. [clinic start generated code]*/
  25. static PyObject *
  26. crypt_crypt_impl(PyObject *module, const char *word, const char *salt)
  27. /*[clinic end generated code: output=0512284a03d2803c input=0e8edec9c364352b]*/
  28. {
  29. char *crypt_result;
  30. #ifdef HAVE_CRYPT_R
  31. struct crypt_data data;
  32. memset(&data, 0, sizeof(data));
  33. crypt_result = crypt_r(word, salt, &data);
  34. #else
  35. crypt_result = crypt(word, salt);
  36. #endif
  37. if (crypt_result == NULL) {
  38. return PyErr_SetFromErrno(PyExc_OSError);
  39. }
  40. return Py_BuildValue("s", crypt_result);
  41. }
  42. static PyMethodDef crypt_methods[] = {
  43. CRYPT_CRYPT_METHODDEF
  44. {NULL, NULL} /* sentinel */
  45. };
  46. static PyModuleDef_Slot _crypt_slots[] = {
  47. {Py_mod_multiple_interpreters, Py_MOD_PER_INTERPRETER_GIL_SUPPORTED},
  48. {0, NULL}
  49. };
  50. static struct PyModuleDef cryptmodule = {
  51. PyModuleDef_HEAD_INIT,
  52. "_crypt",
  53. NULL,
  54. 0,
  55. crypt_methods,
  56. _crypt_slots,
  57. NULL,
  58. NULL,
  59. NULL
  60. };
  61. PyMODINIT_FUNC
  62. PyInit__crypt(void)
  63. {
  64. return PyModuleDef_Init(&cryptmodule);
  65. }