box8.c 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. #define TEST_NAME "box8"
  2. #include "cmptest.h"
  3. static unsigned char alicesk[crypto_box_SECRETKEYBYTES];
  4. static unsigned char alicepk[crypto_box_PUBLICKEYBYTES];
  5. static unsigned char bobsk[crypto_box_SECRETKEYBYTES];
  6. static unsigned char bobpk[crypto_box_PUBLICKEYBYTES];
  7. static unsigned char n[crypto_box_NONCEBYTES];
  8. int
  9. main(void)
  10. {
  11. unsigned char *m;
  12. unsigned char *c;
  13. unsigned char *m2;
  14. size_t mlen;
  15. size_t mlen_max = 1000;
  16. size_t i;
  17. int faults;
  18. int ret;
  19. m = (unsigned char *) sodium_malloc(mlen_max);
  20. c = (unsigned char *) sodium_malloc(mlen_max);
  21. m2 = (unsigned char *) sodium_malloc(mlen_max);
  22. crypto_box_keypair(alicepk, alicesk);
  23. crypto_box_keypair(bobpk, bobsk);
  24. for (mlen = 0; mlen + crypto_box_ZEROBYTES <= mlen_max; mlen++) {
  25. randombytes_buf(n, crypto_box_NONCEBYTES);
  26. randombytes_buf(m + crypto_box_ZEROBYTES, mlen);
  27. ret = crypto_box(c, m, mlen + crypto_box_ZEROBYTES, n, bobpk, alicesk);
  28. assert(ret == 0);
  29. #ifdef BROWSER_TESTS
  30. faults = 1;
  31. #else
  32. faults = 5;
  33. #endif
  34. while (faults > 0) {
  35. c[rand() % (mlen + crypto_box_ZEROBYTES)] = rand();
  36. if (crypto_box_open(m2, c, mlen + crypto_box_ZEROBYTES, n, alicepk,
  37. bobsk) == 0) {
  38. for (i = 0; i < mlen + crypto_box_ZEROBYTES; ++i) {
  39. if (m2[i] != m[i]) {
  40. printf("forgery\n");
  41. return 100;
  42. }
  43. }
  44. } else {
  45. faults--;
  46. }
  47. }
  48. }
  49. sodium_free(m);
  50. sodium_free(c);
  51. sodium_free(m2);
  52. return 0;
  53. }