crypto_box_seal.c 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. #include <string.h>
  2. #include "crypto_box.h"
  3. #include "crypto_generichash.h"
  4. #include "private/common.h"
  5. #include "utils.h"
  6. static int
  7. _crypto_box_seal_nonce(unsigned char *nonce,
  8. const unsigned char *pk1, const unsigned char *pk2)
  9. {
  10. crypto_generichash_state st;
  11. crypto_generichash_init(&st, NULL, 0U, crypto_box_NONCEBYTES);
  12. crypto_generichash_update(&st, pk1, crypto_box_PUBLICKEYBYTES);
  13. crypto_generichash_update(&st, pk2, crypto_box_PUBLICKEYBYTES);
  14. crypto_generichash_final(&st, nonce, crypto_box_NONCEBYTES);
  15. return 0;
  16. }
  17. int
  18. crypto_box_seal(unsigned char *c, const unsigned char *m,
  19. unsigned long long mlen, const unsigned char *pk)
  20. {
  21. unsigned char nonce[crypto_box_NONCEBYTES];
  22. unsigned char epk[crypto_box_PUBLICKEYBYTES];
  23. unsigned char esk[crypto_box_SECRETKEYBYTES];
  24. int ret;
  25. if (crypto_box_keypair(epk, esk) != 0) {
  26. return -1; /* LCOV_EXCL_LINE */
  27. }
  28. _crypto_box_seal_nonce(nonce, epk, pk);
  29. ret = crypto_box_easy(c + crypto_box_PUBLICKEYBYTES, m, mlen,
  30. nonce, pk, esk);
  31. memcpy(c, epk, crypto_box_PUBLICKEYBYTES);
  32. sodium_memzero(esk, sizeof esk);
  33. sodium_memzero(epk, sizeof epk);
  34. sodium_memzero(nonce, sizeof nonce);
  35. return ret;
  36. }
  37. int
  38. crypto_box_seal_open(unsigned char *m, const unsigned char *c,
  39. unsigned long long clen,
  40. const unsigned char *pk, const unsigned char *sk)
  41. {
  42. unsigned char nonce[crypto_box_NONCEBYTES];
  43. if (clen < crypto_box_SEALBYTES) {
  44. return -1;
  45. }
  46. _crypto_box_seal_nonce(nonce, c, pk);
  47. COMPILER_ASSERT(crypto_box_PUBLICKEYBYTES < crypto_box_SEALBYTES);
  48. return crypto_box_open_easy(m, c + crypto_box_PUBLICKEYBYTES,
  49. clen - crypto_box_PUBLICKEYBYTES,
  50. nonce, c, sk);
  51. }
  52. size_t
  53. crypto_box_sealbytes(void)
  54. {
  55. return crypto_box_SEALBYTES;
  56. }