randombytes.cc 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. /**
  2. * Node Native Module for Lib Sodium
  3. *
  4. * @Author Pedro Paixao
  5. * @email paixaop at gmail dot com
  6. * @License MIT
  7. */
  8. #include "node_sodium.h"
  9. // Generating Random Data
  10. // Docs: https://download.libsodium.org/doc/generating_random_data/index.html
  11. // Lib Sodium Random
  12. // void randombytes_buf(void *const buf, const size_t size)
  13. NAN_METHOD(bind_randombytes_buf) {
  14. Nan::EscapableHandleScope scope;
  15. ARGS(1, "argument must be a buffer");
  16. ARG_TO_VOID_BUFFER(buffer);
  17. randombytes_buf(buffer, buffer_size);
  18. return JS_NULL;
  19. }
  20. // void randombytes_stir()
  21. NAN_METHOD(bind_randombytes_stir) {
  22. Nan::EscapableHandleScope scope;
  23. randombytes_stir();
  24. return JS_NULL;
  25. }
  26. NAN_METHOD(bind_randombytes_close) {
  27. Nan::EscapableHandleScope scope;
  28. // int randombytes_close()
  29. return JS_INTEGER(randombytes_close());
  30. }
  31. NAN_METHOD(bind_randombytes_random) {
  32. Nan::EscapableHandleScope scope;
  33. // uint_32 randombytes_random()
  34. return JS_UINT32(randombytes_random());
  35. }
  36. NAN_METHOD(bind_randombytes_uniform) {
  37. Nan::EscapableHandleScope scope;
  38. ARGS(1, "argument size must be a positive number");
  39. ARG_TO_NUMBER(upper_bound);
  40. if (upper_bound <= 0) {
  41. return Nan::ThrowError("argument size must be a positive number");
  42. }
  43. // uint32_t randombytes_uniform(const uint32_t upper_bound)
  44. return JS_UINT32(randombytes_uniform(upper_bound));
  45. }
  46. NAN_METHOD(bind_randombytes_buf_deterministic) {
  47. Nan::EscapableHandleScope scope;
  48. ARGS(2,"arguments buf and seed must be buffers");
  49. ARG_TO_UCHAR_BUFFER(buffer);
  50. ARG_TO_UCHAR_BUFFER_LEN(seed, randombytes_SEEDBYTES);
  51. randombytes_buf_deterministic(buffer, buffer_size, seed);
  52. return JS_NULL;
  53. }
  54. /**
  55. * Register function calls in node binding
  56. */
  57. void register_randombytes(Handle<Object> target) {
  58. NEW_METHOD(randombytes_buf);
  59. Nan::SetMethod(target, "randombytes", bind_randombytes_buf);
  60. NEW_METHOD(randombytes_close);
  61. NEW_METHOD(randombytes_stir);
  62. NEW_METHOD(randombytes_random);
  63. NEW_METHOD(randombytes_uniform);
  64. NEW_METHOD(randombytes_buf_deterministic);
  65. NEW_INT_PROP(randombytes_SEEDBYTES);
  66. }