secretbox_easy2.c 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. #define TEST_NAME "secretbox_easy2"
  2. #include "cmptest.h"
  3. int
  4. main(void)
  5. {
  6. unsigned char *m;
  7. unsigned char *m2;
  8. unsigned char *c;
  9. unsigned char *nonce;
  10. unsigned char *k;
  11. unsigned char *mac;
  12. size_t mlen;
  13. size_t i;
  14. mlen = (size_t) randombytes_uniform((uint32_t) 10000) + 1U;
  15. m = (unsigned char *) sodium_malloc(mlen);
  16. m2 = (unsigned char *) sodium_malloc(mlen);
  17. c = (unsigned char *) sodium_malloc(crypto_secretbox_MACBYTES + mlen);
  18. nonce = (unsigned char *) sodium_malloc(crypto_secretbox_NONCEBYTES);
  19. k = (unsigned char *) sodium_malloc(crypto_secretbox_KEYBYTES);
  20. mac = (unsigned char *) sodium_malloc(crypto_secretbox_MACBYTES);
  21. crypto_secretbox_keygen(k);
  22. randombytes_buf(m, (unsigned long long) mlen);
  23. randombytes_buf(nonce, crypto_secretbox_NONCEBYTES);
  24. crypto_secretbox_easy(c, m, (unsigned long long) mlen, nonce, k);
  25. if (crypto_secretbox_open_easy(
  26. m2, c, (unsigned long long) mlen + crypto_secretbox_MACBYTES, nonce,
  27. k) != 0) {
  28. printf("crypto_secretbox_open_easy() failed\n");
  29. }
  30. printf("%d\n", memcmp(m, m2, mlen));
  31. for (i = 0; i < mlen + crypto_secretbox_MACBYTES - 1; i++) {
  32. if (crypto_secretbox_open_easy(m2, c, (unsigned long long) i, nonce,
  33. k) == 0) {
  34. printf("short open() should have failed\n");
  35. return 1;
  36. }
  37. }
  38. crypto_secretbox_detached(c, mac, m, (unsigned long long) mlen, nonce, k);
  39. if (crypto_secretbox_open_detached(NULL, c, mac, (unsigned long long) mlen,
  40. nonce, k) != 0) {
  41. printf("crypto_secretbox_open_detached() with a NULL message pointer failed\n");
  42. }
  43. if (crypto_secretbox_open_detached(m2, c, mac, (unsigned long long) mlen,
  44. nonce, k) != 0) {
  45. printf("crypto_secretbox_open_detached() failed\n");
  46. }
  47. printf("%d\n", memcmp(m, m2, mlen));
  48. memcpy(c, m, mlen);
  49. crypto_secretbox_easy(c, c, (unsigned long long) mlen, nonce, k);
  50. printf("%d\n", memcmp(m, c, mlen) == 0);
  51. printf("%d\n", memcmp(m, c + crypto_secretbox_MACBYTES, mlen) == 0);
  52. if (crypto_secretbox_open_easy(
  53. c, c, (unsigned long long) mlen + crypto_secretbox_MACBYTES, nonce,
  54. k) != 0) {
  55. printf("crypto_secretbox_open_easy() failed\n");
  56. }
  57. printf("%d\n", memcmp(m, c, mlen));
  58. sodium_free(m);
  59. sodium_free(m2);
  60. sodium_free(c);
  61. sodium_free(nonce);
  62. sodium_free(k);
  63. sodium_free(mac);
  64. return 0;
  65. }