pkcs_1_test.c 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. /* LibTomCrypt, modular cryptographic library -- Tom St Denis */
  2. /* SPDX-License-Identifier: Unlicense */
  3. #include <tomcrypt_test.h>
  4. #ifdef LTC_PKCS_1
  5. #ifdef LTC_TEST_REAL_RAND
  6. #define LTC_TEST_RAND_SEED time(NULL)
  7. #else
  8. #define LTC_TEST_RAND_SEED 23
  9. #endif
  10. int pkcs_1_test(void)
  11. {
  12. unsigned char buf[3][128];
  13. int res1, res2, res3;
  14. unsigned long x, y, l1, l2, l3, i1, modlen;
  15. static const unsigned char lparam[] = { 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16 };
  16. ltc_rsa_op_parameters rsa_params = {
  17. .wprng = find_prng("yarrow"),
  18. .prng = &yarrow_prng,
  19. .params.hash_alg = "sha1",
  20. .params.mgf1_hash_alg = "sha1",
  21. };
  22. srand(LTC_TEST_RAND_SEED);
  23. /* do many tests */
  24. for (x = 0; x < 100; x++) {
  25. zeromem(buf, sizeof(buf));
  26. /* make a dummy message (of random length) */
  27. l3 = (rand() & 31) + 8;
  28. for (y = 0; y < l3; y++) buf[0][y] = rand() & 255;
  29. /* pick a random lparam len [0..16] */
  30. rsa_params.u.crypt.lparamlen = abs(rand()) % 17;
  31. /* pick a random saltlen 0..16 */
  32. rsa_params.params.saltlen = abs(rand()) % 17;
  33. /* PKCS #1 v2.0 supports modlens not multiple of 8 */
  34. modlen = 800 + (abs(rand()) % 224);
  35. /* encode it */
  36. l1 = sizeof(buf[1]);
  37. rsa_params.padding = LTC_PKCS_1_OAEP;
  38. rsa_params.u.crypt.lparam = lparam;
  39. DO(ltc_pkcs_1_oaep_encode(buf[0], l3, &rsa_params, modlen, buf[1], &l1));
  40. /* decode it */
  41. l2 = sizeof(buf[2]);
  42. DO(ltc_pkcs_1_oaep_decode(buf[1], l1, &rsa_params, modlen, buf[2], &l2, &res1));
  43. ENSURE(res1 == 1);
  44. COMPARE_TESTVECTOR(buf[0], l3, buf[2], l2, "PKCS#1 OAEP", x);
  45. /* test PSS */
  46. l1 = sizeof(buf[1]);
  47. rsa_params.padding = LTC_PKCS_1_PSS;
  48. rsa_params.u.crypt.lparam = NULL;
  49. rsa_params.u.crypt.lparamlen = 0;
  50. DO(ltc_pkcs_1_pss_encode_mgf1(buf[0], l3, &rsa_params, modlen, buf[1], &l1));
  51. DO(ltc_pkcs_1_pss_decode_mgf1(buf[0], l3, buf[1], l1, &rsa_params, modlen, &res1));
  52. buf[0][i1 = abs(rand()) % l3] ^= 1;
  53. DO(ltc_pkcs_1_pss_decode_mgf1(buf[0], l3, buf[1], l1, &rsa_params, modlen, &res2));
  54. buf[0][i1] ^= 1;
  55. buf[1][abs(rand()) % (l1 - 1)] ^= 1;
  56. ltc_pkcs_1_pss_decode_mgf1(buf[0], l3, buf[1], l1, &rsa_params, modlen, &res3);
  57. if (!(res1 == 1 && res2 == 0 && res3 == 0)) {
  58. fprintf(stderr, "PSS failed: %d, %d, %d, %lu, %lu\n", res1, res2, res3, l3, rsa_params.params.saltlen);
  59. return 1;
  60. }
  61. }
  62. return 0;
  63. }
  64. #else
  65. int pkcs_1_test(void)
  66. {
  67. return CRYPT_NOP;
  68. }
  69. #endif