luat_lib_crypto.c 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. /*
  2. @module crypto
  3. @summary 加解密和hash函数
  4. @version 1.0
  5. @data 2020.07.03
  6. */
  7. #include "luat_base.h"
  8. #include "luat_crypto.h"
  9. static unsigned char hexchars[] = "0123456789ABCDEF";
  10. static void fixhex(const char* source, char* dst, size_t len) {
  11. for (size_t i = 0; i < len; i++)
  12. {
  13. char ch = *(source+i);
  14. dst[i*2] = hexchars[(unsigned char)ch >> 4];
  15. dst[i*2+1] = hexchars[(unsigned char)ch & 0xF];
  16. }
  17. }
  18. static int l_crypto_md5(lua_State *L) {
  19. size_t size = 0;
  20. const char* str = luaL_checklstring(L, 1, &size);
  21. char tmp[32] = {0};
  22. char dst[32] = {0};
  23. if (luat_crypto_md5_simple(str, size, tmp) == 0) {
  24. fixhex(tmp, dst, 16);
  25. lua_pushlstring(L, dst, 32);
  26. return 1;
  27. }
  28. return 0;
  29. }
  30. static int l_crypto_hmac_md5(lua_State *L) {
  31. size_t str_size = 0;
  32. size_t key_size = 0;
  33. const char* str = luaL_checklstring(L, 1, &str_size);
  34. const char* key = luaL_checklstring(L, 2, &key_size);
  35. char tmp[32] = {0};
  36. char dst[32] = {0};
  37. if (luat_crypto_hmac_md5_simple(str, str_size, key, key_size, tmp) == 0) {
  38. fixhex(tmp, dst, 16);
  39. lua_pushlstring(L, dst, 32);
  40. return 1;
  41. }
  42. return 0;
  43. }
  44. static int l_crypto_sha1(lua_State *L) {
  45. size_t size = 0;
  46. const char* str = luaL_checklstring(L, 1, &size);
  47. char tmp[40] = {0};
  48. char dst[40] = {0};
  49. if (luat_crypto_sha1_simple(str, size, tmp) == 0) {
  50. fixhex(tmp, dst, 20);
  51. lua_pushlstring(L, dst, 40);
  52. return 1;
  53. }
  54. return 0;
  55. }
  56. static int l_crypto_hmac_sha1(lua_State *L) {
  57. size_t str_size = 0;
  58. size_t key_size = 0;
  59. const char* str = luaL_checklstring(L, 1, &str_size);
  60. const char* key = luaL_checklstring(L, 2, &key_size);
  61. char tmp[40] = {0};
  62. char dst[40] = {0};
  63. if (luat_crypto_hmac_sha1_simple(str, str_size, key, key_size, tmp) == 0) {
  64. fixhex(tmp, dst, 20);
  65. lua_pushlstring(L, dst, 40);
  66. return 1;
  67. }
  68. return 0;
  69. }
  70. #include "rotable.h"
  71. static const rotable_Reg reg_crypto[] =
  72. {
  73. { "md5" , l_crypto_md5 ,0},
  74. { "hmac_md5" , l_crypto_hmac_md5 ,0},
  75. { "sha1" , l_crypto_sha1 ,0},
  76. { "hmac_sha1" , l_crypto_hmac_sha1 ,0},
  77. { NULL, NULL ,0}
  78. };
  79. LUAMOD_API int luaopen_crypto( lua_State *L ) {
  80. rotable_newlib(L, reg_crypto);
  81. return 1;
  82. }