box_seal_curve25519xchacha20poly1305.c 3.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. #include <string.h>
  2. #include "crypto_box_curve25519xchacha20poly1305.h"
  3. #include "crypto_generichash.h"
  4. #include "private/common.h"
  5. #include "utils.h"
  6. static int
  7. _crypto_box_curve25519xchacha20poly1305_seal_nonce(unsigned char *nonce,
  8. const unsigned char *pk1,
  9. const unsigned char *pk2)
  10. {
  11. crypto_generichash_state st;
  12. crypto_generichash_init(&st, NULL, 0U,
  13. crypto_box_curve25519xchacha20poly1305_NONCEBYTES);
  14. crypto_generichash_update(&st, pk1,
  15. crypto_box_curve25519xchacha20poly1305_PUBLICKEYBYTES);
  16. crypto_generichash_update(&st, pk2,
  17. crypto_box_curve25519xchacha20poly1305_PUBLICKEYBYTES);
  18. crypto_generichash_final(&st, nonce,
  19. crypto_box_curve25519xchacha20poly1305_NONCEBYTES);
  20. return 0;
  21. }
  22. int
  23. crypto_box_curve25519xchacha20poly1305_seal(unsigned char *c, const unsigned char *m,
  24. unsigned long long mlen,
  25. const unsigned char *pk)
  26. {
  27. unsigned char nonce[crypto_box_curve25519xchacha20poly1305_NONCEBYTES];
  28. unsigned char epk[crypto_box_curve25519xchacha20poly1305_PUBLICKEYBYTES];
  29. unsigned char esk[crypto_box_curve25519xchacha20poly1305_SECRETKEYBYTES];
  30. int ret;
  31. if (crypto_box_curve25519xchacha20poly1305_keypair(epk, esk) != 0) {
  32. return -1; /* LCOV_EXCL_LINE */
  33. }
  34. memcpy(c, epk, crypto_box_curve25519xchacha20poly1305_PUBLICKEYBYTES);
  35. _crypto_box_curve25519xchacha20poly1305_seal_nonce(nonce, epk, pk);
  36. ret = crypto_box_curve25519xchacha20poly1305_easy(
  37. c + crypto_box_curve25519xchacha20poly1305_PUBLICKEYBYTES, m, mlen,
  38. nonce, pk, esk);
  39. sodium_memzero(esk, sizeof esk);
  40. sodium_memzero(epk, sizeof epk);
  41. sodium_memzero(nonce, sizeof nonce);
  42. return ret;
  43. }
  44. int
  45. crypto_box_curve25519xchacha20poly1305_seal_open(unsigned char *m, const unsigned char *c,
  46. unsigned long long clen,
  47. const unsigned char *pk,
  48. const unsigned char *sk)
  49. {
  50. unsigned char nonce[crypto_box_curve25519xchacha20poly1305_NONCEBYTES];
  51. if (clen < crypto_box_curve25519xchacha20poly1305_SEALBYTES) {
  52. return -1;
  53. }
  54. _crypto_box_curve25519xchacha20poly1305_seal_nonce(nonce, c, pk);
  55. COMPILER_ASSERT(crypto_box_curve25519xchacha20poly1305_PUBLICKEYBYTES <
  56. crypto_box_curve25519xchacha20poly1305_SEALBYTES);
  57. return crypto_box_curve25519xchacha20poly1305_open_easy(
  58. m, c + crypto_box_curve25519xchacha20poly1305_PUBLICKEYBYTES,
  59. clen - crypto_box_curve25519xchacha20poly1305_PUBLICKEYBYTES,
  60. nonce, c, sk);
  61. }
  62. size_t
  63. crypto_box_curve25519xchacha20poly1305_sealbytes(void)
  64. {
  65. return crypto_box_curve25519xchacha20poly1305_SEALBYTES;
  66. }