PageRenderTime 87ms CodeModel.GetById 27ms RepoModel.GetById 0ms app.codeStats 0ms

/security/nss/cmd/fipstest/fipstest.c

https://bitbucket.org/mkato/mozilla-1.9.0-win64
C | 4903 lines | 3797 code | 360 blank | 746 comment | 1445 complexity | ac6666cf55eeec83bda3ea3b4e6ec112 MD5 | raw file
Possible License(s): LGPL-3.0, MIT, BSD-3-Clause, MPL-2.0-no-copyleft-exception, GPL-2.0, LGPL-2.1
  1. /* ***** BEGIN LICENSE BLOCK *****
  2. * Version: MPL 1.1/GPL 2.0/LGPL 2.1
  3. *
  4. * The contents of this file are subject to the Mozilla Public License Version
  5. * 1.1 (the "License"); you may not use this file except in compliance with
  6. * the License. You may obtain a copy of the License at
  7. * http://www.mozilla.org/MPL/
  8. *
  9. * Software distributed under the License is distributed on an "AS IS" basis,
  10. * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
  11. * for the specific language governing rights and limitations under the
  12. * License.
  13. *
  14. * The Original Code is the Netscape security libraries.
  15. *
  16. * The Initial Developer of the Original Code is
  17. * Netscape Communications Corporation.
  18. * Portions created by the Initial Developer are Copyright (C) 1994-2000
  19. * the Initial Developer. All Rights Reserved.
  20. *
  21. * Contributor(s):
  22. *
  23. * Alternatively, the contents of this file may be used under the terms of
  24. * either the GNU General Public License Version 2 or later (the "GPL"), or
  25. * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
  26. * in which case the provisions of the GPL or the LGPL are applicable instead
  27. * of those above. If you wish to allow use of your version of this file only
  28. * under the terms of either the GPL or the LGPL, and not to allow others to
  29. * use your version of this file under the terms of the MPL, indicate your
  30. * decision by deleting the provisions above and replace them with the notice
  31. * and other provisions required by the GPL or the LGPL. If you do not delete
  32. * the provisions above, a recipient may use your version of this file under
  33. * the terms of any one of the MPL, the GPL or the LGPL.
  34. *
  35. * ***** END LICENSE BLOCK ***** */
  36. #include <stdio.h>
  37. #include <stdlib.h>
  38. #include <ctype.h>
  39. #include "secitem.h"
  40. #include "blapi.h"
  41. #include "nss.h"
  42. #include "secerr.h"
  43. #include "secder.h"
  44. #include "secdig.h"
  45. #include "keythi.h"
  46. #include "ec.h"
  47. #include "hasht.h"
  48. #include "lowkeyi.h"
  49. #include "softoken.h"
  50. #if 0
  51. #include "../../lib/freebl/mpi/mpi.h"
  52. #endif
  53. #ifdef NSS_ENABLE_ECC
  54. extern SECStatus
  55. EC_DecodeParams(const SECItem *encodedParams, ECParams **ecparams);
  56. extern SECStatus
  57. EC_CopyParams(PRArenaPool *arena, ECParams *dstParams,
  58. const ECParams *srcParams);
  59. #endif
  60. #define ENCRYPT 1
  61. #define DECRYPT 0
  62. #define BYTE unsigned char
  63. #define DEFAULT_RSA_PUBLIC_EXPONENT 0x10001
  64. #define RSA_MAX_TEST_MODULUS_BITS 4096
  65. #define RSA_MAX_TEST_MODULUS_BYTES RSA_MAX_TEST_MODULUS_BITS/8
  66. #define RSA_MAX_TEST_EXPONENT_BYTES 8
  67. #define PQG_TEST_SEED_BYTES 20
  68. SECStatus
  69. hex_to_byteval(const char *c2, unsigned char *byteval)
  70. {
  71. int i;
  72. unsigned char offset;
  73. *byteval = 0;
  74. for (i=0; i<2; i++) {
  75. if (c2[i] >= '0' && c2[i] <= '9') {
  76. offset = c2[i] - '0';
  77. *byteval |= offset << 4*(1-i);
  78. } else if (c2[i] >= 'a' && c2[i] <= 'f') {
  79. offset = c2[i] - 'a';
  80. *byteval |= (offset + 10) << 4*(1-i);
  81. } else if (c2[i] >= 'A' && c2[i] <= 'F') {
  82. offset = c2[i] - 'A';
  83. *byteval |= (offset + 10) << 4*(1-i);
  84. } else {
  85. return SECFailure;
  86. }
  87. }
  88. return SECSuccess;
  89. }
  90. SECStatus
  91. byteval_to_hex(unsigned char byteval, char *c2, char a)
  92. {
  93. int i;
  94. unsigned char offset;
  95. for (i=0; i<2; i++) {
  96. offset = (byteval >> 4*(1-i)) & 0x0f;
  97. if (offset < 10) {
  98. c2[i] = '0' + offset;
  99. } else {
  100. c2[i] = a + offset - 10;
  101. }
  102. }
  103. return SECSuccess;
  104. }
  105. void
  106. to_hex_str(char *str, const unsigned char *buf, unsigned int len)
  107. {
  108. unsigned int i;
  109. for (i=0; i<len; i++) {
  110. byteval_to_hex(buf[i], &str[2*i], 'a');
  111. }
  112. str[2*len] = '\0';
  113. }
  114. void
  115. to_hex_str_cap(char *str, const unsigned char *buf, unsigned int len)
  116. {
  117. unsigned int i;
  118. for (i=0; i<len; i++) {
  119. byteval_to_hex(buf[i], &str[2*i], 'A');
  120. }
  121. str[2*len] = '\0';
  122. }
  123. /*
  124. * Convert a string of hex digits (str) to an array (buf) of len bytes.
  125. * Return PR_TRUE if the hex string can fit in the byte array. Return
  126. * PR_FALSE if the hex string is empty or is too long.
  127. */
  128. PRBool
  129. from_hex_str(unsigned char *buf, unsigned int len, const char *str)
  130. {
  131. unsigned int nxdigit; /* number of hex digits in str */
  132. unsigned int i; /* index into buf */
  133. unsigned int j; /* index into str */
  134. /* count the hex digits */
  135. nxdigit = 0;
  136. for (nxdigit = 0; isxdigit(str[nxdigit]); nxdigit++) {
  137. /* empty body */
  138. }
  139. if (nxdigit == 0) {
  140. return PR_FALSE;
  141. }
  142. if (nxdigit > 2*len) {
  143. /*
  144. * The input hex string is too long, but we allow it if the
  145. * extra digits are leading 0's.
  146. */
  147. for (j = 0; j < nxdigit-2*len; j++) {
  148. if (str[j] != '0') {
  149. return PR_FALSE;
  150. }
  151. }
  152. /* skip leading 0's */
  153. str += nxdigit-2*len;
  154. nxdigit = 2*len;
  155. }
  156. for (i=0, j=0; i< len; i++) {
  157. if (2*i < 2*len-nxdigit) {
  158. /* Handle a short input as if we padded it with leading 0's. */
  159. if (2*i+1 < 2*len-nxdigit) {
  160. buf[i] = 0;
  161. } else {
  162. char tmp[2];
  163. tmp[0] = '0';
  164. tmp[1] = str[j];
  165. hex_to_byteval(tmp, &buf[i]);
  166. j++;
  167. }
  168. } else {
  169. hex_to_byteval(&str[j], &buf[i]);
  170. j += 2;
  171. }
  172. }
  173. return PR_TRUE;
  174. }
  175. SECStatus
  176. tdea_encrypt_buf(
  177. int mode,
  178. const unsigned char *key,
  179. const unsigned char *iv,
  180. unsigned char *output, unsigned int *outputlen, unsigned int maxoutputlen,
  181. const unsigned char *input, unsigned int inputlen)
  182. {
  183. SECStatus rv = SECFailure;
  184. DESContext *cx;
  185. unsigned char doublecheck[8*20]; /* 1 to 20 blocks */
  186. unsigned int doublechecklen = 0;
  187. cx = DES_CreateContext(key, iv, mode, PR_TRUE);
  188. if (cx == NULL) {
  189. goto loser;
  190. }
  191. rv = DES_Encrypt(cx, output, outputlen, maxoutputlen, input, inputlen);
  192. if (rv != SECSuccess) {
  193. goto loser;
  194. }
  195. if (*outputlen != inputlen) {
  196. goto loser;
  197. }
  198. DES_DestroyContext(cx, PR_TRUE);
  199. cx = NULL;
  200. /*
  201. * Doublecheck our result by decrypting the ciphertext and
  202. * compare the output with the input plaintext.
  203. */
  204. cx = DES_CreateContext(key, iv, mode, PR_FALSE);
  205. if (cx == NULL) {
  206. goto loser;
  207. }
  208. rv = DES_Decrypt(cx, doublecheck, &doublechecklen, sizeof doublecheck,
  209. output, *outputlen);
  210. if (rv != SECSuccess) {
  211. goto loser;
  212. }
  213. if (doublechecklen != *outputlen) {
  214. goto loser;
  215. }
  216. DES_DestroyContext(cx, PR_TRUE);
  217. cx = NULL;
  218. if (memcmp(doublecheck, input, inputlen) != 0) {
  219. goto loser;
  220. }
  221. rv = SECSuccess;
  222. loser:
  223. if (cx != NULL) {
  224. DES_DestroyContext(cx, PR_TRUE);
  225. }
  226. return rv;
  227. }
  228. SECStatus
  229. tdea_decrypt_buf(
  230. int mode,
  231. const unsigned char *key,
  232. const unsigned char *iv,
  233. unsigned char *output, unsigned int *outputlen, unsigned int maxoutputlen,
  234. const unsigned char *input, unsigned int inputlen)
  235. {
  236. SECStatus rv = SECFailure;
  237. DESContext *cx;
  238. unsigned char doublecheck[8*20]; /* 1 to 20 blocks */
  239. unsigned int doublechecklen = 0;
  240. cx = DES_CreateContext(key, iv, mode, PR_FALSE);
  241. if (cx == NULL) {
  242. goto loser;
  243. }
  244. rv = DES_Decrypt(cx, output, outputlen, maxoutputlen,
  245. input, inputlen);
  246. if (rv != SECSuccess) {
  247. goto loser;
  248. }
  249. if (*outputlen != inputlen) {
  250. goto loser;
  251. }
  252. DES_DestroyContext(cx, PR_TRUE);
  253. cx = NULL;
  254. /*
  255. * Doublecheck our result by encrypting the plaintext and
  256. * compare the output with the input ciphertext.
  257. */
  258. cx = DES_CreateContext(key, iv, mode, PR_TRUE);
  259. if (cx == NULL) {
  260. goto loser;
  261. }
  262. rv = DES_Encrypt(cx, doublecheck, &doublechecklen, sizeof doublecheck,
  263. output, *outputlen);
  264. if (rv != SECSuccess) {
  265. goto loser;
  266. }
  267. if (doublechecklen != *outputlen) {
  268. goto loser;
  269. }
  270. DES_DestroyContext(cx, PR_TRUE);
  271. cx = NULL;
  272. if (memcmp(doublecheck, input, inputlen) != 0) {
  273. goto loser;
  274. }
  275. rv = SECSuccess;
  276. loser:
  277. if (cx != NULL) {
  278. DES_DestroyContext(cx, PR_TRUE);
  279. }
  280. return rv;
  281. }
  282. /*
  283. * Perform the TDEA Known Answer Test (KAT) or Multi-block Message
  284. * Test (MMT) in ECB or CBC mode. The KAT (there are five types)
  285. * and MMT have the same structure: given the key and IV (CBC mode
  286. * only), encrypt the given plaintext or decrypt the given ciphertext.
  287. * So we can handle them the same way.
  288. *
  289. * reqfn is the pathname of the REQUEST file.
  290. *
  291. * The output RESPONSE file is written to stdout.
  292. */
  293. void
  294. tdea_kat_mmt(char *reqfn)
  295. {
  296. char buf[180]; /* holds one line from the input REQUEST file.
  297. * needs to be large enough to hold the longest
  298. * line "CIPHERTEXT = <180 hex digits>\n".
  299. */
  300. FILE *req; /* input stream from the REQUEST file */
  301. FILE *resp; /* output stream to the RESPONSE file */
  302. int i, j;
  303. int mode; /* NSS_DES_EDE3 (ECB) or NSS_DES_EDE3_CBC */
  304. int crypt = DECRYPT; /* 1 means encrypt, 0 means decrypt */
  305. unsigned char key[24]; /* TDEA 3 key bundle */
  306. unsigned int numKeys = 0;
  307. unsigned char iv[8]; /* for all modes except ECB */
  308. unsigned char plaintext[8*20]; /* 1 to 20 blocks */
  309. unsigned int plaintextlen;
  310. unsigned char ciphertext[8*20]; /* 1 to 20 blocks */
  311. unsigned int ciphertextlen;
  312. SECStatus rv;
  313. req = fopen(reqfn, "r");
  314. resp = stdout;
  315. while (fgets(buf, sizeof buf, req) != NULL) {
  316. /* a comment or blank line */
  317. if (buf[0] == '#' || buf[0] == '\n') {
  318. fputs(buf, resp);
  319. continue;
  320. }
  321. /* [ENCRYPT] or [DECRYPT] */
  322. if (buf[0] == '[') {
  323. if (strncmp(&buf[1], "ENCRYPT", 7) == 0) {
  324. crypt = ENCRYPT;
  325. } else {
  326. crypt = DECRYPT;
  327. }
  328. fputs(buf, resp);
  329. continue;
  330. }
  331. /* NumKeys */
  332. if (strncmp(&buf[0], "NumKeys", 7) == 0) {
  333. i = 7;
  334. while (isspace(buf[i]) || buf[i] == '=') {
  335. i++;
  336. }
  337. numKeys = buf[i];
  338. fputs(buf, resp);
  339. continue;
  340. }
  341. /* "COUNT = x" begins a new data set */
  342. if (strncmp(buf, "COUNT", 5) == 0) {
  343. /* mode defaults to ECB, if dataset has IV mode will be set CBC */
  344. mode = NSS_DES_EDE3;
  345. /* zeroize the variables for the test with this data set */
  346. memset(key, 0, sizeof key);
  347. memset(iv, 0, sizeof iv);
  348. memset(plaintext, 0, sizeof plaintext);
  349. plaintextlen = 0;
  350. memset(ciphertext, 0, sizeof ciphertext);
  351. ciphertextlen = 0;
  352. fputs(buf, resp);
  353. continue;
  354. }
  355. if (numKeys == 0) {
  356. if (strncmp(buf, "KEYs", 4) == 0) {
  357. i = 4;
  358. while (isspace(buf[i]) || buf[i] == '=') {
  359. i++;
  360. }
  361. for (j=0; isxdigit(buf[i]); i+=2,j++) {
  362. hex_to_byteval(&buf[i], &key[j]);
  363. key[j+8] = key[j];
  364. key[j+16] = key[j];
  365. }
  366. fputs(buf, resp);
  367. continue;
  368. }
  369. } else {
  370. /* KEY1 = ... */
  371. if (strncmp(buf, "KEY1", 4) == 0) {
  372. i = 4;
  373. while (isspace(buf[i]) || buf[i] == '=') {
  374. i++;
  375. }
  376. for (j=0; isxdigit(buf[i]); i+=2,j++) {
  377. hex_to_byteval(&buf[i], &key[j]);
  378. }
  379. fputs(buf, resp);
  380. continue;
  381. }
  382. /* KEY2 = ... */
  383. if (strncmp(buf, "KEY2", 4) == 0) {
  384. i = 4;
  385. while (isspace(buf[i]) || buf[i] == '=') {
  386. i++;
  387. }
  388. for (j=8; isxdigit(buf[i]); i+=2,j++) {
  389. hex_to_byteval(&buf[i], &key[j]);
  390. }
  391. fputs(buf, resp);
  392. continue;
  393. }
  394. /* KEY3 = ... */
  395. if (strncmp(buf, "KEY3", 4) == 0) {
  396. i = 4;
  397. while (isspace(buf[i]) || buf[i] == '=') {
  398. i++;
  399. }
  400. for (j=16; isxdigit(buf[i]); i+=2,j++) {
  401. hex_to_byteval(&buf[i], &key[j]);
  402. }
  403. fputs(buf, resp);
  404. continue;
  405. }
  406. }
  407. /* IV = ... */
  408. if (strncmp(buf, "IV", 2) == 0) {
  409. mode = NSS_DES_EDE3_CBC;
  410. i = 2;
  411. while (isspace(buf[i]) || buf[i] == '=') {
  412. i++;
  413. }
  414. for (j=0; j<sizeof iv; i+=2,j++) {
  415. hex_to_byteval(&buf[i], &iv[j]);
  416. }
  417. fputs(buf, resp);
  418. continue;
  419. }
  420. /* PLAINTEXT = ... */
  421. if (strncmp(buf, "PLAINTEXT", 9) == 0) {
  422. /* sanity check */
  423. if (crypt != ENCRYPT) {
  424. goto loser;
  425. }
  426. i = 9;
  427. while (isspace(buf[i]) || buf[i] == '=') {
  428. i++;
  429. }
  430. for (j=0; isxdigit(buf[i]); i+=2,j++) {
  431. hex_to_byteval(&buf[i], &plaintext[j]);
  432. }
  433. plaintextlen = j;
  434. rv = tdea_encrypt_buf(mode, key,
  435. (mode == NSS_DES_EDE3) ? NULL : iv,
  436. ciphertext, &ciphertextlen, sizeof ciphertext,
  437. plaintext, plaintextlen);
  438. if (rv != SECSuccess) {
  439. goto loser;
  440. }
  441. fputs(buf, resp);
  442. fputs("CIPHERTEXT = ", resp);
  443. to_hex_str(buf, ciphertext, ciphertextlen);
  444. fputs(buf, resp);
  445. fputc('\n', resp);
  446. continue;
  447. }
  448. /* CIPHERTEXT = ... */
  449. if (strncmp(buf, "CIPHERTEXT", 10) == 0) {
  450. /* sanity check */
  451. if (crypt != DECRYPT) {
  452. goto loser;
  453. }
  454. i = 10;
  455. while (isspace(buf[i]) || buf[i] == '=') {
  456. i++;
  457. }
  458. for (j=0; isxdigit(buf[i]); i+=2,j++) {
  459. hex_to_byteval(&buf[i], &ciphertext[j]);
  460. }
  461. ciphertextlen = j;
  462. rv = tdea_decrypt_buf(mode, key,
  463. (mode == NSS_DES_EDE3) ? NULL : iv,
  464. plaintext, &plaintextlen, sizeof plaintext,
  465. ciphertext, ciphertextlen);
  466. if (rv != SECSuccess) {
  467. goto loser;
  468. }
  469. fputs(buf, resp);
  470. fputs("PLAINTEXT = ", resp);
  471. to_hex_str(buf, plaintext, plaintextlen);
  472. fputs(buf, resp);
  473. fputc('\n', resp);
  474. continue;
  475. }
  476. }
  477. loser:
  478. fclose(req);
  479. }
  480. /*
  481. * Set the parity bit for the given byte
  482. */
  483. BYTE odd_parity( BYTE in)
  484. {
  485. BYTE out = in;
  486. in ^= in >> 4;
  487. in ^= in >> 2;
  488. in ^= in >> 1;
  489. return (BYTE)(out ^ !(in & 1));
  490. }
  491. /*
  492. * Generate Keys [i+1] from Key[i], PT/CT[j-2], PT/CT[j-1], and PT/CT[j]
  493. * for TDEA Monte Carlo Test (MCT) in ECB and CBC modes.
  494. */
  495. void
  496. tdea_mct_next_keys(unsigned char *key,
  497. const unsigned char *text_2, const unsigned char *text_1,
  498. const unsigned char *text, unsigned int numKeys)
  499. {
  500. int k;
  501. /* key1[i+1] = key1[i] xor PT/CT[j] */
  502. for (k=0; k<8; k++) {
  503. key[k] ^= text[k];
  504. }
  505. /* key2 */
  506. if (numKeys == 2 || numKeys == 3) {
  507. /* key2 independent */
  508. for (k=8; k<16; k++) {
  509. /* key2[i+1] = KEY2[i] xor PT/CT[j-1] */
  510. key[k] ^= text_1[k-8];
  511. }
  512. } else {
  513. /* key2 == key 1 */
  514. for (k=8; k<16; k++) {
  515. /* key2[i+1] = KEY2[i] xor PT/CT[j] */
  516. key[k] = key[k-8];
  517. }
  518. }
  519. /* key3 */
  520. if (numKeys == 1 || numKeys == 2) {
  521. /* key3 == key 1 */
  522. for (k=16; k<24; k++) {
  523. /* key3[i+1] = KEY3[i] xor PT/CT[j] */
  524. key[k] = key[k-16];
  525. }
  526. } else {
  527. /* key3 independent */
  528. for (k=16; k<24; k++) {
  529. /* key3[i+1] = KEY3[i] xor PT/CT[j-2] */
  530. key[k] ^= text_2[k-16];
  531. }
  532. }
  533. /* set the parity bits */
  534. for (k=0; k<24; k++) {
  535. key[k] = odd_parity(key[k]);
  536. }
  537. }
  538. /*
  539. * Perform the Monte Carlo Test
  540. *
  541. * mode = NSS_DES_EDE3 or NSS_DES_EDE3_CBC
  542. * crypt = ENCRYPT || DECRYPT
  543. * inputtext = plaintext or Cyphertext depending on the value of crypt
  544. * inputlength is expected to be size 8 bytes
  545. * iv = needs to be set for NSS_DES_EDE3_CBC mode
  546. * resp = is the output response file.
  547. */
  548. void
  549. tdea_mct_test(int mode, unsigned char* key, unsigned int numKeys,
  550. unsigned int crypt, unsigned char* inputtext,
  551. unsigned int inputlength, unsigned char* iv, FILE *resp) {
  552. int i, j;
  553. unsigned char outputtext_1[8]; /* PT/CT[j-1] */
  554. unsigned char outputtext_2[8]; /* PT/CT[j-2] */
  555. char buf[80]; /* holds one line from the input REQUEST file. */
  556. unsigned int outputlen;
  557. unsigned char outputtext[8];
  558. SECStatus rv;
  559. if (mode == NSS_DES_EDE3 && iv != NULL) {
  560. printf("IV must be NULL for NSS_DES_EDE3 mode");
  561. goto loser;
  562. } else if (mode == NSS_DES_EDE3_CBC && iv == NULL) {
  563. printf("IV must not be NULL for NSS_DES_EDE3_CBC mode");
  564. goto loser;
  565. }
  566. /* loop 400 times */
  567. for (i=0; i<400; i++) {
  568. /* if i == 0 CV[0] = IV not necessary */
  569. /* record the count and key values and plainText */
  570. sprintf(buf, "COUNT = %d\n", i);
  571. fputs(buf, resp);
  572. /* Output KEY1[i] */
  573. fputs("KEY1 = ", resp);
  574. to_hex_str(buf, key, 8);
  575. fputs(buf, resp);
  576. fputc('\n', resp);
  577. /* Output KEY2[i] */
  578. fputs("KEY2 = ", resp);
  579. to_hex_str(buf, &key[8], 8);
  580. fputs(buf, resp);
  581. fputc('\n', resp);
  582. /* Output KEY3[i] */
  583. fputs("KEY3 = ", resp);
  584. to_hex_str(buf, &key[16], 8);
  585. fputs(buf, resp);
  586. fputc('\n', resp);
  587. if (mode == NSS_DES_EDE3_CBC) {
  588. /* Output CV[i] */
  589. fputs("IV = ", resp);
  590. to_hex_str(buf, iv, 8);
  591. fputs(buf, resp);
  592. fputc('\n', resp);
  593. }
  594. if (crypt == ENCRYPT) {
  595. /* Output PT[0] */
  596. fputs("PLAINTEXT = ", resp);
  597. } else {
  598. /* Output CT[0] */
  599. fputs("CIPHERTEXT = ", resp);
  600. }
  601. to_hex_str(buf, inputtext, inputlength);
  602. fputs(buf, resp);
  603. fputc('\n', resp);
  604. /* loop 10,000 times */
  605. for (j=0; j<10000; j++) {
  606. outputlen = 0;
  607. if (crypt == ENCRYPT) {
  608. /* inputtext == ciphertext outputtext == plaintext*/
  609. rv = tdea_encrypt_buf(mode, key,
  610. (mode == NSS_DES_EDE3) ? NULL : iv,
  611. outputtext, &outputlen, 8,
  612. inputtext, 8);
  613. } else {
  614. /* inputtext == plaintext outputtext == ciphertext */
  615. rv = tdea_decrypt_buf(mode, key,
  616. (mode == NSS_DES_EDE3) ? NULL : iv,
  617. outputtext, &outputlen, 8,
  618. inputtext, 8);
  619. }
  620. if (rv != SECSuccess) {
  621. goto loser;
  622. }
  623. if (outputlen != inputlength) {
  624. goto loser;
  625. }
  626. if (mode == NSS_DES_EDE3_CBC) {
  627. if (crypt == ENCRYPT) {
  628. if (j == 0) {
  629. /*P[j+1] = CV[0] */
  630. memcpy(inputtext, iv, 8);
  631. } else {
  632. /* p[j+1] = C[j-1] */
  633. memcpy(inputtext, outputtext_1, 8);
  634. }
  635. /* CV[j+1] = C[j] */
  636. memcpy(iv, outputtext, 8);
  637. if (j != 9999) {
  638. /* save C[j-1] */
  639. memcpy(outputtext_1, outputtext, 8);
  640. }
  641. } else { /* DECRYPT */
  642. /* CV[j+1] = C[j] */
  643. memcpy(iv, inputtext, 8);
  644. /* C[j+1] = P[j] */
  645. memcpy(inputtext, outputtext, 8);
  646. }
  647. } else {
  648. /* ECB mode PT/CT[j+1] = CT/PT[j] */
  649. memcpy(inputtext, outputtext, 8);
  650. }
  651. /* Save PT/CT[j-2] and PT/CT[j-1] */
  652. if (j==9997) memcpy(outputtext_2, outputtext, 8);
  653. if (j==9998) memcpy(outputtext_1, outputtext, 8);
  654. /* done at the end of the for(j) loop */
  655. }
  656. if (crypt == ENCRYPT) {
  657. /* Output CT[j] */
  658. fputs("CIPHERTEXT = ", resp);
  659. } else {
  660. /* Output PT[j] */
  661. fputs("PLAINTEXT = ", resp);
  662. }
  663. to_hex_str(buf, outputtext, 8);
  664. fputs(buf, resp);
  665. fputc('\n', resp);
  666. /* Key[i+1] = Key[i] xor ... outputtext_2 == PT/CT[j-2]
  667. * outputtext_1 == PT/CT[j-1] outputtext == PT/CT[j]
  668. */
  669. tdea_mct_next_keys(key, outputtext_2,
  670. outputtext_1, outputtext, numKeys);
  671. if (mode == NSS_DES_EDE3_CBC) {
  672. /* taken care of in the j=9999 iteration */
  673. if (crypt == ENCRYPT) {
  674. /* P[i] = C[j-1] */
  675. /* CV[i] = C[j] */
  676. } else {
  677. /* taken care of in the j=9999 iteration */
  678. /* CV[i] = C[j] */
  679. /* C[i] = P[j] */
  680. }
  681. } else {
  682. /* ECB PT/CT[i] = PT/CT[j] */
  683. memcpy(inputtext, outputtext, 8);
  684. }
  685. /* done at the end of the for(i) loop */
  686. fputc('\n', resp);
  687. }
  688. loser:
  689. return;
  690. }
  691. /*
  692. * Perform the TDEA Monte Carlo Test (MCT) in ECB/CBC modes.
  693. * by gathering the input from the request file, and then
  694. * calling tdea_mct_test.
  695. *
  696. * reqfn is the pathname of the input REQUEST file.
  697. *
  698. * The output RESPONSE file is written to stdout.
  699. */
  700. void
  701. tdea_mct(int mode, char *reqfn)
  702. {
  703. int i, j;
  704. char buf[80]; /* holds one line from the input REQUEST file. */
  705. FILE *req; /* input stream from the REQUEST file */
  706. FILE *resp; /* output stream to the RESPONSE file */
  707. unsigned int crypt = 0; /* 1 means encrypt, 0 means decrypt */
  708. unsigned char key[24]; /* TDEA 3 key bundle */
  709. unsigned int numKeys = 0;
  710. unsigned char plaintext[8]; /* PT[j] */
  711. unsigned char ciphertext[8]; /* CT[j] */
  712. unsigned char iv[8];
  713. /* zeroize the variables for the test with this data set */
  714. memset(key, 0, sizeof key);
  715. memset(plaintext, 0, sizeof plaintext);
  716. memset(ciphertext, 0, sizeof ciphertext);
  717. memset(iv, 0, sizeof iv);
  718. req = fopen(reqfn, "r");
  719. resp = stdout;
  720. while (fgets(buf, sizeof buf, req) != NULL) {
  721. /* a comment or blank line */
  722. if (buf[0] == '#' || buf[0] == '\n') {
  723. fputs(buf, resp);
  724. continue;
  725. }
  726. /* [ENCRYPT] or [DECRYPT] */
  727. if (buf[0] == '[') {
  728. if (strncmp(&buf[1], "ENCRYPT", 7) == 0) {
  729. crypt = ENCRYPT;
  730. } else {
  731. crypt = DECRYPT;
  732. }
  733. fputs(buf, resp);
  734. continue;
  735. }
  736. /* NumKeys */
  737. if (strncmp(&buf[0], "NumKeys", 7) == 0) {
  738. i = 7;
  739. while (isspace(buf[i]) || buf[i] == '=') {
  740. i++;
  741. }
  742. numKeys = atoi(&buf[i]);
  743. continue;
  744. }
  745. /* KEY1 = ... */
  746. if (strncmp(buf, "KEY1", 4) == 0) {
  747. i = 4;
  748. while (isspace(buf[i]) || buf[i] == '=') {
  749. i++;
  750. }
  751. for (j=0; isxdigit(buf[i]); i+=2,j++) {
  752. hex_to_byteval(&buf[i], &key[j]);
  753. }
  754. continue;
  755. }
  756. /* KEY2 = ... */
  757. if (strncmp(buf, "KEY2", 4) == 0) {
  758. i = 4;
  759. while (isspace(buf[i]) || buf[i] == '=') {
  760. i++;
  761. }
  762. for (j=8; isxdigit(buf[i]); i+=2,j++) {
  763. hex_to_byteval(&buf[i], &key[j]);
  764. }
  765. continue;
  766. }
  767. /* KEY3 = ... */
  768. if (strncmp(buf, "KEY3", 4) == 0) {
  769. i = 4;
  770. while (isspace(buf[i]) || buf[i] == '=') {
  771. i++;
  772. }
  773. for (j=16; isxdigit(buf[i]); i+=2,j++) {
  774. hex_to_byteval(&buf[i], &key[j]);
  775. }
  776. continue;
  777. }
  778. /* IV = ... */
  779. if (strncmp(buf, "IV", 2) == 0) {
  780. i = 2;
  781. while (isspace(buf[i]) || buf[i] == '=') {
  782. i++;
  783. }
  784. for (j=0; j<sizeof iv; i+=2,j++) {
  785. hex_to_byteval(&buf[i], &iv[j]);
  786. }
  787. continue;
  788. }
  789. /* PLAINTEXT = ... */
  790. if (strncmp(buf, "PLAINTEXT", 9) == 0) {
  791. /* sanity check */
  792. if (crypt != ENCRYPT) {
  793. goto loser;
  794. }
  795. /* PT[0] = PT */
  796. i = 9;
  797. while (isspace(buf[i]) || buf[i] == '=') {
  798. i++;
  799. }
  800. for (j=0; j<sizeof plaintext; i+=2,j++) {
  801. hex_to_byteval(&buf[i], &plaintext[j]);
  802. }
  803. /* do the Monte Carlo test */
  804. if (mode==NSS_DES_EDE3) {
  805. tdea_mct_test(NSS_DES_EDE3, key, numKeys, crypt, plaintext, sizeof plaintext, NULL, resp);
  806. } else {
  807. tdea_mct_test(NSS_DES_EDE3_CBC, key, numKeys, crypt, plaintext, sizeof plaintext, iv, resp);
  808. }
  809. continue;
  810. }
  811. /* CIPHERTEXT = ... */
  812. if (strncmp(buf, "CIPHERTEXT", 10) == 0) {
  813. /* sanity check */
  814. if (crypt != DECRYPT) {
  815. goto loser;
  816. }
  817. /* CT[0] = CT */
  818. i = 10;
  819. while (isspace(buf[i]) || buf[i] == '=') {
  820. i++;
  821. }
  822. for (j=0; isxdigit(buf[i]); i+=2,j++) {
  823. hex_to_byteval(&buf[i], &ciphertext[j]);
  824. }
  825. /* do the Monte Carlo test */
  826. if (mode==NSS_DES_EDE3) {
  827. tdea_mct_test(NSS_DES_EDE3, key, numKeys, crypt, ciphertext, sizeof ciphertext, NULL, resp);
  828. } else {
  829. tdea_mct_test(NSS_DES_EDE3_CBC, key, numKeys, crypt, ciphertext, sizeof ciphertext, iv, resp);
  830. }
  831. continue;
  832. }
  833. }
  834. loser:
  835. fclose(req);
  836. }
  837. SECStatus
  838. aes_encrypt_buf(
  839. int mode,
  840. const unsigned char *key, unsigned int keysize,
  841. const unsigned char *iv,
  842. unsigned char *output, unsigned int *outputlen, unsigned int maxoutputlen,
  843. const unsigned char *input, unsigned int inputlen)
  844. {
  845. SECStatus rv = SECFailure;
  846. AESContext *cx;
  847. unsigned char doublecheck[10*16]; /* 1 to 10 blocks */
  848. unsigned int doublechecklen = 0;
  849. cx = AES_CreateContext(key, iv, mode, PR_TRUE, keysize, 16);
  850. if (cx == NULL) {
  851. goto loser;
  852. }
  853. rv = AES_Encrypt(cx, output, outputlen, maxoutputlen, input, inputlen);
  854. if (rv != SECSuccess) {
  855. goto loser;
  856. }
  857. if (*outputlen != inputlen) {
  858. goto loser;
  859. }
  860. AES_DestroyContext(cx, PR_TRUE);
  861. cx = NULL;
  862. /*
  863. * Doublecheck our result by decrypting the ciphertext and
  864. * compare the output with the input plaintext.
  865. */
  866. cx = AES_CreateContext(key, iv, mode, PR_FALSE, keysize, 16);
  867. if (cx == NULL) {
  868. goto loser;
  869. }
  870. rv = AES_Decrypt(cx, doublecheck, &doublechecklen, sizeof doublecheck,
  871. output, *outputlen);
  872. if (rv != SECSuccess) {
  873. goto loser;
  874. }
  875. if (doublechecklen != *outputlen) {
  876. goto loser;
  877. }
  878. AES_DestroyContext(cx, PR_TRUE);
  879. cx = NULL;
  880. if (memcmp(doublecheck, input, inputlen) != 0) {
  881. goto loser;
  882. }
  883. rv = SECSuccess;
  884. loser:
  885. if (cx != NULL) {
  886. AES_DestroyContext(cx, PR_TRUE);
  887. }
  888. return rv;
  889. }
  890. SECStatus
  891. aes_decrypt_buf(
  892. int mode,
  893. const unsigned char *key, unsigned int keysize,
  894. const unsigned char *iv,
  895. unsigned char *output, unsigned int *outputlen, unsigned int maxoutputlen,
  896. const unsigned char *input, unsigned int inputlen)
  897. {
  898. SECStatus rv = SECFailure;
  899. AESContext *cx;
  900. unsigned char doublecheck[10*16]; /* 1 to 10 blocks */
  901. unsigned int doublechecklen = 0;
  902. cx = AES_CreateContext(key, iv, mode, PR_FALSE, keysize, 16);
  903. if (cx == NULL) {
  904. goto loser;
  905. }
  906. rv = AES_Decrypt(cx, output, outputlen, maxoutputlen,
  907. input, inputlen);
  908. if (rv != SECSuccess) {
  909. goto loser;
  910. }
  911. if (*outputlen != inputlen) {
  912. goto loser;
  913. }
  914. AES_DestroyContext(cx, PR_TRUE);
  915. cx = NULL;
  916. /*
  917. * Doublecheck our result by encrypting the plaintext and
  918. * compare the output with the input ciphertext.
  919. */
  920. cx = AES_CreateContext(key, iv, mode, PR_TRUE, keysize, 16);
  921. if (cx == NULL) {
  922. goto loser;
  923. }
  924. rv = AES_Encrypt(cx, doublecheck, &doublechecklen, sizeof doublecheck,
  925. output, *outputlen);
  926. if (rv != SECSuccess) {
  927. goto loser;
  928. }
  929. if (doublechecklen != *outputlen) {
  930. goto loser;
  931. }
  932. AES_DestroyContext(cx, PR_TRUE);
  933. cx = NULL;
  934. if (memcmp(doublecheck, input, inputlen) != 0) {
  935. goto loser;
  936. }
  937. rv = SECSuccess;
  938. loser:
  939. if (cx != NULL) {
  940. AES_DestroyContext(cx, PR_TRUE);
  941. }
  942. return rv;
  943. }
  944. /*
  945. * Perform the AES Known Answer Test (KAT) or Multi-block Message
  946. * Test (MMT) in ECB or CBC mode. The KAT (there are four types)
  947. * and MMT have the same structure: given the key and IV (CBC mode
  948. * only), encrypt the given plaintext or decrypt the given ciphertext.
  949. * So we can handle them the same way.
  950. *
  951. * reqfn is the pathname of the REQUEST file.
  952. *
  953. * The output RESPONSE file is written to stdout.
  954. */
  955. void
  956. aes_kat_mmt(char *reqfn)
  957. {
  958. char buf[512]; /* holds one line from the input REQUEST file.
  959. * needs to be large enough to hold the longest
  960. * line "CIPHERTEXT = <320 hex digits>\n".
  961. */
  962. FILE *aesreq; /* input stream from the REQUEST file */
  963. FILE *aesresp; /* output stream to the RESPONSE file */
  964. int i, j;
  965. int mode; /* NSS_AES (ECB) or NSS_AES_CBC */
  966. int encrypt = 0; /* 1 means encrypt, 0 means decrypt */
  967. unsigned char key[32]; /* 128, 192, or 256 bits */
  968. unsigned int keysize;
  969. unsigned char iv[16]; /* for all modes except ECB */
  970. unsigned char plaintext[10*16]; /* 1 to 10 blocks */
  971. unsigned int plaintextlen;
  972. unsigned char ciphertext[10*16]; /* 1 to 10 blocks */
  973. unsigned int ciphertextlen;
  974. SECStatus rv;
  975. aesreq = fopen(reqfn, "r");
  976. aesresp = stdout;
  977. while (fgets(buf, sizeof buf, aesreq) != NULL) {
  978. /* a comment or blank line */
  979. if (buf[0] == '#' || buf[0] == '\n') {
  980. fputs(buf, aesresp);
  981. continue;
  982. }
  983. /* [ENCRYPT] or [DECRYPT] */
  984. if (buf[0] == '[') {
  985. if (strncmp(&buf[1], "ENCRYPT", 7) == 0) {
  986. encrypt = 1;
  987. } else {
  988. encrypt = 0;
  989. }
  990. fputs(buf, aesresp);
  991. continue;
  992. }
  993. /* "COUNT = x" begins a new data set */
  994. if (strncmp(buf, "COUNT", 5) == 0) {
  995. mode = NSS_AES;
  996. /* zeroize the variables for the test with this data set */
  997. memset(key, 0, sizeof key);
  998. keysize = 0;
  999. memset(iv, 0, sizeof iv);
  1000. memset(plaintext, 0, sizeof plaintext);
  1001. plaintextlen = 0;
  1002. memset(ciphertext, 0, sizeof ciphertext);
  1003. ciphertextlen = 0;
  1004. fputs(buf, aesresp);
  1005. continue;
  1006. }
  1007. /* KEY = ... */
  1008. if (strncmp(buf, "KEY", 3) == 0) {
  1009. i = 3;
  1010. while (isspace(buf[i]) || buf[i] == '=') {
  1011. i++;
  1012. }
  1013. for (j=0; isxdigit(buf[i]); i+=2,j++) {
  1014. hex_to_byteval(&buf[i], &key[j]);
  1015. }
  1016. keysize = j;
  1017. fputs(buf, aesresp);
  1018. continue;
  1019. }
  1020. /* IV = ... */
  1021. if (strncmp(buf, "IV", 2) == 0) {
  1022. mode = NSS_AES_CBC;
  1023. i = 2;
  1024. while (isspace(buf[i]) || buf[i] == '=') {
  1025. i++;
  1026. }
  1027. for (j=0; j<sizeof iv; i+=2,j++) {
  1028. hex_to_byteval(&buf[i], &iv[j]);
  1029. }
  1030. fputs(buf, aesresp);
  1031. continue;
  1032. }
  1033. /* PLAINTEXT = ... */
  1034. if (strncmp(buf, "PLAINTEXT", 9) == 0) {
  1035. /* sanity check */
  1036. if (!encrypt) {
  1037. goto loser;
  1038. }
  1039. i = 9;
  1040. while (isspace(buf[i]) || buf[i] == '=') {
  1041. i++;
  1042. }
  1043. for (j=0; isxdigit(buf[i]); i+=2,j++) {
  1044. hex_to_byteval(&buf[i], &plaintext[j]);
  1045. }
  1046. plaintextlen = j;
  1047. rv = aes_encrypt_buf(mode, key, keysize,
  1048. (mode == NSS_AES) ? NULL : iv,
  1049. ciphertext, &ciphertextlen, sizeof ciphertext,
  1050. plaintext, plaintextlen);
  1051. if (rv != SECSuccess) {
  1052. goto loser;
  1053. }
  1054. fputs(buf, aesresp);
  1055. fputs("CIPHERTEXT = ", aesresp);
  1056. to_hex_str(buf, ciphertext, ciphertextlen);
  1057. fputs(buf, aesresp);
  1058. fputc('\n', aesresp);
  1059. continue;
  1060. }
  1061. /* CIPHERTEXT = ... */
  1062. if (strncmp(buf, "CIPHERTEXT", 10) == 0) {
  1063. /* sanity check */
  1064. if (encrypt) {
  1065. goto loser;
  1066. }
  1067. i = 10;
  1068. while (isspace(buf[i]) || buf[i] == '=') {
  1069. i++;
  1070. }
  1071. for (j=0; isxdigit(buf[i]); i+=2,j++) {
  1072. hex_to_byteval(&buf[i], &ciphertext[j]);
  1073. }
  1074. ciphertextlen = j;
  1075. rv = aes_decrypt_buf(mode, key, keysize,
  1076. (mode == NSS_AES) ? NULL : iv,
  1077. plaintext, &plaintextlen, sizeof plaintext,
  1078. ciphertext, ciphertextlen);
  1079. if (rv != SECSuccess) {
  1080. goto loser;
  1081. }
  1082. fputs(buf, aesresp);
  1083. fputs("PLAINTEXT = ", aesresp);
  1084. to_hex_str(buf, plaintext, plaintextlen);
  1085. fputs(buf, aesresp);
  1086. fputc('\n', aesresp);
  1087. continue;
  1088. }
  1089. }
  1090. loser:
  1091. fclose(aesreq);
  1092. }
  1093. /*
  1094. * Generate Key[i+1] from Key[i], CT[j-1], and CT[j] for AES Monte Carlo
  1095. * Test (MCT) in ECB and CBC modes.
  1096. */
  1097. void
  1098. aes_mct_next_key(unsigned char *key, unsigned int keysize,
  1099. const unsigned char *ciphertext_1, const unsigned char *ciphertext)
  1100. {
  1101. int k;
  1102. switch (keysize) {
  1103. case 16: /* 128-bit key */
  1104. /* Key[i+1] = Key[i] xor CT[j] */
  1105. for (k=0; k<16; k++) {
  1106. key[k] ^= ciphertext[k];
  1107. }
  1108. break;
  1109. case 24: /* 192-bit key */
  1110. /*
  1111. * Key[i+1] = Key[i] xor (last 64-bits of
  1112. * CT[j-1] || CT[j])
  1113. */
  1114. for (k=0; k<8; k++) {
  1115. key[k] ^= ciphertext_1[k+8];
  1116. }
  1117. for (k=8; k<24; k++) {
  1118. key[k] ^= ciphertext[k-8];
  1119. }
  1120. break;
  1121. case 32: /* 256-bit key */
  1122. /* Key[i+1] = Key[i] xor (CT[j-1] || CT[j]) */
  1123. for (k=0; k<16; k++) {
  1124. key[k] ^= ciphertext_1[k];
  1125. }
  1126. for (k=16; k<32; k++) {
  1127. key[k] ^= ciphertext[k-16];
  1128. }
  1129. break;
  1130. }
  1131. }
  1132. /*
  1133. * Perform the AES Monte Carlo Test (MCT) in ECB mode. MCT exercises
  1134. * our AES code in streaming mode because the plaintext or ciphertext
  1135. * is generated block by block as we go, so we can't collect all the
  1136. * plaintext or ciphertext in one buffer and encrypt or decrypt it in
  1137. * one shot.
  1138. *
  1139. * reqfn is the pathname of the input REQUEST file.
  1140. *
  1141. * The output RESPONSE file is written to stdout.
  1142. */
  1143. void
  1144. aes_ecb_mct(char *reqfn)
  1145. {
  1146. char buf[80]; /* holds one line from the input REQUEST file.
  1147. * needs to be large enough to hold the longest
  1148. * line "KEY = <64 hex digits>\n".
  1149. */
  1150. FILE *aesreq; /* input stream from the REQUEST file */
  1151. FILE *aesresp; /* output stream to the RESPONSE file */
  1152. int i, j;
  1153. int encrypt = 0; /* 1 means encrypt, 0 means decrypt */
  1154. unsigned char key[32]; /* 128, 192, or 256 bits */
  1155. unsigned int keysize;
  1156. unsigned char plaintext[16]; /* PT[j] */
  1157. unsigned char plaintext_1[16]; /* PT[j-1] */
  1158. unsigned char ciphertext[16]; /* CT[j] */
  1159. unsigned char ciphertext_1[16]; /* CT[j-1] */
  1160. unsigned char doublecheck[16];
  1161. unsigned int outputlen;
  1162. AESContext *cx = NULL; /* the operation being tested */
  1163. AESContext *cx2 = NULL; /* the inverse operation done in parallel
  1164. * to doublecheck our result.
  1165. */
  1166. SECStatus rv;
  1167. aesreq = fopen(reqfn, "r");
  1168. aesresp = stdout;
  1169. while (fgets(buf, sizeof buf, aesreq) != NULL) {
  1170. /* a comment or blank line */
  1171. if (buf[0] == '#' || buf[0] == '\n') {
  1172. fputs(buf, aesresp);
  1173. continue;
  1174. }
  1175. /* [ENCRYPT] or [DECRYPT] */
  1176. if (buf[0] == '[') {
  1177. if (strncmp(&buf[1], "ENCRYPT", 7) == 0) {
  1178. encrypt = 1;
  1179. } else {
  1180. encrypt = 0;
  1181. }
  1182. fputs(buf, aesresp);
  1183. continue;
  1184. }
  1185. /* "COUNT = x" begins a new data set */
  1186. if (strncmp(buf, "COUNT", 5) == 0) {
  1187. /* zeroize the variables for the test with this data set */
  1188. memset(key, 0, sizeof key);
  1189. keysize = 0;
  1190. memset(plaintext, 0, sizeof plaintext);
  1191. memset(ciphertext, 0, sizeof ciphertext);
  1192. continue;
  1193. }
  1194. /* KEY = ... */
  1195. if (strncmp(buf, "KEY", 3) == 0) {
  1196. /* Key[0] = Key */
  1197. i = 3;
  1198. while (isspace(buf[i]) || buf[i] == '=') {
  1199. i++;
  1200. }
  1201. for (j=0; isxdigit(buf[i]); i+=2,j++) {
  1202. hex_to_byteval(&buf[i], &key[j]);
  1203. }
  1204. keysize = j;
  1205. continue;
  1206. }
  1207. /* PLAINTEXT = ... */
  1208. if (strncmp(buf, "PLAINTEXT", 9) == 0) {
  1209. /* sanity check */
  1210. if (!encrypt) {
  1211. goto loser;
  1212. }
  1213. /* PT[0] = PT */
  1214. i = 9;
  1215. while (isspace(buf[i]) || buf[i] == '=') {
  1216. i++;
  1217. }
  1218. for (j=0; j<sizeof plaintext; i+=2,j++) {
  1219. hex_to_byteval(&buf[i], &plaintext[j]);
  1220. }
  1221. for (i=0; i<100; i++) {
  1222. sprintf(buf, "COUNT = %d\n", i);
  1223. fputs(buf, aesresp);
  1224. /* Output Key[i] */
  1225. fputs("KEY = ", aesresp);
  1226. to_hex_str(buf, key, keysize);
  1227. fputs(buf, aesresp);
  1228. fputc('\n', aesresp);
  1229. /* Output PT[0] */
  1230. fputs("PLAINTEXT = ", aesresp);
  1231. to_hex_str(buf, plaintext, sizeof plaintext);
  1232. fputs(buf, aesresp);
  1233. fputc('\n', aesresp);
  1234. cx = AES_CreateContext(key, NULL, NSS_AES,
  1235. PR_TRUE, keysize, 16);
  1236. if (cx == NULL) {
  1237. goto loser;
  1238. }
  1239. /*
  1240. * doublecheck our result by decrypting the result
  1241. * and comparing the output with the plaintext.
  1242. */
  1243. cx2 = AES_CreateContext(key, NULL, NSS_AES,
  1244. PR_FALSE, keysize, 16);
  1245. if (cx2 == NULL) {
  1246. goto loser;
  1247. }
  1248. for (j=0; j<1000; j++) {
  1249. /* Save CT[j-1] */
  1250. memcpy(ciphertext_1, ciphertext, sizeof ciphertext);
  1251. /* CT[j] = AES(Key[i], PT[j]) */
  1252. outputlen = 0;
  1253. rv = AES_Encrypt(cx,
  1254. ciphertext, &outputlen, sizeof ciphertext,
  1255. plaintext, sizeof plaintext);
  1256. if (rv != SECSuccess) {
  1257. goto loser;
  1258. }
  1259. if (outputlen != sizeof plaintext) {
  1260. goto loser;
  1261. }
  1262. /* doublecheck our result */
  1263. outputlen = 0;
  1264. rv = AES_Decrypt(cx2,
  1265. doublecheck, &outputlen, sizeof doublecheck,
  1266. ciphertext, sizeof ciphertext);
  1267. if (rv != SECSuccess) {
  1268. goto loser;
  1269. }
  1270. if (outputlen != sizeof ciphertext) {
  1271. goto loser;
  1272. }
  1273. if (memcmp(doublecheck, plaintext, sizeof plaintext)) {
  1274. goto loser;
  1275. }
  1276. /* PT[j+1] = CT[j] */
  1277. memcpy(plaintext, ciphertext, sizeof plaintext);
  1278. }
  1279. AES_DestroyContext(cx, PR_TRUE);
  1280. cx = NULL;
  1281. AES_DestroyContext(cx2, PR_TRUE);
  1282. cx2 = NULL;
  1283. /* Output CT[j] */
  1284. fputs("CIPHERTEXT = ", aesresp);
  1285. to_hex_str(buf, ciphertext, sizeof ciphertext);
  1286. fputs(buf, aesresp);
  1287. fputc('\n', aesresp);
  1288. /* Key[i+1] = Key[i] xor ... */
  1289. aes_mct_next_key(key, keysize, ciphertext_1, ciphertext);
  1290. /* PT[0] = CT[j] */
  1291. /* done at the end of the for(j) loop */
  1292. fputc('\n', aesresp);
  1293. }
  1294. continue;
  1295. }
  1296. /* CIPHERTEXT = ... */
  1297. if (strncmp(buf, "CIPHERTEXT", 10) == 0) {
  1298. /* sanity check */
  1299. if (encrypt) {
  1300. goto loser;
  1301. }
  1302. /* CT[0] = CT */
  1303. i = 10;
  1304. while (isspace(buf[i]) || buf[i] == '=') {
  1305. i++;
  1306. }
  1307. for (j=0; isxdigit(buf[i]); i+=2,j++) {
  1308. hex_to_byteval(&buf[i], &ciphertext[j]);
  1309. }
  1310. for (i=0; i<100; i++) {
  1311. sprintf(buf, "COUNT = %d\n", i);
  1312. fputs(buf, aesresp);
  1313. /* Output Key[i] */
  1314. fputs("KEY = ", aesresp);
  1315. to_hex_str(buf, key, keysize);
  1316. fputs(buf, aesresp);
  1317. fputc('\n', aesresp);
  1318. /* Output CT[0] */
  1319. fputs("CIPHERTEXT = ", aesresp);
  1320. to_hex_str(buf, ciphertext, sizeof ciphertext);
  1321. fputs(buf, aesresp);
  1322. fputc('\n', aesresp);
  1323. cx = AES_CreateContext(key, NULL, NSS_AES,
  1324. PR_FALSE, keysize, 16);
  1325. if (cx == NULL) {
  1326. goto loser;
  1327. }
  1328. /*
  1329. * doublecheck our result by encrypting the result
  1330. * and comparing the output with the ciphertext.
  1331. */
  1332. cx2 = AES_CreateContext(key, NULL, NSS_AES,
  1333. PR_TRUE, keysize, 16);
  1334. if (cx2 == NULL) {
  1335. goto loser;
  1336. }
  1337. for (j=0; j<1000; j++) {
  1338. /* Save PT[j-1] */
  1339. memcpy(plaintext_1, plaintext, sizeof plaintext);
  1340. /* PT[j] = AES(Key[i], CT[j]) */
  1341. outputlen = 0;
  1342. rv = AES_Decrypt(cx,
  1343. plaintext, &outputlen, sizeof plaintext,
  1344. ciphertext, sizeof ciphertext);
  1345. if (rv != SECSuccess) {
  1346. goto loser;
  1347. }
  1348. if (outputlen != sizeof ciphertext) {
  1349. goto loser;
  1350. }
  1351. /* doublecheck our result */
  1352. outputlen = 0;
  1353. rv = AES_Encrypt(cx2,
  1354. doublecheck, &outputlen, sizeof doublecheck,
  1355. plaintext, sizeof plaintext);
  1356. if (rv != SECSuccess) {
  1357. goto loser;
  1358. }
  1359. if (outputlen != sizeof plaintext) {
  1360. goto loser;
  1361. }
  1362. if (memcmp(doublecheck, ciphertext, sizeof ciphertext)) {
  1363. goto loser;
  1364. }
  1365. /* CT[j+1] = PT[j] */
  1366. memcpy(ciphertext, plaintext, sizeof ciphertext);
  1367. }
  1368. AES_DestroyContext(cx, PR_TRUE);
  1369. cx = NULL;
  1370. AES_DestroyContext(cx2, PR_TRUE);
  1371. cx2 = NULL;
  1372. /* Output PT[j] */
  1373. fputs("PLAINTEXT = ", aesresp);
  1374. to_hex_str(buf, plaintext, sizeof plaintext);
  1375. fputs(buf, aesresp);
  1376. fputc('\n', aesresp);
  1377. /* Key[i+1] = Key[i] xor ... */
  1378. aes_mct_next_key(key, keysize, plaintext_1, plaintext);
  1379. /* CT[0] = PT[j] */
  1380. /* done at the end of the for(j) loop */
  1381. fputc('\n', aesresp);
  1382. }
  1383. continue;
  1384. }
  1385. }
  1386. loser:
  1387. if (cx != NULL) {
  1388. AES_DestroyContext(cx, PR_TRUE);
  1389. }
  1390. if (cx2 != NULL) {
  1391. AES_DestroyContext(cx2, PR_TRUE);
  1392. }
  1393. fclose(aesreq);
  1394. }
  1395. /*
  1396. * Perform the AES Monte Carlo Test (MCT) in CBC mode. MCT exercises
  1397. * our AES code in streaming mode because the plaintext or ciphertext
  1398. * is generated block by block as we go, so we can't collect all the
  1399. * plaintext or ciphertext in one buffer and encrypt or decrypt it in
  1400. * one shot.
  1401. *
  1402. * reqfn is the pathname of the input REQUEST file.
  1403. *
  1404. * The output RESPONSE file is written to stdout.
  1405. */
  1406. void
  1407. aes_cbc_mct(char *reqfn)
  1408. {
  1409. char buf[80]; /* holds one line from the input REQUEST file.
  1410. * needs to be large enough to hold the longest
  1411. * line "KEY = <64 hex digits>\n".
  1412. */
  1413. FILE *aesreq; /* input stream from the REQUEST file */
  1414. FILE *aesresp; /* output stream to the RESPONSE file */
  1415. int i, j;
  1416. int encrypt = 0; /* 1 means encrypt, 0 means decrypt */
  1417. unsigned char key[32]; /* 128, 192, or 256 bits */
  1418. unsigned int keysize;
  1419. unsigned char iv[16];
  1420. unsigned char plaintext[16]; /* PT[j] */
  1421. unsigned char plaintext_1[16]; /* PT[j-1] */
  1422. unsigned char ciphertext[16]; /* CT[j] */
  1423. unsigned char ciphertext_1[16]; /* CT[j-1] */
  1424. unsigned char doublecheck[16];
  1425. unsigned int outputlen;
  1426. AESContext *cx = NULL; /* the operation being tested */
  1427. AESContext *cx2 = NULL; /* the inverse operation done in parallel
  1428. * to doublecheck our result.
  1429. */
  1430. SECStatus rv;
  1431. aesreq = fopen(reqfn, "r");
  1432. aesresp = stdout;
  1433. while (fgets(buf, sizeof buf, aesreq) != NULL) {
  1434. /* a comment or blank line */
  1435. if (buf[0] == '#' || buf[0] == '\n') {
  1436. fputs(buf, aesresp);
  1437. continue;
  1438. }
  1439. /* [ENCRYPT] or [DECRYPT] */
  1440. if (buf[0] == '[') {
  1441. if (strncmp(&buf[1], "ENCRYPT", 7) == 0) {
  1442. encrypt = 1;
  1443. } else {
  1444. encrypt = 0;
  1445. }
  1446. fputs(buf, aesresp);
  1447. continue;
  1448. }
  1449. /* "COUNT = x" begins a new data set */
  1450. if (strncmp(buf, "COUNT", 5) == 0) {
  1451. /* zeroize the variables for the test with this data set */
  1452. memset(key, 0, sizeof key);
  1453. keysize = 0;
  1454. memset(iv, 0, sizeof iv);
  1455. memset(plaintext, 0, sizeof plaintext);
  1456. memset(ciphertext, 0, sizeof ciphertext);
  1457. continue;
  1458. }
  1459. /* KEY = ... */
  1460. if (strncmp(buf, "KEY", 3) == 0) {
  1461. /* Key[0] = Key */
  1462. i = 3;
  1463. while (isspace(buf[i]) || buf[i] == '=') {
  1464. i++;
  1465. }
  1466. for (j=0; isxdigit(buf[i]); i+=2,j++) {
  1467. hex_to_byteval(&buf[i], &key[j]);
  1468. }
  1469. keysize = j;
  1470. continue;
  1471. }
  1472. /* IV = ... */
  1473. if (strncmp(buf, "IV", 2) == 0) {
  1474. /* IV[0] = IV */
  1475. i = 2;
  1476. while (isspace(buf[i]) || buf[i] == '=') {
  1477. i++;
  1478. }
  1479. for (j=0; j<sizeof iv; i+=2,j++) {
  1480. hex_to_byteval(&buf[i], &iv[j]);
  1481. }
  1482. continue;
  1483. }
  1484. /* PLAINTEXT = ... */
  1485. if (strncmp(buf, "PLAINTEXT", 9) == 0) {
  1486. /* sanity check */
  1487. if (!encrypt) {
  1488. goto loser;
  1489. }
  1490. /* PT[0] = PT */
  1491. i = 9;
  1492. while (isspace(buf[i]) || buf[i] == '=') {
  1493. i++;
  1494. }
  1495. for (j=0; j<sizeof plaintext; i+=2,j++) {
  1496. hex_to_byteval(&buf[i], &plaintext[j]);
  1497. }
  1498. for (i=0; i<100; i++) {
  1499. sprintf(buf, "COUNT = %d\n", i);
  1500. fputs(buf, aesresp);
  1501. /* Output Key[i] */
  1502. fputs("KEY = ", aesresp);
  1503. to_hex_str(buf, key, keysize);
  1504. fputs(buf, aesresp);
  1505. fputc('\n', aesresp);
  1506. /* Output IV[i] */
  1507. fputs("IV = ", aesresp);
  1508. to_hex_str(buf, iv, sizeof iv);
  1509. fputs(buf, aesresp);
  1510. fputc('\n', aesresp);
  1511. /* Output PT[0] */
  1512. fputs("PLAINTEXT = ", aesresp);
  1513. to_hex_str(buf, plaintext, sizeof plaintext);
  1514. fputs(buf, aesresp);
  1515. fputc('\n', aesresp);
  1516. cx = AES_CreateContext(key, iv, NSS_AES_CBC,
  1517. PR_TRUE, keysize, 16);
  1518. if (cx == NULL) {
  1519. goto loser;
  1520. }
  1521. /*
  1522. * doublecheck our result by decrypting the result
  1523. * and comparing the output with the plaintext.
  1524. */
  1525. cx2 = AES_CreateContext(key, iv, NSS_AES_CBC,
  1526. PR_FALSE, keysize, 16);
  1527. if (cx2 == NULL) {
  1528. goto loser;
  1529. }
  1530. /* CT[-1] = IV[i] */
  1531. memcpy(ciphertext, iv, sizeof ciphertext);
  1532. for (j=0; j<1000; j++) {
  1533. /* Save CT[j-1] */
  1534. memcpy(ciphertext_1, ciphertext, sizeof ciphertext);
  1535. /*
  1536. * If ( j=0 )
  1537. * CT[j] = AES(Key[i], IV[i], PT[j])
  1538. * PT[j+1] = IV[i] (= CT[j-1])
  1539. * Else
  1540. * CT[j] = AES(Key[i], PT[j])
  1541. * PT[j+1] = CT[j-1]
  1542. */
  1543. outputlen = 0;
  1544. rv = AES_Encrypt(cx,
  1545. ciphertext, &outputlen, sizeof ciphertext,
  1546. plaintext, sizeof plaintext);
  1547. if (rv != SECSuccess) {
  1548. goto loser;
  1549. }
  1550. if (outputlen != sizeof plaintext) {
  1551. goto loser;
  1552. }
  1553. /* doublecheck our result */
  1554. outputlen = 0;
  1555. rv = AES_Decrypt(cx2,
  1556. doublecheck, &outputlen, sizeof doublecheck,
  1557. ciphertext, sizeof ciphertext);
  1558. if (rv != SECSuccess) {
  1559. goto loser;
  1560. }
  1561. if (outputlen != sizeof ciphertext) {
  1562. goto loser;
  1563. }
  1564. if (memcmp(doublecheck, plaintext, sizeof plaintext)) {
  1565. goto loser;
  1566. }
  1567. memcpy(plaintext, ciphertext_1, sizeof plaintext);
  1568. }
  1569. AES_DestroyContext(cx, PR_TRUE);
  1570. cx = NULL;
  1571. AES_DestroyContext(cx2, PR_TRUE);
  1572. cx2 = NULL;
  1573. /* Output CT[j] */
  1574. fputs("CIPHERTEXT = ", aesresp);
  1575. to_hex_str(buf, ciphertext, sizeof ciphertext);
  1576. fputs(buf, aesresp);
  1577. fputc('\n', aesresp);
  1578. /* Key[i+1] = Key[i] xor ... */
  1579. aes_mct_next_key(key, keysize, ciphertext_1, ciphertext);
  1580. /* IV[i+1] = CT[j] */
  1581. memcpy(iv, ciphertext, sizeof iv);
  1582. /* PT[0] = CT[j-1] */
  1583. /* done at the end of the for(j) loop */
  1584. fputc('\n', aesresp);
  1585. }
  1586. continue;
  1587. }
  1588. /* CIPHERTEXT = ... */
  1589. if (strncmp(buf, "CIPHERTEXT", 10) == 0) {
  1590. /* sanity check */
  1591. if (encrypt) {
  1592. goto loser;
  1593. }
  1594. /* CT[0] = CT */
  1595. i = 10;
  1596. while (isspace(buf[i]) || buf[i] == '=') {
  1597. i++;
  1598. }
  1599. for (j=0; isxdigit(buf[i]); i+=2,j++) {
  1600. hex_to_byteval(&buf[i], &ciphertext[j]);
  1601. }
  1602. for (i=0; i<100; i++) {
  1603. sprintf(buf, "COUNT = %d\n", i);
  1604. fputs(buf, aesresp);
  1605. /* Output Key[i] */
  1606. fputs("KEY = ", aesresp);
  1607. to_hex_str(buf, key, keysize);
  1608. fputs(buf, aesresp);
  1609. fputc('\n', aesresp);
  1610. /* Output IV[i] */
  1611. fputs("IV = ", aesresp);
  1612. to_hex_str(buf, iv, sizeof iv);
  1613. fputs(buf, aesresp);
  1614. fputc('\n', aesresp);
  1615. /* Output CT[0] */
  1616. fputs("CIPHERTEXT = ", aesresp);
  1617. to_hex_str(buf, ciphertext, sizeof ciphertext);
  1618. fputs(buf, aesresp);
  1619. fputc('\n', aesresp);
  1620. cx = AES_CreateContext(key, iv, NSS_AES_CBC,
  1621. PR_FALSE, keysize, 16);
  1622. if (cx == NULL) {
  1623. goto loser;
  1624. }
  1625. /*
  1626. * doublecheck our result by encrypting the result
  1627. * and comparing the output with the ciphertext.
  1628. */
  1629. cx2 = AES_CreateContext(key, iv, NSS_AES_CBC,
  1630. PR_TRUE, keysize, 16);
  1631. if (cx2 == NULL) {
  1632. goto loser;
  1633. }
  1634. /* PT[-1] = IV[i] */
  1635. memcpy(plaintext, iv, sizeof plaintext);
  1636. for (j=0; j<1000; j++) {
  1637. /* Save PT[j-1] */
  1638. memcpy(plaintext_1, plaintext, sizeof plaintext);
  1639. /*
  1640. * If ( j=0 )
  1641. * PT[j] = AES(Key[i], IV[i], CT[j])
  1642. * CT[j+1] = IV[i] (= PT[j-1])
  1643. * Else
  1644. * PT[j] = AES(Key[i], CT[j])
  1645. * CT[j+1] = PT[j-1]
  1646. */
  1647. outputlen = 0;
  1648. rv = AES_Decrypt(cx,
  1649. plaintext, &outputlen, sizeof plaintext,
  1650. ciphertext, sizeof ciphertext);
  1651. if (rv != SECSuccess) {
  1652. goto loser;
  1653. }
  1654. if (outputlen != sizeof ciphertext) {
  1655. goto loser;
  1656. }
  1657. /* doublecheck our result */
  1658. outputlen = 0;
  1659. rv = AES_Encrypt(cx2,
  1660. doublecheck, &outputlen, sizeof doublecheck,
  1661. plaintext, sizeof plaintext);
  1662. if (rv != SECSuccess) {
  1663. goto loser;
  1664. }
  1665. if (outputlen != sizeof plaintext) {
  1666. goto loser;
  1667. }
  1668. if (memcmp(doublecheck, ciphertext, sizeof ciphertext)) {
  1669. goto loser;
  1670. }
  1671. memcpy(ciphertext, plaintext_1, sizeof ciphertext);
  1672. }
  1673. AES_DestroyContext(cx, PR_TRUE);
  1674. cx = NULL;
  1675. AES_DestroyContext(cx2, PR_TRUE);
  1676. cx2 = NULL;
  1677. /* Output PT[j] */
  1678. fputs("PLAINTEXT = ", aesresp);
  1679. to_hex_str(buf, plaintext, sizeof plaintext);
  1680. fputs(buf, aesresp);
  1681. fputc('\n', aesresp);
  1682. /* Key[i+1] = Key[i] xor ... */
  1683. aes_mct_next_key(key, keysize, plaintext_1, plaintext);
  1684. /* IV[i+1] = PT[j] */
  1685. memcpy(iv, plaintext, sizeof iv);
  1686. /* CT[0] = PT[j-1] */
  1687. /* done at the end of the for(j) loop */
  1688. fputc('\n', aesresp);
  1689. }
  1690. continue;
  1691. }
  1692. }
  1693. loser:
  1694. if (cx != NULL) {
  1695. AES_DestroyContext(cx, PR_TRUE);
  1696. }
  1697. if (cx2 != NULL) {
  1698. AES_DestroyContext(cx2, PR_TRUE);
  1699. }
  1700. fclose(aesreq);
  1701. }
  1702. void write_compact_string(FILE *out, unsigned char *hash, unsigned int len)
  1703. {
  1704. unsigned int i;
  1705. int j, count = 0, last = -1, z = 0;
  1706. long start = ftell(out);
  1707. for (i=0; i<len; i++) {
  1708. for (j=7; j>=0; j--) {
  1709. if (last < 0) {
  1710. last = (hash[i] & (1 << j)) ? 1 : 0;
  1711. fprintf(out, "%d ", last);
  1712. count = 1;
  1713. } else if (hash[i] & (1 << j)) {
  1714. if (last) {
  1715. count++;
  1716. } else {
  1717. last = 0;
  1718. fprintf(out, "%d ", count);
  1719. count = 1;
  1720. z++;
  1721. }
  1722. } else {
  1723. if (!last) {
  1724. count++;
  1725. } else {
  1726. last = 1;
  1727. fprintf(out, "%d ", count);
  1728. count = 1;
  1729. z++;
  1730. }
  1731. }
  1732. }
  1733. }
  1734. fprintf(out, "^\n");
  1735. fseek(out, start, SEEK_SET);
  1736. fprintf(out, "%d ", z);
  1737. fseek(out, 0, SEEK_END);
  1738. }
  1739. int get_next_line(FILE *req, char *key, char *val, FILE *rsp)
  1740. {
  1741. int ignore = 0;
  1742. char *writeto = key;
  1743. int w = 0;
  1744. int c;
  1745. while ((c = fgetc(req)) != EOF) {
  1746. if (ignore) {
  1747. fprintf(rsp, "%c", c);
  1748. if (c == '\n') return ignore;
  1749. } else if (c == '\n') {
  1750. break;
  1751. } else if (c == '#') {
  1752. ignore = 1;
  1753. fprintf(rsp, "%c", c);
  1754. } else if (c == '=') {
  1755. writeto[w] = '\0';
  1756. w = 0;
  1757. writeto = val;
  1758. } else if (c == ' ' || c == '[' || c == ']') {
  1759. continue;
  1760. } else {
  1761. writeto[w++] = c;
  1762. }
  1763. }
  1764. writeto[w] = '\0';
  1765. return (c == EOF) ? -1 : ignore;
  1766. }
  1767. #ifdef NSS_ENABLE_ECC
  1768. typedef struct curveNameTagPairStr {
  1769. char *curveName;
  1770. SECOidTag curveOidTag;
  1771. } CurveNameTagPair;
  1772. #define DEFAULT_CURVE_OID_TAG SEC_OID_SECG_EC_SECP192R1
  1773. /* #define DEFAULT_CURVE_OID_TAG SEC_OID_SECG_EC_SECP160R1 */
  1774. static CurveNameTagPair nameTagPair[] =
  1775. {
  1776. { "sect163k1", SEC_OID_SECG_EC_SECT163K1},
  1777. { "nistk163", SEC_OID_SECG_EC_SECT163K1},
  1778. { "sect163r1", SEC_OID_SECG_EC_SECT163R1},
  1779. { "sect163r2", SEC_OID_SECG_EC_SECT163R2},
  1780. { "nistb163", SEC_OID_SECG_EC_SECT163R2},
  1781. { "sect193r1", SEC_OID_SECG_EC_SECT193R1},
  1782. { "sect193r2", SEC_OID_SECG_EC_SECT193R2},
  1783. { "sect233k1", SEC_OID_SECG_EC_SECT233K1},
  1784. { "nistk233", SEC_OID_SECG_EC_SECT233K1},
  1785. { "sect233r1", SEC_OID_SECG_EC_SECT233R1},
  1786. { "nistb233", SEC_OID_SECG_EC_SECT233R1},
  1787. { "sect239k1", SEC_OID_SECG_EC_SECT239K1},
  1788. { "sect283k1", SEC_OID_SECG_EC_SECT283K1},
  1789. { "nistk283", SEC_OID_SECG_EC_SECT283K1},
  1790. { "sect283r1", SEC_OID_SECG_EC_SECT283R1},
  1791. { "nistb283", SEC_OID_SECG_EC_SECT283R1},
  1792. { "sect409k1", SEC_OID_SECG_EC_SECT409K1},
  1793. { "nistk409", SEC_OID_SECG_EC_SECT409K1},
  1794. { "sect409r1", SEC_OID_SECG_EC_SECT409R1},
  1795. { "nistb409", SEC_OID_SECG_EC_SECT409R1},
  1796. { "sect571k1", SEC_OID_SECG_EC_SECT571K1},
  1797. { "nistk571", SEC_OID_SECG_EC_SECT571K1},
  1798. { "sect571r1", SEC_OID_SECG_EC_SECT571R1},
  1799. { "nistb571", SEC_OID_SECG_EC_SECT571R1},
  1800. { "secp160k1", SEC_OID_SECG_EC_SECP160K1},
  1801. { "secp160r1", SEC_OID_SECG_EC_SECP160R1},
  1802. { "secp160r2", SEC_OID_SECG_EC_SECP160R2},
  1803. { "secp192k1", SEC_OID_SECG_EC_SECP192K1},
  1804. { "secp192r1", SEC_OID_SECG_EC_SECP192R1},
  1805. { "nistp192", SEC_OID_SECG_EC_SECP192R1},
  1806. { "secp224k1", SEC_OID_SECG_EC_SECP224K1},
  1807. { "secp224r1", SEC_OID_SECG_EC_SECP224R1},
  1808. { "nistp224", SEC_OID_SECG_EC_SECP224R1},
  1809. { "secp256k1", SEC_OID_SECG_EC_SECP256K1},
  1810. { "secp256r1", SEC_OID_SECG_EC_SECP256R1},
  1811. { "nistp256", SEC_OID_SECG_EC_SECP256R1},
  1812. { "secp384r1", SEC_OID_SECG_EC_SECP384R1},
  1813. { "nistp384", SEC_OID_SECG_EC_SECP384R1},
  1814. { "secp521r1", SEC_OID_SECG_EC_SECP521R1},
  1815. { "nistp521", SEC_OID_SECG_EC_SECP521R1},
  1816. { "prime192v1", SEC_OID_ANSIX962_EC_PRIME192V1 },
  1817. { "prime192v2", SEC_OID_ANSIX962_EC_PRIME192V2 },
  1818. { "prime192v3", SEC_OID_ANSIX962_EC_PRIME192V3 },
  1819. { "prime239v1", SEC_OID_ANSIX962_EC_PRIME239V1 },
  1820. { "prime239v2", SEC_OID_ANSIX962_EC_PRIME239V2 },
  1821. { "prime239v3", SEC_OID_ANSIX962_EC_PRIME239V3 },
  1822. { "c2pnb163v1", SEC_OID_ANSIX962_EC_C2PNB163V1 },
  1823. { "c2pnb163v2", SEC_OID_ANSIX962_EC_C2PNB163V2 },
  1824. { "c2pnb163v3", SEC_OID_ANSIX962_EC_C2PNB163V3 },
  1825. { "c2pnb176v1", SEC_OID_ANSIX962_EC_C2PNB176V1 },
  1826. { "c2tnb191v1", SEC_OID_ANSIX962_EC_C2TNB191V1 },
  1827. { "c2tnb191v2", SEC_OID_ANSIX962_EC_C2TNB191V2 },
  1828. { "c2tnb191v3", SEC_OID_ANSIX962_EC_C2TNB191V3 },
  1829. { "c2onb191v4", SEC_OID_ANSIX962_EC_C2ONB191V4 },
  1830. { "c2onb191v5", SEC_OID_ANSIX962_EC_C2ONB191V5 },
  1831. { "c2pnb208w1", SEC_OID_ANSIX962_EC_C2PNB208W1 },
  1832. { "c2tnb239v1", SEC_OID_ANSIX962_EC_C2TNB239V1 },
  1833. { "c2tnb239v2", SEC_OID_ANSIX962_EC_C2TNB239V2 },
  1834. { "c2tnb239v3", SEC_OID_ANSIX962_EC_C2TNB239V3 },
  1835. { "c2onb239v4", SEC_OID_ANSIX962_EC_C2ONB239V4 },
  1836. { "c2onb239v5", SEC_OID_ANSIX962_EC_C2ONB239V5 },
  1837. { "c2pnb272w1", SEC_OID_ANSIX962_EC_C2PNB272W1 },
  1838. { "c2pnb304w1", SEC_OID_ANSIX962_EC_C2PNB304W1 },
  1839. { "c2tnb359v1", SEC_OID_ANSIX962_EC_C2TNB359V1 },
  1840. { "c2pnb368w1", SEC_OID_ANSIX962_EC_C2PNB368W1 },
  1841. { "c2tnb431r1", SEC_OID_ANSIX962_EC_C2TNB431R1 },
  1842. { "secp112r1", SEC_OID_SECG_EC_SECP112R1},
  1843. { "secp112r2", SEC_OID_SECG_EC_SECP112R2},
  1844. { "secp128r1", SEC_OID_SECG_EC_SECP128R1},
  1845. { "secp128r2", SEC_OID_SECG_EC_SECP128R2},
  1846. { "sect113r1", SEC_OID_SECG_EC_SECT113R1},
  1847. { "sect113r2", SEC_OID_SECG_EC_SECT113R2},
  1848. { "sect131r1", SEC_OID_SECG_EC_SECT131R1},
  1849. { "sect131r2", SEC_OID_SECG_EC_SECT131R2},
  1850. };
  1851. static SECKEYECParams *
  1852. getECParams(const char *curve)
  1853. {
  1854. SECKEYECParams *ecparams;
  1855. SECOidData *oidData = NULL;
  1856. SECOidTag curveOidTag = SEC_OID_UNKNOWN; /* default */
  1857. int i, numCurves;
  1858. if (curve != NULL) {
  1859. numCurves = sizeof(nameTagPair)/sizeof(CurveNameTagPair);
  1860. for (i = 0; ((i < numCurves) && (curveOidTag == SEC_OID_UNKNOWN));
  1861. i++) {
  1862. if (PL_strcmp(curve, nameTagPair[i].curveName) == 0)
  1863. curveOidTag = nameTagPair[i].curveOidTag;
  1864. }
  1865. }
  1866. /* Return NULL if curve name is not recognized */
  1867. if ((curveOidTag == SEC_OID_UNKNOWN) ||
  1868. (oidData = SECOID_FindOIDByTag(curveOidTag)) == NULL) {
  1869. fprintf(stderr, "Unrecognized elliptic curve %s\n", curve);
  1870. return NULL;
  1871. }
  1872. ecparams = SECITEM_AllocItem(NULL, NULL, (2 + oidData->oid.len));
  1873. /*
  1874. * ecparams->data needs to contain the ASN encoding of an object ID (OID)
  1875. * representing the named curve. The actual OID is in
  1876. * oidData->oid.data so we simply prepend 0x06 and OID length
  1877. */
  1878. ecparams->data[0] = SEC_ASN1_OBJECT_ID;
  1879. ecparams->data[1] = oidData->oid.len;
  1880. memcpy(ecparams->data + 2, oidData->oid.data, oidData->oid.len);
  1881. return ecparams;
  1882. }
  1883. /*
  1884. * Perform the ECDSA Key Pair Generation Test.
  1885. *
  1886. * reqfn is the pathname of the REQUEST file.
  1887. *
  1888. * The output RESPONSE file is written to stdout.
  1889. */
  1890. void
  1891. ecdsa_keypair_test(char *reqfn)
  1892. {
  1893. char buf[256]; /* holds one line from the input REQUEST file
  1894. * or to the output RESPONSE file.
  1895. * needs to be large enough to hold the longest
  1896. * line "Qx = <144 hex digits>\n".
  1897. */
  1898. FILE *ecdsareq; /* input stream from the REQUEST file */
  1899. FILE *ecdsaresp; /* output stream to the RESPONSE file */
  1900. char curve[16]; /* "nistxddd" */
  1901. ECParams *ecparams;
  1902. int N;
  1903. int i;
  1904. unsigned int len;
  1905. ecdsareq = fopen(reqfn, "r");
  1906. ecdsaresp = stdout;
  1907. strcpy(curve, "nist");
  1908. while (fgets(buf, sizeof buf, ecdsareq) != NULL) {
  1909. /* a comment or blank line */
  1910. if (buf[0] == '#' || buf[0] == '\n') {
  1911. fputs(buf, ecdsaresp);
  1912. continue;
  1913. }
  1914. /* [X-ddd] */
  1915. if (buf[0] == '[') {
  1916. const char *src;
  1917. char *dst;
  1918. SECKEYECParams *encodedparams;
  1919. src = &buf[1];
  1920. dst = &curve[4];
  1921. *dst++ = tolower(*src);
  1922. src += 2; /* skip the hyphen */
  1923. *dst++ = *src++;
  1924. *dst++ = *src++;
  1925. *dst++ = *src++;
  1926. *dst = '\0';
  1927. encodedparams = getECParams(curve);
  1928. if (encodedparams == NULL) {
  1929. goto loser;
  1930. }
  1931. if (EC_DecodeParams(encodedparams, &ecparams) != SECSuccess) {
  1932. goto loser;
  1933. }
  1934. SECITEM_FreeItem(encodedparams, PR_TRUE);
  1935. fputs(buf, ecdsaresp);
  1936. continue;
  1937. }
  1938. /* N = x */
  1939. if (buf[0] == 'N') {
  1940. if (sscanf(buf, "N = %d", &N) != 1) {
  1941. goto loser;
  1942. }
  1943. for (i = 0; i < N; i++) {
  1944. ECPrivateKey *ecpriv;
  1945. if (EC_NewKey(ecparams, &ecpriv) != SECSuccess) {
  1946. goto loser;
  1947. }
  1948. fputs("d = ", ecdsaresp);
  1949. to_hex_str(buf, ecpriv->privateValue.data,
  1950. ecpriv->privateValue.len);
  1951. fputs(buf, ecdsaresp);
  1952. fputc('\n', ecdsaresp);
  1953. if (EC_ValidatePublicKey(ecparams, &ecpriv->publicValue)
  1954. != SECSuccess) {
  1955. goto loser;
  1956. }
  1957. len = ecpriv->publicValue.len;
  1958. if (len%2 == 0) {
  1959. goto loser;
  1960. }
  1961. len = (len-1)/2;
  1962. if (ecpriv->publicValue.data[0]
  1963. != EC_POINT_FORM_UNCOMPRESSED) {
  1964. goto loser;
  1965. }
  1966. fputs("Qx = ", ecdsaresp);
  1967. to_hex_str(buf, &ecpriv->publicValue.data[1], len);
  1968. fputs(buf, ecdsaresp);
  1969. fputc('\n', ecdsaresp);
  1970. fputs("Qy = ", ecdsaresp);
  1971. to_hex_str(buf, &ecpriv->publicValue.data[1+len], len);
  1972. fputs(buf, ecdsaresp);
  1973. fputc('\n', ecdsaresp);
  1974. fputc('\n', ecdsaresp);
  1975. PORT_FreeArena(ecpriv->ecParams.arena, PR_TRUE);
  1976. }
  1977. PORT_FreeArena(ecparams->arena, PR_FALSE);
  1978. continue;
  1979. }
  1980. }
  1981. loser:
  1982. fclose(ecdsareq);
  1983. }
  1984. /*
  1985. * Perform the ECDSA Public Key Validation Test.
  1986. *
  1987. * reqfn is the pathname of the REQUEST file.
  1988. *
  1989. * The output RESPONSE file is written to stdout.
  1990. */
  1991. void
  1992. ecdsa_pkv_test(char *reqfn)
  1993. {
  1994. char buf[256]; /* holds one line from the input REQUEST file.
  1995. * needs to be large enough to hold the longest
  1996. * line "Qx = <144 hex digits>\n".
  1997. */
  1998. FILE *ecdsareq; /* input stream from the REQUEST file */
  1999. FILE *ecdsaresp; /* output stream to the RESPONSE file */
  2000. char curve[16]; /* "nistxddd" */
  2001. ECParams *ecparams = NULL;
  2002. SECItem pubkey;
  2003. unsigned int i;
  2004. unsigned int len;
  2005. PRBool keyvalid = PR_TRUE;
  2006. ecdsareq = fopen(reqfn, "r");
  2007. ecdsaresp = stdout;
  2008. strcpy(curve, "nist");
  2009. pubkey.data = NULL;
  2010. while (fgets(buf, sizeof buf, ecdsareq) != NULL) {
  2011. /* a comment or blank line */
  2012. if (buf[0] == '#' || buf[0] == '\n') {
  2013. fputs(buf, ecdsaresp);
  2014. continue;
  2015. }
  2016. /* [X-ddd] */
  2017. if (buf[0] == '[') {
  2018. const char *src;
  2019. char *dst;
  2020. SECKEYECParams *encodedparams;
  2021. src = &buf[1];
  2022. dst = &curve[4];
  2023. *dst++ = tolower(*src);
  2024. src += 2; /* skip the hyphen */
  2025. *dst++ = *src++;
  2026. *dst++ = *src++;
  2027. *dst++ = *src++;
  2028. *dst = '\0';
  2029. if (ecparams != NULL) {
  2030. PORT_FreeArena(ecparams->arena, PR_FALSE);
  2031. ecparams = NULL;
  2032. }
  2033. encodedparams = getECParams(curve);
  2034. if (encodedparams == NULL) {
  2035. goto loser;
  2036. }
  2037. if (EC_DecodeParams(encodedparams, &ecparams) != SECSuccess) {
  2038. goto loser;
  2039. }
  2040. SECITEM_FreeItem(encodedparams, PR_TRUE);
  2041. len = (ecparams->fieldID.size + 7) >> 3;
  2042. if (pubkey.data != NULL) {
  2043. PORT_Free(pubkey.data);
  2044. pubkey.data = NULL;
  2045. }
  2046. SECITEM_AllocItem(NULL, &pubkey, 2*len+1);
  2047. if (pubkey.data == NULL) {
  2048. goto loser;
  2049. }
  2050. pubkey.data[0] = EC_POINT_FORM_UNCOMPRESSED;
  2051. fputs(buf, ecdsaresp);
  2052. continue;
  2053. }
  2054. /* Qx = ... */
  2055. if (strncmp(buf, "Qx", 2) == 0) {
  2056. fputs(buf, ecdsaresp);
  2057. i = 2;
  2058. while (isspace(buf[i]) || buf[i] == '=') {
  2059. i++;
  2060. }
  2061. keyvalid = from_hex_str(&pubkey.data[1], len, &buf[i]);
  2062. continue;
  2063. }
  2064. /* Qy = ... */
  2065. if (strncmp(buf, "Qy", 2) == 0) {
  2066. fputs(buf, ecdsaresp);
  2067. if (!keyvalid) {
  2068. fputs("Result = F\n", ecdsaresp);
  2069. continue;
  2070. }
  2071. i = 2;
  2072. while (isspace(buf[i]) || buf[i] == '=') {
  2073. i++;
  2074. }
  2075. keyvalid = from_hex_str(&pubkey.data[1+len], len, &buf[i]);
  2076. if (!keyvalid) {
  2077. fputs("Result = F\n", ecdsaresp);
  2078. continue;
  2079. }
  2080. if (EC_ValidatePublicKey(ecparams, &pubkey) == SECSuccess) {
  2081. fputs("Result = P\n", ecdsaresp);
  2082. } else if (PORT_GetError() == SEC_ERROR_BAD_KEY) {
  2083. fputs("Result = F\n", ecdsaresp);
  2084. } else {
  2085. goto loser;
  2086. }
  2087. continue;
  2088. }
  2089. }
  2090. loser:
  2091. if (ecparams != NULL) {
  2092. PORT_FreeArena(ecparams->arena, PR_FALSE);
  2093. }
  2094. if (pubkey.data != NULL) {
  2095. PORT_Free(pubkey.data);
  2096. }
  2097. fclose(ecdsareq);
  2098. }
  2099. /*
  2100. * Perform the ECDSA Signature Generation Test.
  2101. *
  2102. * reqfn is the pathname of the REQUEST file.
  2103. *
  2104. * The output RESPONSE file is written to stdout.
  2105. */
  2106. void
  2107. ecdsa_siggen_test(char *reqfn)
  2108. {
  2109. char buf[1024]; /* holds one line from the input REQUEST file
  2110. * or to the output RESPONSE file.
  2111. * needs to be large enough to hold the longest
  2112. * line "Msg = <256 hex digits>\n".
  2113. */
  2114. FILE *ecdsareq; /* input stream from the REQUEST file */
  2115. FILE *ecdsaresp; /* output stream to the RESPONSE file */
  2116. char curve[16]; /* "nistxddd" */
  2117. ECParams *ecparams = NULL;
  2118. int i, j;
  2119. unsigned int len;
  2120. unsigned char msg[512]; /* message to be signed (<= 128 bytes) */
  2121. unsigned int msglen;
  2122. unsigned char sha1[20]; /* SHA-1 hash (160 bits) */
  2123. unsigned char sig[2*MAX_ECKEY_LEN];
  2124. SECItem signature, digest;
  2125. ecdsareq = fopen(reqfn, "r");
  2126. ecdsaresp = stdout;
  2127. strcpy(curve, "nist");
  2128. while (fgets(buf, sizeof buf, ecdsareq) != NULL) {
  2129. /* a comment or blank line */
  2130. if (buf[0] == '#' || buf[0] == '\n') {
  2131. fputs(buf, ecdsaresp);
  2132. continue;
  2133. }
  2134. /* [X-ddd] */
  2135. if (buf[0] == '[') {
  2136. const char *src;
  2137. char *dst;
  2138. SECKEYECParams *encodedparams;
  2139. src = &buf[1];
  2140. dst = &curve[4];
  2141. *dst++ = tolower(*src);
  2142. src += 2; /* skip the hyphen */
  2143. *dst++ = *src++;
  2144. *dst++ = *src++;
  2145. *dst++ = *src++;
  2146. *dst = '\0';
  2147. if (ecparams != NULL) {
  2148. PORT_FreeArena(ecparams->arena, PR_FALSE);
  2149. ecparams = NULL;
  2150. }
  2151. encodedparams = getECParams(curve);
  2152. if (encodedparams == NULL) {
  2153. goto loser;
  2154. }
  2155. if (EC_DecodeParams(encodedparams, &ecparams) != SECSuccess) {
  2156. goto loser;
  2157. }
  2158. SECITEM_FreeItem(encodedparams, PR_TRUE);
  2159. fputs(buf, ecdsaresp);
  2160. continue;
  2161. }
  2162. /* Msg = ... */
  2163. if (strncmp(buf, "Msg", 3) == 0) {
  2164. ECPrivateKey *ecpriv;
  2165. i = 3;
  2166. while (isspace(buf[i]) || buf[i] == '=') {
  2167. i++;
  2168. }
  2169. for (j=0; isxdigit(buf[i]); i+=2,j++) {
  2170. hex_to_byteval(&buf[i], &msg[j]);
  2171. }
  2172. msglen = j;
  2173. if (SHA1_HashBuf(sha1, msg, msglen) != SECSuccess) {
  2174. goto loser;
  2175. }
  2176. fputs(buf, ecdsaresp);
  2177. if (EC_NewKey(ecparams, &ecpriv) != SECSuccess) {
  2178. goto loser;
  2179. }
  2180. if (EC_ValidatePublicKey(ecparams, &ecpriv->publicValue)
  2181. != SECSuccess) {
  2182. goto loser;
  2183. }
  2184. len = ecpriv->publicValue.len;
  2185. if (len%2 == 0) {
  2186. goto loser;
  2187. }
  2188. len = (len-1)/2;
  2189. if (ecpriv->publicValue.data[0] != EC_POINT_FORM_UNCOMPRESSED) {
  2190. goto loser;
  2191. }
  2192. fputs("Qx = ", ecdsaresp);
  2193. to_hex_str(buf, &ecpriv->publicValue.data[1], len);
  2194. fputs(buf, ecdsaresp);
  2195. fputc('\n', ecdsaresp);
  2196. fputs("Qy = ", ecdsaresp);
  2197. to_hex_str(buf, &ecpriv->publicValue.data[1+len], len);
  2198. fputs(buf, ecdsaresp);
  2199. fputc('\n', ecdsaresp);
  2200. digest.type = siBuffer;
  2201. digest.data = sha1;
  2202. digest.len = sizeof sha1;
  2203. signature.type = siBuffer;
  2204. signature.data = sig;
  2205. signature.len = sizeof sig;
  2206. if (ECDSA_SignDigest(ecpriv, &signature, &digest) != SECSuccess) {
  2207. goto loser;
  2208. }
  2209. len = signature.len;
  2210. if (len%2 != 0) {
  2211. goto loser;
  2212. }
  2213. len = len/2;
  2214. fputs("R = ", ecdsaresp);
  2215. to_hex_str(buf, &signature.data[0], len);
  2216. fputs(buf, ecdsaresp);
  2217. fputc('\n', ecdsaresp);
  2218. fputs("S = ", ecdsaresp);
  2219. to_hex_str(buf, &signature.data[len], len);
  2220. fputs(buf, ecdsaresp);
  2221. fputc('\n', ecdsaresp);
  2222. PORT_FreeArena(ecpriv->ecParams.arena, PR_TRUE);
  2223. continue;
  2224. }
  2225. }
  2226. loser:
  2227. if (ecparams != NULL) {
  2228. PORT_FreeArena(ecparams->arena, PR_FALSE);
  2229. }
  2230. fclose(ecdsareq);
  2231. }
  2232. /*
  2233. * Perform the ECDSA Signature Verification Test.
  2234. *
  2235. * reqfn is the pathname of the REQUEST file.
  2236. *
  2237. * The output RESPONSE file is written to stdout.
  2238. */
  2239. void
  2240. ecdsa_sigver_test(char *reqfn)
  2241. {
  2242. char buf[1024]; /* holds one line from the input REQUEST file.
  2243. * needs to be large enough to hold the longest
  2244. * line "Msg = <256 hex digits>\n".
  2245. */
  2246. FILE *ecdsareq; /* input stream from the REQUEST file */
  2247. FILE *ecdsaresp; /* output stream to the RESPONSE file */
  2248. char curve[16]; /* "nistxddd" */
  2249. ECPublicKey ecpub;
  2250. unsigned int i, j;
  2251. unsigned int flen; /* length in bytes of the field size */
  2252. unsigned int olen; /* length in bytes of the base point order */
  2253. unsigned char msg[512]; /* message that was signed (<= 128 bytes) */
  2254. unsigned int msglen;
  2255. unsigned char sha1[20]; /* SHA-1 hash (160 bits) */
  2256. unsigned char sig[2*MAX_ECKEY_LEN];
  2257. SECItem signature, digest;
  2258. PRBool keyvalid = PR_TRUE;
  2259. PRBool sigvalid = PR_TRUE;
  2260. ecdsareq = fopen(reqfn, "r");
  2261. ecdsaresp = stdout;
  2262. ecpub.ecParams.arena = NULL;
  2263. strcpy(curve, "nist");
  2264. while (fgets(buf, sizeof buf, ecdsareq) != NULL) {
  2265. /* a comment or blank line */
  2266. if (buf[0] == '#' || buf[0] == '\n') {
  2267. fputs(buf, ecdsaresp);
  2268. continue;
  2269. }
  2270. /* [X-ddd] */
  2271. if (buf[0] == '[') {
  2272. const char *src;
  2273. char *dst;
  2274. SECKEYECParams *encodedparams;
  2275. ECParams *ecparams;
  2276. src = &buf[1];
  2277. dst = &curve[4];
  2278. *dst++ = tolower(*src);
  2279. src += 2; /* skip the hyphen */
  2280. *dst++ = *src++;
  2281. *dst++ = *src++;
  2282. *dst++ = *src++;
  2283. *dst = '\0';
  2284. encodedparams = getECParams(curve);
  2285. if (encodedparams == NULL) {
  2286. goto loser;
  2287. }
  2288. if (EC_DecodeParams(encodedparams, &ecparams) != SECSuccess) {
  2289. goto loser;
  2290. }
  2291. SECITEM_FreeItem(encodedparams, PR_TRUE);
  2292. if (ecpub.ecParams.arena != NULL) {
  2293. PORT_FreeArena(ecpub.ecParams.arena, PR_FALSE);
  2294. }
  2295. ecpub.ecParams.arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
  2296. if (ecpub.ecParams.arena == NULL) {
  2297. goto loser;
  2298. }
  2299. if (EC_CopyParams(ecpub.ecParams.arena, &ecpub.ecParams, ecparams)
  2300. != SECSuccess) {
  2301. goto loser;
  2302. }
  2303. PORT_FreeArena(ecparams->arena, PR_FALSE);
  2304. flen = (ecpub.ecParams.fieldID.size + 7) >> 3;
  2305. olen = ecpub.ecParams.order.len;
  2306. if (2*olen > sizeof sig) {
  2307. goto loser;
  2308. }
  2309. ecpub.publicValue.type = siBuffer;
  2310. ecpub.publicValue.data = NULL;
  2311. ecpub.publicValue.len = 0;
  2312. SECITEM_AllocItem(ecpub.ecParams.arena,
  2313. &ecpub.publicValue, 2*flen+1);
  2314. if (ecpub.publicValue.data == NULL) {
  2315. goto loser;
  2316. }
  2317. ecpub.publicValue.data[0] = EC_POINT_FORM_UNCOMPRESSED;
  2318. fputs(buf, ecdsaresp);
  2319. continue;
  2320. }
  2321. /* Msg = ... */
  2322. if (strncmp(buf, "Msg", 3) == 0) {
  2323. i = 3;
  2324. while (isspace(buf[i]) || buf[i] == '=') {
  2325. i++;
  2326. }
  2327. for (j=0; isxdigit(buf[i]); i+=2,j++) {
  2328. hex_to_byteval(&buf[i], &msg[j]);
  2329. }
  2330. msglen = j;
  2331. if (SHA1_HashBuf(sha1, msg, msglen) != SECSuccess) {
  2332. goto loser;
  2333. }
  2334. fputs(buf, ecdsaresp);
  2335. digest.type = siBuffer;
  2336. digest.data = sha1;
  2337. digest.len = sizeof sha1;
  2338. continue;
  2339. }
  2340. /* Qx = ... */
  2341. if (strncmp(buf, "Qx", 2) == 0) {
  2342. fputs(buf, ecdsaresp);
  2343. i = 2;
  2344. while (isspace(buf[i]) || buf[i] == '=') {
  2345. i++;
  2346. }
  2347. keyvalid = from_hex_str(&ecpub.publicValue.data[1], flen,
  2348. &buf[i]);
  2349. continue;
  2350. }
  2351. /* Qy = ... */
  2352. if (strncmp(buf, "Qy", 2) == 0) {
  2353. fputs(buf, ecdsaresp);
  2354. if (!keyvalid) {
  2355. continue;
  2356. }
  2357. i = 2;
  2358. while (isspace(buf[i]) || buf[i] == '=') {
  2359. i++;
  2360. }
  2361. keyvalid = from_hex_str(&ecpub.publicValue.data[1+flen], flen,
  2362. &buf[i]);
  2363. if (!keyvalid) {
  2364. continue;
  2365. }
  2366. if (EC_ValidatePublicKey(&ecpub.ecParams, &ecpub.publicValue)
  2367. != SECSuccess) {
  2368. if (PORT_GetError() == SEC_ERROR_BAD_KEY) {
  2369. keyvalid = PR_FALSE;
  2370. } else {
  2371. goto loser;
  2372. }
  2373. }
  2374. continue;
  2375. }
  2376. /* R = ... */
  2377. if (buf[0] == 'R') {
  2378. fputs(buf, ecdsaresp);
  2379. i = 1;
  2380. while (isspace(buf[i]) || buf[i] == '=') {
  2381. i++;
  2382. }
  2383. sigvalid = from_hex_str(sig, olen, &buf[i]);
  2384. continue;
  2385. }
  2386. /* S = ... */
  2387. if (buf[0] == 'S') {
  2388. fputs(buf, ecdsaresp);
  2389. i = 1;
  2390. while (isspace(buf[i]) || buf[i] == '=') {
  2391. i++;
  2392. }
  2393. if (sigvalid) {
  2394. sigvalid = from_hex_str(&sig[olen], olen, &buf[i]);
  2395. }
  2396. signature.type = siBuffer;
  2397. signature.data = sig;
  2398. signature.len = 2*olen;
  2399. if (!keyvalid || !sigvalid) {
  2400. fputs("Result = F\n", ecdsaresp);
  2401. } else if (ECDSA_VerifyDigest(&ecpub, &signature, &digest)
  2402. == SECSuccess) {
  2403. fputs("Result = P\n", ecdsaresp);
  2404. } else {
  2405. fputs("Result = F\n", ecdsaresp);
  2406. }
  2407. continue;
  2408. }
  2409. }
  2410. loser:
  2411. if (ecpub.ecParams.arena != NULL) {
  2412. PORT_FreeArena(ecpub.ecParams.arena, PR_FALSE);
  2413. }
  2414. fclose(ecdsareq);
  2415. }
  2416. #endif /* NSS_ENABLE_ECC */
  2417. /*
  2418. * Read a value from the test and allocate the result.
  2419. */
  2420. static unsigned char *
  2421. alloc_value(char *buf, int *len)
  2422. {
  2423. unsigned char * value;
  2424. int i, count;
  2425. if (strncmp(buf, "<None>", 6) == 0) {
  2426. *len = 0;
  2427. return NULL;
  2428. }
  2429. /* find the length of the number */
  2430. for (count = 0; isxdigit(buf[count]); count++);
  2431. *len = count/2;
  2432. if (*len == 0) {
  2433. return NULL;
  2434. }
  2435. value = PORT_Alloc(*len);
  2436. if (!value) {
  2437. *len = 0;
  2438. return NULL;
  2439. }
  2440. for (i=0; i<*len; buf+=2 , i++) {
  2441. hex_to_byteval(buf, &value[i]);
  2442. }
  2443. return value;
  2444. }
  2445. PRBool
  2446. isblankline(char *b)
  2447. {
  2448. while (isspace(*b)) b++;
  2449. if ((*b == '\n') || (*b == 0)) {
  2450. return PR_TRUE;
  2451. }
  2452. return PR_FALSE;
  2453. }
  2454. /*
  2455. * Perform the Hash_DRBG (CAVS) for the RNG algorithm
  2456. *
  2457. * reqfn is the pathname of the REQUEST file.
  2458. *
  2459. * The output RESPONSE file is written to stdout.
  2460. */
  2461. void
  2462. drbg(char *reqfn)
  2463. {
  2464. char buf[2000]; /* test case has some very long lines, returned bits
  2465. * as high as 800 bytes (6400 bits). That 1600 byte
  2466. * plus a tag */
  2467. char buf2[2000];
  2468. FILE *rngreq; /* input stream from the REQUEST file */
  2469. FILE *rngresp; /* output stream to the RESPONSE file */
  2470. unsigned int i;
  2471. unsigned char *entropy = NULL;
  2472. int entropy_len = 0;
  2473. unsigned char *nonce = NULL;
  2474. int nonce_len = 0;
  2475. unsigned char *personalization_string = NULL;
  2476. int ps_len = 0;
  2477. unsigned char *return_bytes = NULL;
  2478. unsigned char *predicted_return_bytes = NULL;
  2479. int return_bytes_len = 0;
  2480. unsigned char *additional_input = NULL;
  2481. int additional_len = 0;
  2482. enum { NONE, INSTANTIATE, GENERATE, RESEED, UNINSTANTIATE } command =
  2483. NONE;
  2484. SECStatus rv;
  2485. rngreq = fopen(reqfn, "r");
  2486. rngresp = stdout;
  2487. while (fgets(buf, sizeof buf, rngreq) != NULL) {
  2488. /* a comment, skip it. */
  2489. if (buf[0] == '#') {
  2490. fputs(buf, rngresp);
  2491. continue;
  2492. }
  2493. if (isblankline(buf)) {
  2494. switch (command) {
  2495. case INSTANTIATE:
  2496. rv = PRNGTEST_Instantiate(entropy, entropy_len,
  2497. nonce, nonce_len,
  2498. personalization_string, ps_len);
  2499. if (rv != SECSuccess) {
  2500. goto loser;
  2501. }
  2502. /* clear */
  2503. if (entropy) {
  2504. PORT_ZFree(entropy, entropy_len);
  2505. entropy = NULL;
  2506. entropy_len = 0;
  2507. }
  2508. if (nonce) {
  2509. PORT_ZFree(nonce, nonce_len);
  2510. nonce = NULL;
  2511. nonce_len = 0;
  2512. }
  2513. if (personalization_string) {
  2514. PORT_ZFree(personalization_string, ps_len);
  2515. personalization_string = NULL;
  2516. ps_len = 0;
  2517. }
  2518. break;
  2519. case GENERATE:
  2520. rv = PRNGTEST_Generate(return_bytes, return_bytes_len,
  2521. additional_input, additional_len);
  2522. if (rv != SECSuccess) {
  2523. goto loser;
  2524. }
  2525. /* clear */
  2526. if (predicted_return_bytes) {
  2527. fputc('+', rngresp);
  2528. }
  2529. fputs("Returned bits = ", rngresp);
  2530. to_hex_str(buf2, return_bytes, return_bytes_len);
  2531. fputs(buf2, rngresp);
  2532. fputc('\n', rngresp);
  2533. if (predicted_return_bytes) {
  2534. if (memcmp(return_bytes,
  2535. predicted_return_bytes, return_bytes_len) != 0) {
  2536. fprintf(stderr, "Generate failed:\n");
  2537. fputs( " predicted=", stderr);
  2538. to_hex_str(buf, predicted_return_bytes,
  2539. return_bytes_len);
  2540. fputs(buf, stderr);
  2541. fputs("\n actual = ", stderr);
  2542. fputs(buf2, stderr);
  2543. fputc('\n', stderr);
  2544. }
  2545. PORT_ZFree(predicted_return_bytes, return_bytes_len);
  2546. predicted_return_bytes = NULL;
  2547. }
  2548. if (return_bytes) {
  2549. PORT_ZFree(return_bytes, return_bytes_len);
  2550. return_bytes = NULL;
  2551. return_bytes_len = 0;
  2552. }
  2553. if (additional_input) {
  2554. PORT_ZFree(additional_input, additional_len);
  2555. additional_input = NULL;
  2556. additional_len = 0;
  2557. }
  2558. break;
  2559. case RESEED:
  2560. rv = PRNGTEST_Reseed(entropy, entropy_len,
  2561. additional_input, additional_len);
  2562. if (rv != SECSuccess) {
  2563. goto loser;
  2564. }
  2565. /* clear */
  2566. if (entropy) {
  2567. PORT_ZFree(entropy, entropy_len);
  2568. entropy = NULL;
  2569. entropy_len = 0;
  2570. }
  2571. if (additional_input) {
  2572. PORT_ZFree(additional_input, additional_len);
  2573. additional_input = NULL;
  2574. additional_len = 0;
  2575. }
  2576. break;
  2577. case UNINSTANTIATE:
  2578. rv = PRNGTEST_Uninstantiate();
  2579. if (rv != SECSuccess) {
  2580. goto loser;
  2581. }
  2582. break;
  2583. }
  2584. fputs(buf, rngresp);
  2585. command = NONE;
  2586. continue;
  2587. }
  2588. /* [Hash - SHA256] */
  2589. if (buf[0] == '[') {
  2590. fputs(buf, rngresp);
  2591. continue;
  2592. }
  2593. /* INSTANTIATE */
  2594. if (strncmp(buf, "INSTANTIATE", 11) == 0) {
  2595. i = 11;
  2596. command = INSTANTIATE;
  2597. fputs(buf, rngresp);
  2598. continue;
  2599. }
  2600. /* Generate bytes */
  2601. if (strncmp(buf, "GENERATE", 8) == 0) {
  2602. i = 8;
  2603. while (isspace(buf[i])) {
  2604. i++;
  2605. }
  2606. return_bytes_len = atoi(&buf[i])/8;
  2607. return_bytes = PORT_Alloc(return_bytes_len);
  2608. command = GENERATE;
  2609. fputs(buf, rngresp);
  2610. continue;
  2611. }
  2612. if (strncmp(buf, "RESEED", 6) == 0) {
  2613. i = 6;
  2614. command = RESEED;
  2615. fputs(buf, rngresp);
  2616. continue;
  2617. }
  2618. if (strncmp(buf, "UNINSTANTIATE", 13) == 0) {
  2619. i = 13;
  2620. command = UNINSTANTIATE;
  2621. fputs(buf, rngresp);
  2622. continue;
  2623. }
  2624. /* Entropy input = ... */
  2625. if (strncmp(buf, "Entropy input", 13) == 0) {
  2626. i = 13;
  2627. while (isspace(buf[i]) || buf[i] == '=') {
  2628. i++;
  2629. }
  2630. if ((command == INSTANTIATE) || (command == RESEED)) {
  2631. entropy = alloc_value(&buf[i], &entropy_len);
  2632. }
  2633. fputs(buf, rngresp);
  2634. continue;
  2635. }
  2636. /* Nonce = ... */
  2637. if (strncmp(buf, "Nonce", 5) == 0) {
  2638. i = 5;
  2639. while (isspace(buf[i]) || buf[i] == '=') {
  2640. i++;
  2641. }
  2642. if (command == INSTANTIATE) {
  2643. nonce = alloc_value(&buf[i], &nonce_len);
  2644. }
  2645. fputs(buf, rngresp);
  2646. continue;
  2647. }
  2648. /* Personalization string = ... */
  2649. if (strncmp(buf, "Personalization string", 22) == 0) {
  2650. i = 22;
  2651. while (isspace(buf[i]) || buf[i] == '=') {
  2652. i++;
  2653. }
  2654. if (command == INSTANTIATE) {
  2655. personalization_string = alloc_value(&buf[i], &ps_len);
  2656. }
  2657. fputs(buf, rngresp);
  2658. continue;
  2659. }
  2660. /* Returned bits = ... */
  2661. if (strncmp(buf, "Returned bits", 13) == 0) {
  2662. i = 13;
  2663. while (isspace(buf[i]) || buf[i] == '=') {
  2664. i++;
  2665. }
  2666. if (command == GENERATE) {
  2667. int len;
  2668. predicted_return_bytes = alloc_value(&buf[i], &len);
  2669. }
  2670. fputs(buf, rngresp);
  2671. continue;
  2672. }
  2673. /* Additional input = ... */
  2674. if (strncmp(buf, "Additional input", 16) == 0) {
  2675. i = 16;
  2676. while (isspace(buf[i]) || buf[i] == '=') {
  2677. i++;
  2678. }
  2679. if ((command == GENERATE) || (command = RESEED)) {
  2680. additional_input = alloc_value(&buf[i], &additional_len);
  2681. }
  2682. fputs(buf, rngresp);
  2683. continue;
  2684. }
  2685. }
  2686. loser:
  2687. fclose(rngreq);
  2688. }
  2689. /*
  2690. * Perform the RNG Variable Seed Test (VST) for the RNG algorithm
  2691. * "DSA - Generation of X", used both as specified and as a generic
  2692. * purpose RNG. The presence of "Q = ..." in the REQUEST file
  2693. * indicates we are using the algorithm as specified.
  2694. *
  2695. * reqfn is the pathname of the REQUEST file.
  2696. *
  2697. * The output RESPONSE file is written to stdout.
  2698. */
  2699. void
  2700. rng_vst(char *reqfn)
  2701. {
  2702. char buf[256]; /* holds one line from the input REQUEST file.
  2703. * needs to be large enough to hold the longest
  2704. * line "XSeed = <128 hex digits>\n".
  2705. */
  2706. FILE *rngreq; /* input stream from the REQUEST file */
  2707. FILE *rngresp; /* output stream to the RESPONSE file */
  2708. unsigned int i, j;
  2709. unsigned char Q[DSA_SUBPRIME_LEN];
  2710. PRBool hasQ = PR_FALSE;
  2711. unsigned int b; /* 160 <= b <= 512, b is a multiple of 8 */
  2712. unsigned char XKey[512/8];
  2713. unsigned char XSeed[512/8];
  2714. unsigned char GENX[2*SHA1_LENGTH];
  2715. unsigned char DSAX[DSA_SUBPRIME_LEN];
  2716. SECStatus rv;
  2717. rngreq = fopen(reqfn, "r");
  2718. rngresp = stdout;
  2719. while (fgets(buf, sizeof buf, rngreq) != NULL) {
  2720. /* a comment or blank line */
  2721. if (buf[0] == '#' || buf[0] == '\n') {
  2722. fputs(buf, rngresp);
  2723. continue;
  2724. }
  2725. /* [Xchange - SHA1] */
  2726. if (buf[0] == '[') {
  2727. fputs(buf, rngresp);
  2728. continue;
  2729. }
  2730. /* Q = ... */
  2731. if (buf[0] == 'Q') {
  2732. i = 1;
  2733. while (isspace(buf[i]) || buf[i] == '=') {
  2734. i++;
  2735. }
  2736. for (j=0; j<sizeof Q; i+=2,j++) {
  2737. hex_to_byteval(&buf[i], &Q[j]);
  2738. }
  2739. fputs(buf, rngresp);
  2740. hasQ = PR_TRUE;
  2741. continue;
  2742. }
  2743. /* "COUNT = x" begins a new data set */
  2744. if (strncmp(buf, "COUNT", 5) == 0) {
  2745. /* zeroize the variables for the test with this data set */
  2746. b = 0;
  2747. memset(XKey, 0, sizeof XKey);
  2748. memset(XSeed, 0, sizeof XSeed);
  2749. fputs(buf, rngresp);
  2750. continue;
  2751. }
  2752. /* b = ... */
  2753. if (buf[0] == 'b') {
  2754. i = 1;
  2755. while (isspace(buf[i]) || buf[i] == '=') {
  2756. i++;
  2757. }
  2758. b = atoi(&buf[i]);
  2759. if (b < 160 || b > 512 || b%8 != 0) {
  2760. goto loser;
  2761. }
  2762. fputs(buf, rngresp);
  2763. continue;
  2764. }
  2765. /* XKey = ... */
  2766. if (strncmp(buf, "XKey", 4) == 0) {
  2767. i = 4;
  2768. while (isspace(buf[i]) || buf[i] == '=') {
  2769. i++;
  2770. }
  2771. for (j=0; j<b/8; i+=2,j++) {
  2772. hex_to_byteval(&buf[i], &XKey[j]);
  2773. }
  2774. fputs(buf, rngresp);
  2775. continue;
  2776. }
  2777. /* XSeed = ... */
  2778. if (strncmp(buf, "XSeed", 5) == 0) {
  2779. i = 5;
  2780. while (isspace(buf[i]) || buf[i] == '=') {
  2781. i++;
  2782. }
  2783. for (j=0; j<b/8; i+=2,j++) {
  2784. hex_to_byteval(&buf[i], &XSeed[j]);
  2785. }
  2786. fputs(buf, rngresp);
  2787. rv = FIPS186Change_GenerateX(XKey, XSeed, GENX);
  2788. if (rv != SECSuccess) {
  2789. goto loser;
  2790. }
  2791. fputs("X = ", rngresp);
  2792. if (hasQ) {
  2793. rv = FIPS186Change_ReduceModQForDSA(GENX, Q, DSAX);
  2794. if (rv != SECSuccess) {
  2795. goto loser;
  2796. }
  2797. to_hex_str(buf, DSAX, sizeof DSAX);
  2798. } else {
  2799. to_hex_str(buf, GENX, sizeof GENX);
  2800. }
  2801. fputs(buf, rngresp);
  2802. fputc('\n', rngresp);
  2803. continue;
  2804. }
  2805. }
  2806. loser:
  2807. fclose(rngreq);
  2808. }
  2809. /*
  2810. * Perform the RNG Monte Carlo Test (MCT) for the RNG algorithm
  2811. * "DSA - Generation of X", used both as specified and as a generic
  2812. * purpose RNG. The presence of "Q = ..." in the REQUEST file
  2813. * indicates we are using the algorithm as specified.
  2814. *
  2815. * reqfn is the pathname of the REQUEST file.
  2816. *
  2817. * The output RESPONSE file is written to stdout.
  2818. */
  2819. void
  2820. rng_mct(char *reqfn)
  2821. {
  2822. char buf[256]; /* holds one line from the input REQUEST file.
  2823. * needs to be large enough to hold the longest
  2824. * line "XSeed = <128 hex digits>\n".
  2825. */
  2826. FILE *rngreq; /* input stream from the REQUEST file */
  2827. FILE *rngresp; /* output stream to the RESPONSE file */
  2828. unsigned int i, j;
  2829. unsigned char Q[DSA_SUBPRIME_LEN];
  2830. PRBool hasQ = PR_FALSE;
  2831. unsigned int b; /* 160 <= b <= 512, b is a multiple of 8 */
  2832. unsigned char XKey[512/8];
  2833. unsigned char XSeed[512/8];
  2834. unsigned char GENX[2*SHA1_LENGTH];
  2835. unsigned char DSAX[DSA_SUBPRIME_LEN];
  2836. SECStatus rv;
  2837. rngreq = fopen(reqfn, "r");
  2838. rngresp = stdout;
  2839. while (fgets(buf, sizeof buf, rngreq) != NULL) {
  2840. /* a comment or blank line */
  2841. if (buf[0] == '#' || buf[0] == '\n') {
  2842. fputs(buf, rngresp);
  2843. continue;
  2844. }
  2845. /* [Xchange - SHA1] */
  2846. if (buf[0] == '[') {
  2847. fputs(buf, rngresp);
  2848. continue;
  2849. }
  2850. /* Q = ... */
  2851. if (buf[0] == 'Q') {
  2852. i = 1;
  2853. while (isspace(buf[i]) || buf[i] == '=') {
  2854. i++;
  2855. }
  2856. for (j=0; j<sizeof Q; i+=2,j++) {
  2857. hex_to_byteval(&buf[i], &Q[j]);
  2858. }
  2859. fputs(buf, rngresp);
  2860. hasQ = PR_TRUE;
  2861. continue;
  2862. }
  2863. /* "COUNT = x" begins a new data set */
  2864. if (strncmp(buf, "COUNT", 5) == 0) {
  2865. /* zeroize the variables for the test with this data set */
  2866. b = 0;
  2867. memset(XKey, 0, sizeof XKey);
  2868. memset(XSeed, 0, sizeof XSeed);
  2869. fputs(buf, rngresp);
  2870. continue;
  2871. }
  2872. /* b = ... */
  2873. if (buf[0] == 'b') {
  2874. i = 1;
  2875. while (isspace(buf[i]) || buf[i] == '=') {
  2876. i++;
  2877. }
  2878. b = atoi(&buf[i]);
  2879. if (b < 160 || b > 512 || b%8 != 0) {
  2880. goto loser;
  2881. }
  2882. fputs(buf, rngresp);
  2883. continue;
  2884. }
  2885. /* XKey = ... */
  2886. if (strncmp(buf, "XKey", 4) == 0) {
  2887. i = 4;
  2888. while (isspace(buf[i]) || buf[i] == '=') {
  2889. i++;
  2890. }
  2891. for (j=0; j<b/8; i+=2,j++) {
  2892. hex_to_byteval(&buf[i], &XKey[j]);
  2893. }
  2894. fputs(buf, rngresp);
  2895. continue;
  2896. }
  2897. /* XSeed = ... */
  2898. if (strncmp(buf, "XSeed", 5) == 0) {
  2899. unsigned int k;
  2900. i = 5;
  2901. while (isspace(buf[i]) || buf[i] == '=') {
  2902. i++;
  2903. }
  2904. for (j=0; j<b/8; i+=2,j++) {
  2905. hex_to_byteval(&buf[i], &XSeed[j]);
  2906. }
  2907. fputs(buf, rngresp);
  2908. for (k = 0; k < 10000; k++) {
  2909. rv = FIPS186Change_GenerateX(XKey, XSeed, GENX);
  2910. if (rv != SECSuccess) {
  2911. goto loser;
  2912. }
  2913. }
  2914. fputs("X = ", rngresp);
  2915. if (hasQ) {
  2916. rv = FIPS186Change_ReduceModQForDSA(GENX, Q, DSAX);
  2917. if (rv != SECSuccess) {
  2918. goto loser;
  2919. }
  2920. to_hex_str(buf, DSAX, sizeof DSAX);
  2921. } else {
  2922. to_hex_str(buf, GENX, sizeof GENX);
  2923. }
  2924. fputs(buf, rngresp);
  2925. fputc('\n', rngresp);
  2926. continue;
  2927. }
  2928. }
  2929. loser:
  2930. fclose(rngreq);
  2931. }
  2932. /*
  2933. * Calculate the SHA Message Digest
  2934. *
  2935. * MD = Message digest
  2936. * MDLen = length of Message Digest and SHA_Type
  2937. * msg = message to digest
  2938. * msgLen = length of message to digest
  2939. */
  2940. SECStatus sha_calcMD(unsigned char *MD, unsigned int MDLen, unsigned char *msg, unsigned int msgLen)
  2941. {
  2942. SECStatus sha_status = SECFailure;
  2943. if (MDLen == SHA1_LENGTH) {
  2944. sha_status = SHA1_HashBuf(MD, msg, msgLen);
  2945. } else if (MDLen == SHA256_LENGTH) {
  2946. sha_status = SHA256_HashBuf(MD, msg, msgLen);
  2947. } else if (MDLen == SHA384_LENGTH) {
  2948. sha_status = SHA384_HashBuf(MD, msg, msgLen);
  2949. } else if (MDLen == SHA512_LENGTH) {
  2950. sha_status = SHA512_HashBuf(MD, msg, msgLen);
  2951. }
  2952. return sha_status;
  2953. }
  2954. /*
  2955. * Perform the SHA Monte Carlo Test
  2956. *
  2957. * MDLen = length of Message Digest and SHA_Type
  2958. * seed = input seed value
  2959. * resp = is the output response file.
  2960. */
  2961. SECStatus sha_mct_test(unsigned int MDLen, unsigned char *seed, FILE *resp)
  2962. {
  2963. int i, j;
  2964. unsigned int msgLen = MDLen*3;
  2965. unsigned char MD_i3[HASH_LENGTH_MAX]; /* MD[i-3] */
  2966. unsigned char MD_i2[HASH_LENGTH_MAX]; /* MD[i-2] */
  2967. unsigned char MD_i1[HASH_LENGTH_MAX]; /* MD[i-1] */
  2968. unsigned char MD_i[HASH_LENGTH_MAX]; /* MD[i] */
  2969. unsigned char msg[HASH_LENGTH_MAX*3];
  2970. char buf[HASH_LENGTH_MAX*2 + 1]; /* MAX buf MD_i as a hex string */
  2971. for (j=0; j<100; j++) {
  2972. /* MD_0 = MD_1 = MD_2 = seed */
  2973. memcpy(MD_i3, seed, MDLen);
  2974. memcpy(MD_i2, seed, MDLen);
  2975. memcpy(MD_i1, seed, MDLen);
  2976. for (i=3; i < 1003; i++) {
  2977. /* Mi = MD[i-3] || MD [i-2] || MD [i-1] */
  2978. memcpy(msg, MD_i3, MDLen);
  2979. memcpy(&msg[MDLen], MD_i2, MDLen);
  2980. memcpy(&msg[MDLen*2], MD_i1,MDLen);
  2981. /* MDi = SHA(Msg) */
  2982. if (sha_calcMD(MD_i, MDLen,
  2983. msg, msgLen) != SECSuccess) {
  2984. return SECFailure;
  2985. }
  2986. /* save MD[i-3] MD[i-2] MD[i-1] */
  2987. memcpy(MD_i3, MD_i2, MDLen);
  2988. memcpy(MD_i2, MD_i1, MDLen);
  2989. memcpy(MD_i1, MD_i, MDLen);
  2990. }
  2991. /* seed = MD_i */
  2992. memcpy(seed, MD_i, MDLen);
  2993. sprintf(buf, "COUNT = %d\n", j);
  2994. fputs(buf, resp);
  2995. /* output MD_i */
  2996. fputs("MD = ", resp);
  2997. to_hex_str(buf, MD_i, MDLen);
  2998. fputs(buf, resp);
  2999. fputc('\n', resp);
  3000. }
  3001. return SECSuccess;
  3002. }
  3003. /*
  3004. * Perform the SHA Tests.
  3005. *
  3006. * reqfn is the pathname of the input REQUEST file.
  3007. *
  3008. * The output RESPONSE file is written to stdout.
  3009. */
  3010. void sha_test(char *reqfn)
  3011. {
  3012. unsigned int i, j;
  3013. unsigned int MDlen; /* the length of the Message Digest in Bytes */
  3014. unsigned int msgLen; /* the length of the input Message in Bytes */
  3015. unsigned char *msg = NULL; /* holds the message to digest.*/
  3016. size_t bufSize = 25608; /*MAX buffer size */
  3017. char *buf = NULL; /* holds one line from the input REQUEST file.*/
  3018. unsigned char seed[HASH_LENGTH_MAX]; /* max size of seed 64 bytes */
  3019. unsigned char MD[HASH_LENGTH_MAX]; /* message digest */
  3020. FILE *req = NULL; /* input stream from the REQUEST file */
  3021. FILE *resp; /* output stream to the RESPONSE file */
  3022. buf = PORT_ZAlloc(bufSize);
  3023. if (buf == NULL) {
  3024. goto loser;
  3025. }
  3026. /* zeroize the variables for the test with this data set */
  3027. memset(seed, 0, sizeof seed);
  3028. req = fopen(reqfn, "r");
  3029. resp = stdout;
  3030. while (fgets(buf, bufSize, req) != NULL) {
  3031. /* a comment or blank line */
  3032. if (buf[0] == '#' || buf[0] == '\n') {
  3033. fputs(buf, resp);
  3034. continue;
  3035. }
  3036. /* [L = Length of the Message Digest and sha_type */
  3037. if (buf[0] == '[') {
  3038. if (strncmp(&buf[1], "L ", 1) == 0) {
  3039. i = 2;
  3040. while (isspace(buf[i]) || buf[i] == '=') {
  3041. i++;
  3042. }
  3043. MDlen = atoi(&buf[i]);
  3044. fputs(buf, resp);
  3045. continue;
  3046. }
  3047. }
  3048. /* Len = Length of the Input Message Length ... */
  3049. if (strncmp(buf, "Len", 3) == 0) {
  3050. i = 3;
  3051. while (isspace(buf[i]) || buf[i] == '=') {
  3052. i++;
  3053. }
  3054. if (msg) {
  3055. PORT_ZFree(msg,msgLen);
  3056. msg = NULL;
  3057. }
  3058. msgLen = atoi(&buf[i]); /* in bits */
  3059. if (msgLen%8 != 0) {
  3060. fprintf(stderr, "SHA tests are incorrectly configured for "
  3061. "BIT oriented implementations\n");
  3062. goto loser;
  3063. }
  3064. msgLen = msgLen/8; /* convert to bytes */
  3065. fputs(buf, resp);
  3066. msg = PORT_ZAlloc(msgLen);
  3067. if (msg == NULL && msgLen != 0) {
  3068. goto loser;
  3069. }
  3070. continue;
  3071. }
  3072. /* MSG = ... */
  3073. if (strncmp(buf, "Msg", 3) == 0) {
  3074. i = 3;
  3075. while (isspace(buf[i]) || buf[i] == '=') {
  3076. i++;
  3077. }
  3078. for (j=0; j< msgLen; i+=2,j++) {
  3079. hex_to_byteval(&buf[i], &msg[j]);
  3080. }
  3081. fputs(buf, resp);
  3082. /* calculate the Message Digest */
  3083. memset(MD, 0, sizeof MD);
  3084. if (sha_calcMD(MD, MDlen,
  3085. msg, msgLen) != SECSuccess) {
  3086. goto loser;
  3087. }
  3088. fputs("MD = ", resp);
  3089. to_hex_str(buf, MD, MDlen);
  3090. fputs(buf, resp);
  3091. fputc('\n', resp);
  3092. continue;
  3093. }
  3094. /* Seed = ... */
  3095. if (strncmp(buf, "Seed", 4) == 0) {
  3096. i = 4;
  3097. while (isspace(buf[i]) || buf[i] == '=') {
  3098. i++;
  3099. }
  3100. for (j=0; j<sizeof seed; i+=2,j++) {
  3101. hex_to_byteval(&buf[i], &seed[j]);
  3102. }
  3103. fputs(buf, resp);
  3104. fputc('\n', resp);
  3105. /* do the Monte Carlo test */
  3106. if (sha_mct_test(MDlen, seed, resp) != SECSuccess) {
  3107. goto loser;
  3108. }
  3109. continue;
  3110. }
  3111. }
  3112. loser:
  3113. if (req) {
  3114. fclose(req);
  3115. }
  3116. if (buf) {
  3117. PORT_ZFree(buf, bufSize);
  3118. }
  3119. if (msg) {
  3120. PORT_ZFree(msg, msgLen);
  3121. }
  3122. }
  3123. /****************************************************/
  3124. /* HMAC SHA-X calc */
  3125. /* hmac_computed - the computed HMAC */
  3126. /* hmac_length - the length of the computed HMAC */
  3127. /* secret_key - secret key to HMAC */
  3128. /* secret_key_length - length of secret key, */
  3129. /* message - message to HMAC */
  3130. /* message_length - length ofthe message */
  3131. /****************************************************/
  3132. static SECStatus
  3133. hmac_calc(unsigned char *hmac_computed,
  3134. const unsigned int hmac_length,
  3135. const unsigned char *secret_key,
  3136. const unsigned int secret_key_length,
  3137. const unsigned char *message,
  3138. const unsigned int message_length,
  3139. const HASH_HashType hashAlg )
  3140. {
  3141. SECStatus hmac_status = SECFailure;
  3142. HMACContext *cx = NULL;
  3143. SECHashObject *hashObj = NULL;
  3144. unsigned int bytes_hashed = 0;
  3145. hashObj = (SECHashObject *) HASH_GetRawHashObject(hashAlg);
  3146. if (!hashObj)
  3147. return( SECFailure );
  3148. cx = HMAC_Create(hashObj, secret_key,
  3149. secret_key_length,
  3150. PR_TRUE); /* PR_TRUE for in FIPS mode */
  3151. if (cx == NULL)
  3152. return( SECFailure );
  3153. HMAC_Begin(cx);
  3154. HMAC_Update(cx, message, message_length);
  3155. hmac_status = HMAC_Finish(cx, hmac_computed, &bytes_hashed,
  3156. hmac_length);
  3157. HMAC_Destroy(cx, PR_TRUE);
  3158. return( hmac_status );
  3159. }
  3160. /*
  3161. * Perform the HMAC Tests.
  3162. *
  3163. * reqfn is the pathname of the input REQUEST file.
  3164. *
  3165. * The output RESPONSE file is written to stdout.
  3166. */
  3167. void hmac_test(char *reqfn)
  3168. {
  3169. unsigned int i, j;
  3170. size_t bufSize = 288; /* MAX buffer size */
  3171. char *buf = NULL; /* holds one line from the input REQUEST file.*/
  3172. unsigned int keyLen; /* Key Length */
  3173. unsigned char key[140]; /* key MAX size = 140 */
  3174. unsigned int msgLen = 128; /* the length of the input */
  3175. /* Message is always 128 Bytes */
  3176. unsigned char *msg = NULL; /* holds the message to digest.*/
  3177. unsigned int HMACLen; /* the length of the HMAC Bytes */
  3178. unsigned char HMAC[HASH_LENGTH_MAX]; /* computed HMAC */
  3179. HASH_HashType hash_alg; /* HMAC type */
  3180. FILE *req = NULL; /* input stream from the REQUEST file */
  3181. FILE *resp; /* output stream to the RESPONSE file */
  3182. buf = PORT_ZAlloc(bufSize);
  3183. if (buf == NULL) {
  3184. goto loser;
  3185. }
  3186. msg = PORT_ZAlloc(msgLen);
  3187. memset(msg, 0, msgLen);
  3188. if (msg == NULL) {
  3189. goto loser;
  3190. }
  3191. req = fopen(reqfn, "r");
  3192. resp = stdout;
  3193. while (fgets(buf, bufSize, req) != NULL) {
  3194. /* a comment or blank line */
  3195. if (buf[0] == '#' || buf[0] == '\n') {
  3196. fputs(buf, resp);
  3197. continue;
  3198. }
  3199. /* [L = Length of the MAC and HASH_type */
  3200. if (buf[0] == '[') {
  3201. if (strncmp(&buf[1], "L ", 1) == 0) {
  3202. i = 2;
  3203. while (isspace(buf[i]) || buf[i] == '=') {
  3204. i++;
  3205. }
  3206. /* HMACLen will get reused for Tlen */
  3207. HMACLen = atoi(&buf[i]);
  3208. /* set the HASH algorithm for HMAC */
  3209. if (HMACLen == SHA1_LENGTH) {
  3210. hash_alg = HASH_AlgSHA1;
  3211. } else if (HMACLen == SHA256_LENGTH) {
  3212. hash_alg = HASH_AlgSHA256;
  3213. } else if (HMACLen == SHA384_LENGTH) {
  3214. hash_alg = HASH_AlgSHA384;
  3215. } else if (HMACLen == SHA512_LENGTH) {
  3216. hash_alg = HASH_AlgSHA512;
  3217. } else {
  3218. goto loser;
  3219. }
  3220. fputs(buf, resp);
  3221. continue;
  3222. }
  3223. }
  3224. /* Count = test iteration number*/
  3225. if (strncmp(buf, "Count ", 5) == 0) {
  3226. /* count can just be put into resp file */
  3227. fputs(buf, resp);
  3228. /* zeroize the variables for the test with this data set */
  3229. keyLen = 0;
  3230. HMACLen = 0;
  3231. memset(key, 0, sizeof key);
  3232. memset(msg, 0, sizeof msg);
  3233. memset(HMAC, 0, sizeof HMAC);
  3234. continue;
  3235. }
  3236. /* KLen = Length of the Input Secret Key ... */
  3237. if (strncmp(buf, "Klen", 4) == 0) {
  3238. i = 4;
  3239. while (isspace(buf[i]) || buf[i] == '=') {
  3240. i++;
  3241. }
  3242. keyLen = atoi(&buf[i]); /* in bytes */
  3243. fputs(buf, resp);
  3244. continue;
  3245. }
  3246. /* key = the secret key for the key to MAC */
  3247. if (strncmp(buf, "Key", 3) == 0) {
  3248. i = 3;
  3249. while (isspace(buf[i]) || buf[i] == '=') {
  3250. i++;
  3251. }
  3252. for (j=0; j< keyLen; i+=2,j++) {
  3253. hex_to_byteval(&buf[i], &key[j]);
  3254. }
  3255. fputs(buf, resp);
  3256. }
  3257. /* TLen = Length of the calculated HMAC */
  3258. if (strncmp(buf, "Tlen", 4) == 0) {
  3259. i = 4;
  3260. while (isspace(buf[i]) || buf[i] == '=') {
  3261. i++;
  3262. }
  3263. HMACLen = atoi(&buf[i]); /* in bytes */
  3264. fputs(buf, resp);
  3265. continue;
  3266. }
  3267. /* MSG = to HMAC always 128 bytes for these tests */
  3268. if (strncmp(buf, "Msg", 3) == 0) {
  3269. i = 3;
  3270. while (isspace(buf[i]) || buf[i] == '=') {
  3271. i++;
  3272. }
  3273. for (j=0; j< msgLen; i+=2,j++) {
  3274. hex_to_byteval(&buf[i], &msg[j]);
  3275. }
  3276. fputs(buf, resp);
  3277. /* calculate the HMAC and output */
  3278. if (hmac_calc(HMAC, HMACLen, key, keyLen,
  3279. msg, msgLen, hash_alg) != SECSuccess) {
  3280. goto loser;
  3281. }
  3282. fputs("MAC = ", resp);
  3283. to_hex_str(buf, HMAC, HMACLen);
  3284. fputs(buf, resp);
  3285. fputc('\n', resp);
  3286. continue;
  3287. }
  3288. }
  3289. loser:
  3290. if (req) {
  3291. fclose(req);
  3292. }
  3293. if (buf) {
  3294. PORT_ZFree(buf, bufSize);
  3295. }
  3296. if (msg) {
  3297. PORT_ZFree(msg, msgLen);
  3298. }
  3299. }
  3300. /*
  3301. * Perform the DSA Key Pair Generation Test.
  3302. *
  3303. * reqfn is the pathname of the REQUEST file.
  3304. *
  3305. * The output RESPONSE file is written to stdout.
  3306. */
  3307. void
  3308. dsa_keypair_test(char *reqfn)
  3309. {
  3310. char buf[260]; /* holds one line from the input REQUEST file
  3311. * or to the output RESPONSE file.
  3312. * 257 to hold (128 public key (x2 for HEX) + 1'\n'
  3313. */
  3314. FILE *dsareq; /* input stream from the REQUEST file */
  3315. FILE *dsaresp; /* output stream to the RESPONSE file */
  3316. int N; /* number of time to generate key pair */
  3317. int modulus;
  3318. int i;
  3319. PQGParams *pqg = NULL;
  3320. PQGVerify *vfy = NULL;
  3321. int keySizeIndex; /* index for valid key sizes */
  3322. dsareq = fopen(reqfn, "r");
  3323. dsaresp = stdout;
  3324. while (fgets(buf, sizeof buf, dsareq) != NULL) {
  3325. /* a comment or blank line */
  3326. if (buf[0] == '#' || buf[0] == '\n') {
  3327. fputs(buf, dsaresp);
  3328. continue;
  3329. }
  3330. /* [Mod = x] */
  3331. if (buf[0] == '[') {
  3332. if(pqg!=NULL) {
  3333. PQG_DestroyParams(pqg);
  3334. pqg = NULL;
  3335. }
  3336. if(vfy!=NULL) {
  3337. PQG_DestroyVerify(vfy);
  3338. vfy = NULL;
  3339. }
  3340. if (sscanf(buf, "[mod = %d]", &modulus) != 1) {
  3341. goto loser;
  3342. }
  3343. fputs(buf, dsaresp);
  3344. fputc('\n', dsaresp);
  3345. /*****************************************************************
  3346. * PQG_ParamGenSeedLen doesn't take a key size, it takes an index
  3347. * that points to a valid key size.
  3348. */
  3349. keySizeIndex = PQG_PBITS_TO_INDEX(modulus);
  3350. if(keySizeIndex == -1 || modulus<512 || modulus>1024) {
  3351. fprintf(dsaresp,
  3352. "DSA key size must be a multiple of 64 between 512 "
  3353. "and 1024, inclusive");
  3354. goto loser;
  3355. }
  3356. /* Generate the parameters P, Q, and G */
  3357. if (PQG_ParamGenSeedLen(keySizeIndex, PQG_TEST_SEED_BYTES,
  3358. &pqg, &vfy) != SECSuccess) {
  3359. fprintf(dsaresp, "ERROR: Unable to generate PQG parameters");
  3360. goto loser;
  3361. }
  3362. /* output P, Q, and G */
  3363. to_hex_str(buf, pqg->prime.data, pqg->prime.len);
  3364. fprintf(dsaresp, "P = %s\n", buf);
  3365. to_hex_str(buf, pqg->subPrime.data, pqg->subPrime.len);
  3366. fprintf(dsaresp, "Q = %s\n", buf);
  3367. to_hex_str(buf, pqg->base.data, pqg->base.len);
  3368. fprintf(dsaresp, "G = %s\n\n", buf);
  3369. continue;
  3370. }
  3371. /* N = ...*/
  3372. if (buf[0] == 'N') {
  3373. if (sscanf(buf, "N = %d", &N) != 1) {
  3374. goto loser;
  3375. }
  3376. /* Generate a DSA key, and output the key pair for N times */
  3377. for (i = 0; i < N; i++) {
  3378. DSAPrivateKey *dsakey = NULL;
  3379. if (DSA_NewKey(pqg, &dsakey) != SECSuccess) {
  3380. fprintf(dsaresp, "ERROR: Unable to generate DSA key");
  3381. goto loser;
  3382. }
  3383. to_hex_str(buf, dsakey->privateValue.data,
  3384. dsakey->privateValue.len);
  3385. fprintf(dsaresp, "X = %s\n", buf);
  3386. to_hex_str(buf, dsakey->publicValue.data,
  3387. dsakey->publicValue.len);
  3388. fprintf(dsaresp, "Y = %s\n\n", buf);
  3389. PORT_FreeArena(dsakey->params.arena, PR_TRUE);
  3390. dsakey = NULL;
  3391. }
  3392. continue;
  3393. }
  3394. }
  3395. loser:
  3396. fclose(dsareq);
  3397. }
  3398. /*
  3399. * Perform the DSA Domain Parameter Validation Test.
  3400. *
  3401. * reqfn is the pathname of the REQUEST file.
  3402. *
  3403. * The output RESPONSE file is written to stdout.
  3404. */
  3405. void
  3406. dsa_pqgver_test(char *reqfn)
  3407. {
  3408. char buf[263]; /* holds one line from the input REQUEST file
  3409. * or to the output RESPONSE file.
  3410. * 260 to hold (128 public key (x2 for HEX) + P = ...
  3411. */
  3412. FILE *dsareq; /* input stream from the REQUEST file */
  3413. FILE *dsaresp; /* output stream to the RESPONSE file */
  3414. int modulus;
  3415. unsigned int i, j;
  3416. PQGParams pqg;
  3417. PQGVerify vfy;
  3418. unsigned int pghSize; /* size for p, g, and h */
  3419. dsareq = fopen(reqfn, "r");
  3420. dsaresp = stdout;
  3421. memset(&pqg, 0, sizeof(pqg));
  3422. memset(&vfy, 0, sizeof(vfy));
  3423. while (fgets(buf, sizeof buf, dsareq) != NULL) {
  3424. /* a comment or blank line */
  3425. if (buf[0] == '#' || buf[0] == '\n') {
  3426. fputs(buf, dsaresp);
  3427. continue;
  3428. }
  3429. /* [Mod = x] */
  3430. if (buf[0] == '[') {
  3431. if (sscanf(buf, "[mod = %d]", &modulus) != 1) {
  3432. goto loser;
  3433. }
  3434. if (pqg.prime.data) { /* P */
  3435. SECITEM_ZfreeItem(&pqg.prime, PR_FALSE);
  3436. }
  3437. if (pqg.subPrime.data) { /* Q */
  3438. SECITEM_ZfreeItem(&pqg.subPrime, PR_FALSE);
  3439. }
  3440. if (pqg.base.data) { /* G */
  3441. SECITEM_ZfreeItem(&pqg.base, PR_FALSE);
  3442. }
  3443. if (vfy.seed.data) { /* seed */
  3444. SECITEM_ZfreeItem(&vfy.seed, PR_FALSE);
  3445. }
  3446. if (vfy.h.data) { /* H */
  3447. SECITEM_ZfreeItem(&vfy.h, PR_FALSE);
  3448. }
  3449. fputs(buf, dsaresp);
  3450. /*calculate the size of p, g, and h then allocate items */
  3451. pghSize = modulus/8;
  3452. SECITEM_AllocItem(NULL, &pqg.prime, pghSize);
  3453. SECITEM_AllocItem(NULL, &pqg.base, pghSize);
  3454. SECITEM_AllocItem(NULL, &vfy.h, pghSize);
  3455. pqg.prime.len = pqg.base.len = vfy.h.len = pghSize;
  3456. /* seed and q are always 20 bytes */
  3457. SECITEM_AllocItem(NULL, &vfy.seed, 20);
  3458. SECITEM_AllocItem(NULL, &pqg.subPrime, 20);
  3459. vfy.seed.len = pqg.subPrime.len = 20;
  3460. vfy.counter = 0;
  3461. continue;
  3462. }
  3463. /* P = ... */
  3464. if (buf[0] == 'P') {
  3465. i = 1;
  3466. while (isspace(buf[i]) || buf[i] == '=') {
  3467. i++;
  3468. }
  3469. for (j=0; j< pqg.prime.len; i+=2,j++) {
  3470. hex_to_byteval(&buf[i], &pqg.prime.data[j]);
  3471. }
  3472. fputs(buf, dsaresp);
  3473. continue;
  3474. }
  3475. /* Q = ... */
  3476. if (buf[0] == 'Q') {
  3477. i = 1;
  3478. while (isspace(buf[i]) || buf[i] == '=') {
  3479. i++;
  3480. }
  3481. for (j=0; j< pqg.subPrime.len; i+=2,j++) {
  3482. hex_to_byteval(&buf[i], &pqg.subPrime.data[j]);
  3483. }
  3484. fputs(buf, dsaresp);
  3485. continue;
  3486. }
  3487. /* G = ... */
  3488. if (buf[0] == 'G') {
  3489. i = 1;
  3490. while (isspace(buf[i]) || buf[i] == '=') {
  3491. i++;
  3492. }
  3493. for (j=0; j< pqg.base.len; i+=2,j++) {
  3494. hex_to_byteval(&buf[i], &pqg.base.data[j]);
  3495. }
  3496. fputs(buf, dsaresp);
  3497. continue;
  3498. }
  3499. /* Seed = ... */
  3500. if (strncmp(buf, "Seed", 4) == 0) {
  3501. i = 4;
  3502. while (isspace(buf[i]) || buf[i] == '=') {
  3503. i++;
  3504. }
  3505. for (j=0; j< vfy.seed.len; i+=2,j++) {
  3506. hex_to_byteval(&buf[i], &vfy.seed.data[j]);
  3507. }
  3508. fputs(buf, dsaresp);
  3509. continue;
  3510. }
  3511. /* c = ... */
  3512. if (buf[0] == 'c') {
  3513. if (sscanf(buf, "c = %u", &vfy.counter) != 1) {
  3514. goto loser;
  3515. }
  3516. fputs(buf, dsaresp);
  3517. continue;
  3518. }
  3519. /* H = ... */
  3520. if (buf[0] == 'H') {
  3521. SECStatus rv, result = SECFailure;
  3522. i = 1;
  3523. while (isspace(buf[i]) || buf[i] == '=') {
  3524. i++;
  3525. }
  3526. for (j=0; j< vfy.h.len; i+=2,j++) {
  3527. hex_to_byteval(&buf[i], &vfy.h.data[j]);
  3528. }
  3529. fputs(buf, dsaresp);
  3530. /* Verify the Parameters */
  3531. rv = PQG_VerifyParams(&pqg, &vfy, &result);
  3532. if (rv != SECSuccess) {
  3533. goto loser;
  3534. }
  3535. if (result == SECSuccess) {
  3536. fprintf(dsaresp, "Result = P\n");
  3537. } else {
  3538. fprintf(dsaresp, "Result = F\n");
  3539. }
  3540. continue;
  3541. }
  3542. }
  3543. loser:
  3544. fclose(dsareq);
  3545. if (pqg.prime.data) { /* P */
  3546. SECITEM_ZfreeItem(&pqg.prime, PR_FALSE);
  3547. }
  3548. if (pqg.subPrime.data) { /* Q */
  3549. SECITEM_ZfreeItem(&pqg.subPrime, PR_FALSE);
  3550. }
  3551. if (pqg.base.data) { /* G */
  3552. SECITEM_ZfreeItem(&pqg.base, PR_FALSE);
  3553. }
  3554. if (vfy.seed.data) { /* seed */
  3555. SECITEM_ZfreeItem(&vfy.seed, PR_FALSE);
  3556. }
  3557. if (vfy.h.data) { /* H */
  3558. SECITEM_ZfreeItem(&vfy.h, PR_FALSE);
  3559. }
  3560. }
  3561. /*
  3562. * Perform the DSA Public Key Validation Test.
  3563. *
  3564. * reqfn is the pathname of the REQUEST file.
  3565. *
  3566. * The output RESPONSE file is written to stdout.
  3567. */
  3568. void
  3569. dsa_pqggen_test(char *reqfn)
  3570. {
  3571. char buf[263]; /* holds one line from the input REQUEST file
  3572. * or to the output RESPONSE file.
  3573. * 263 to hold seed = (128 public key (x2 for HEX)
  3574. */
  3575. FILE *dsareq; /* input stream from the REQUEST file */
  3576. FILE *dsaresp; /* output stream to the RESPONSE file */
  3577. int N; /* number of times to generate parameters */
  3578. int modulus;
  3579. int i;
  3580. unsigned int j;
  3581. PQGParams *pqg = NULL;
  3582. PQGVerify *vfy = NULL;
  3583. unsigned int keySizeIndex;
  3584. dsareq = fopen(reqfn, "r");
  3585. dsaresp = stdout;
  3586. while (fgets(buf, sizeof buf, dsareq) != NULL) {
  3587. /* a comment or blank line */
  3588. if (buf[0] == '#' || buf[0] == '\n') {
  3589. fputs(buf, dsaresp);
  3590. continue;
  3591. }
  3592. /* [Mod = ... ] */
  3593. if (buf[0] == '[') {
  3594. if (sscanf(buf, "[mod = %d]", &modulus) != 1) {
  3595. goto loser;
  3596. }
  3597. fputs(buf, dsaresp);
  3598. fputc('\n', dsaresp);
  3599. /****************************************************************
  3600. * PQG_ParamGenSeedLen doesn't take a key size, it takes an index
  3601. * that points to a valid key size.
  3602. */
  3603. keySizeIndex = PQG_PBITS_TO_INDEX(modulus);
  3604. if(keySizeIndex == -1 || modulus<512 || modulus>1024) {
  3605. fprintf(dsaresp,
  3606. "DSA key size must be a multiple of 64 between 512 "
  3607. "and 1024, inclusive");
  3608. goto loser;
  3609. }
  3610. continue;
  3611. }
  3612. /* N = ... */
  3613. if (buf[0] == 'N') {
  3614. if (sscanf(buf, "N = %d", &N) != 1) {
  3615. goto loser;
  3616. }
  3617. for (i = 0; i < N; i++) {
  3618. if (PQG_ParamGenSeedLen(keySizeIndex, PQG_TEST_SEED_BYTES,
  3619. &pqg, &vfy) != SECSuccess) {
  3620. fprintf(dsaresp,
  3621. "ERROR: Unable to generate PQG parameters");
  3622. goto loser;
  3623. }
  3624. to_hex_str(buf, pqg->prime.data, pqg->prime.len);
  3625. fprintf(dsaresp, "P = %s\n", buf);
  3626. to_hex_str(buf, pqg->subPrime.data, pqg->subPrime.len);
  3627. fprintf(dsaresp, "Q = %s\n", buf);
  3628. to_hex_str(buf, pqg->base.data, pqg->base.len);
  3629. fprintf(dsaresp, "G = %s\n", buf);
  3630. to_hex_str(buf, vfy->seed.data, vfy->seed.len);
  3631. fprintf(dsaresp, "Seed = %s\n", buf);
  3632. fprintf(dsaresp, "c = %d\n", vfy->counter);
  3633. to_hex_str(buf, vfy->h.data, vfy->h.len);
  3634. fputs("H = ", dsaresp);
  3635. for (j=vfy->h.len; j<pqg->prime.len; j++) {
  3636. fprintf(dsaresp, "00");
  3637. }
  3638. fprintf(dsaresp, "%s\n", buf);
  3639. fputc('\n', dsaresp);
  3640. if(pqg!=NULL) {
  3641. PQG_DestroyParams(pqg);
  3642. pqg = NULL;
  3643. }
  3644. if(vfy!=NULL) {
  3645. PQG_DestroyVerify(vfy);
  3646. vfy = NULL;
  3647. }
  3648. }
  3649. continue;
  3650. }
  3651. }
  3652. loser:
  3653. fclose(dsareq);
  3654. if(pqg!=NULL) {
  3655. PQG_DestroyParams(pqg);
  3656. }
  3657. if(vfy!=NULL) {
  3658. PQG_DestroyVerify(vfy);
  3659. }
  3660. }
  3661. /*
  3662. * Perform the DSA Signature Generation Test.
  3663. *
  3664. * reqfn is the pathname of the REQUEST file.
  3665. *
  3666. * The output RESPONSE file is written to stdout.
  3667. */
  3668. void
  3669. dsa_siggen_test(char *reqfn)
  3670. {
  3671. char buf[263]; /* holds one line from the input REQUEST file
  3672. * or to the output RESPONSE file.
  3673. * max for Msg = ....
  3674. */
  3675. FILE *dsareq; /* input stream from the REQUEST file */
  3676. FILE *dsaresp; /* output stream to the RESPONSE file */
  3677. int modulus;
  3678. int i, j;
  3679. PQGParams *pqg = NULL;
  3680. PQGVerify *vfy = NULL;
  3681. DSAPrivateKey *dsakey = NULL;
  3682. int keySizeIndex; /* index for valid key sizes */
  3683. unsigned char sha1[20]; /* SHA-1 hash (160 bits) */
  3684. unsigned char sig[DSA_SIGNATURE_LEN];
  3685. SECItem digest, signature;
  3686. dsareq = fopen(reqfn, "r");
  3687. dsaresp = stdout;
  3688. while (fgets(buf, sizeof buf, dsareq) != NULL) {
  3689. /* a comment or blank line */
  3690. if (buf[0] == '#' || buf[0] == '\n') {
  3691. fputs(buf, dsaresp);
  3692. continue;
  3693. }
  3694. /* [Mod = x] */
  3695. if (buf[0] == '[') {
  3696. if(pqg!=NULL) {
  3697. PQG_DestroyParams(pqg);
  3698. pqg = NULL;
  3699. }
  3700. if(vfy!=NULL) {
  3701. PQG_DestroyVerify(vfy);
  3702. vfy = NULL;
  3703. }
  3704. if (dsakey != NULL) {
  3705. PORT_FreeArena(dsakey->params.arena, PR_TRUE);
  3706. dsakey = NULL;
  3707. }
  3708. if (sscanf(buf, "[mod = %d]", &modulus) != 1) {
  3709. goto loser;
  3710. }
  3711. fputs(buf, dsaresp);
  3712. fputc('\n', dsaresp);
  3713. /****************************************************************
  3714. * PQG_ParamGenSeedLen doesn't take a key size, it takes an index
  3715. * that points to a valid key size.
  3716. */
  3717. keySizeIndex = PQG_PBITS_TO_INDEX(modulus);
  3718. if(keySizeIndex == -1 || modulus<512 || modulus>1024) {
  3719. fprintf(dsaresp,
  3720. "DSA key size must be a multiple of 64 between 512 "
  3721. "and 1024, inclusive");
  3722. goto loser;
  3723. }
  3724. /* Generate PQG and output PQG */
  3725. if (PQG_ParamGenSeedLen(keySizeIndex, PQG_TEST_SEED_BYTES,
  3726. &pqg, &vfy) != SECSuccess) {
  3727. fprintf(dsaresp, "ERROR: Unable to generate PQG parameters");
  3728. goto loser;
  3729. }
  3730. to_hex_str(buf, pqg->prime.data, pqg->prime.len);
  3731. fprintf(dsaresp, "P = %s\n", buf);
  3732. to_hex_str(buf, pqg->subPrime.data, pqg->subPrime.len);
  3733. fprintf(dsaresp, "Q = %s\n", buf);
  3734. to_hex_str(buf, pqg->base.data, pqg->base.len);
  3735. fprintf(dsaresp, "G = %s\n", buf);
  3736. /* create DSA Key */
  3737. if (DSA_NewKey(pqg, &dsakey) != SECSuccess) {
  3738. fprintf(dsaresp, "ERROR: Unable to generate DSA key");
  3739. goto loser;
  3740. }
  3741. continue;
  3742. }
  3743. /* Msg = ... */
  3744. if (strncmp(buf, "Msg", 3) == 0) {
  3745. unsigned char msg[128]; /* MAX msg 128 */
  3746. unsigned int len = 0;
  3747. memset(sha1, 0, sizeof sha1);
  3748. memset(sig, 0, sizeof sig);
  3749. i = 3;
  3750. while (isspace(buf[i]) || buf[i] == '=') {
  3751. i++;
  3752. }
  3753. for (j=0; isxdigit(buf[i]); i+=2,j++) {
  3754. hex_to_byteval(&buf[i], &msg[j]);
  3755. }
  3756. if (SHA1_HashBuf(sha1, msg, j) != SECSuccess) {
  3757. fprintf(dsaresp, "ERROR: Unable to generate SHA1 digest");
  3758. goto loser;
  3759. }
  3760. digest.type = siBuffer;
  3761. digest.data = sha1;
  3762. digest.len = sizeof sha1;
  3763. signature.type = siBuffer;
  3764. signature.data = sig;
  3765. signature.len = sizeof sig;
  3766. if (DSA_SignDigest(dsakey, &signature, &digest) != SECSuccess) {
  3767. fprintf(dsaresp, "ERROR: Unable to generate DSA signature");
  3768. goto loser;
  3769. }
  3770. len = signature.len;
  3771. if (len%2 != 0) {
  3772. goto loser;
  3773. }
  3774. len = len/2;
  3775. /* output the orginal Msg, and generated Y, R, and S */
  3776. fputs(buf, dsaresp);
  3777. fputc('\n', dsaresp);
  3778. to_hex_str(buf, dsakey->publicValue.data,
  3779. dsakey->publicValue.len);
  3780. fprintf(dsaresp, "Y = %s\n", buf);
  3781. to_hex_str(buf, &signature.data[0], len);
  3782. fprintf(dsaresp, "R = %s\n", buf);
  3783. to_hex_str(buf, &signature.data[len], len);
  3784. fprintf(dsaresp, "S = %s\n", buf);
  3785. continue;
  3786. }
  3787. }
  3788. loser:
  3789. fclose(dsareq);
  3790. if(pqg != NULL) {
  3791. PQG_DestroyParams(pqg);
  3792. pqg = NULL;
  3793. }
  3794. if(vfy != NULL) {
  3795. PQG_DestroyVerify(vfy);
  3796. vfy = NULL;
  3797. }
  3798. if (dsaKey) {
  3799. PORT_FreeArena(dsakey->params.arena, PR_TRUE);
  3800. dsakey = NULL;
  3801. }
  3802. }
  3803. /*
  3804. * Perform the DSA Signature Verification Test.
  3805. *
  3806. * reqfn is the pathname of the REQUEST file.
  3807. *
  3808. * The output RESPONSE file is written to stdout.
  3809. */
  3810. void
  3811. dsa_sigver_test(char *reqfn)
  3812. {
  3813. char buf[263]; /* holds one line from the input REQUEST file
  3814. * or to the output RESPONSE file.
  3815. * max for Msg = ....
  3816. */
  3817. FILE *dsareq; /* input stream from the REQUEST file */
  3818. FILE *dsaresp; /* output stream to the RESPONSE file */
  3819. int modulus;
  3820. unsigned int i, j;
  3821. SECItem digest, signature;
  3822. DSAPublicKey pubkey;
  3823. unsigned int pgySize; /* size for p, g, and y */
  3824. unsigned char sha1[20]; /* SHA-1 hash (160 bits) */
  3825. unsigned char sig[DSA_SIGNATURE_LEN];
  3826. dsareq = fopen(reqfn, "r");
  3827. dsaresp = stdout;
  3828. memset(&pubkey, 0, sizeof(pubkey));
  3829. while (fgets(buf, sizeof buf, dsareq) != NULL) {
  3830. /* a comment or blank line */
  3831. if (buf[0] == '#' || buf[0] == '\n') {
  3832. fputs(buf, dsaresp);
  3833. continue;
  3834. }
  3835. /* [Mod = x] */
  3836. if (buf[0] == '[') {
  3837. if (sscanf(buf, "[mod = %d]", &modulus) != 1) {
  3838. goto loser;
  3839. }
  3840. if (pubkey.params.prime.data) { /* P */
  3841. SECITEM_ZfreeItem(&pubkey.params.prime, PR_FALSE);
  3842. }
  3843. if (pubkey.params.subPrime.data) { /* Q */
  3844. SECITEM_ZfreeItem(&pubkey.params.subPrime, PR_FALSE);
  3845. }
  3846. if (pubkey.params.base.data) { /* G */
  3847. SECITEM_ZfreeItem(&pubkey.params.base, PR_FALSE);
  3848. }
  3849. if (pubkey.publicValue.data) { /* Y */
  3850. SECITEM_ZfreeItem(&pubkey.publicValue, PR_FALSE);
  3851. }
  3852. fputs(buf, dsaresp);
  3853. /* calculate the size of p, g, and y then allocate items */
  3854. pgySize = modulus/8;
  3855. SECITEM_AllocItem(NULL, &pubkey.params.prime, pgySize);
  3856. SECITEM_AllocItem(NULL, &pubkey.params.base, pgySize);
  3857. SECITEM_AllocItem(NULL, &pubkey.publicValue, pgySize);
  3858. pubkey.params.prime.len = pubkey.params.base.len = pgySize;
  3859. pubkey.publicValue.len = pgySize;
  3860. /* q always 20 bytes */
  3861. SECITEM_AllocItem(NULL, &pubkey.params.subPrime, 20);
  3862. pubkey.params.subPrime.len = 20;
  3863. continue;
  3864. }
  3865. /* P = ... */
  3866. if (buf[0] == 'P') {
  3867. i = 1;
  3868. while (isspace(buf[i]) || buf[i] == '=') {
  3869. i++;
  3870. }
  3871. memset(pubkey.params.prime.data, 0, pubkey.params.prime.len);
  3872. for (j=0; j< pubkey.params.prime.len; i+=2,j++) {
  3873. hex_to_byteval(&buf[i], &pubkey.params.prime.data[j]);
  3874. }
  3875. fputs(buf, dsaresp);
  3876. continue;
  3877. }
  3878. /* Q = ... */
  3879. if (buf[0] == 'Q') {
  3880. i = 1;
  3881. while (isspace(buf[i]) || buf[i] == '=') {
  3882. i++;
  3883. }
  3884. memset(pubkey.params.subPrime.data, 0, pubkey.params.subPrime.len);
  3885. for (j=0; j< pubkey.params.subPrime.len; i+=2,j++) {
  3886. hex_to_byteval(&buf[i], &pubkey.params.subPrime.data[j]);
  3887. }
  3888. fputs(buf, dsaresp);
  3889. continue;
  3890. }
  3891. /* G = ... */
  3892. if (buf[0] == 'G') {
  3893. i = 1;
  3894. while (isspace(buf[i]) || buf[i] == '=') {
  3895. i++;
  3896. }
  3897. memset(pubkey.params.base.data, 0, pubkey.params.base.len);
  3898. for (j=0; j< pubkey.params.base.len; i+=2,j++) {
  3899. hex_to_byteval(&buf[i], &pubkey.params.base.data[j]);
  3900. }
  3901. fputs(buf, dsaresp);
  3902. continue;
  3903. }
  3904. /* Msg = ... */
  3905. if (strncmp(buf, "Msg", 3) == 0) {
  3906. unsigned char msg[128]; /* MAX msg 128 */
  3907. memset(sha1, 0, sizeof sha1);
  3908. i = 3;
  3909. while (isspace(buf[i]) || buf[i] == '=') {
  3910. i++;
  3911. }
  3912. for (j=0; isxdigit(buf[i]); i+=2,j++) {
  3913. hex_to_byteval(&buf[i], &msg[j]);
  3914. }
  3915. if (SHA1_HashBuf(sha1, msg, j) != SECSuccess) {
  3916. fprintf(dsaresp, "ERROR: Unable to generate SHA1 digest");
  3917. goto loser;
  3918. }
  3919. fputs(buf, dsaresp);
  3920. continue;
  3921. }
  3922. /* Y = ... */
  3923. if (buf[0] == 'Y') {
  3924. i = 1;
  3925. while (isspace(buf[i]) || buf[i] == '=') {
  3926. i++;
  3927. }
  3928. memset(pubkey.publicValue.data, 0, pubkey.params.subPrime.len);
  3929. for (j=0; j< pubkey.publicValue.len; i+=2,j++) {
  3930. hex_to_byteval(&buf[i], &pubkey.publicValue.data[j]);
  3931. }
  3932. fputs(buf, dsaresp);
  3933. continue;
  3934. }
  3935. /* R = ... */
  3936. if (buf[0] == 'R') {
  3937. memset(sig, 0, sizeof sig);
  3938. i = 1;
  3939. while (isspace(buf[i]) || buf[i] == '=') {
  3940. i++;
  3941. }
  3942. for (j=0; j< DSA_SUBPRIME_LEN; i+=2,j++) {
  3943. hex_to_byteval(&buf[i], &sig[j]);
  3944. }
  3945. fputs(buf, dsaresp);
  3946. continue;
  3947. }
  3948. /* S = ... */
  3949. if (buf[0] == 'S') {
  3950. i = 1;
  3951. while (isspace(buf[i]) || buf[i] == '=') {
  3952. i++;
  3953. }
  3954. for (j=DSA_SUBPRIME_LEN; j< DSA_SIGNATURE_LEN; i+=2,j++) {
  3955. hex_to_byteval(&buf[i], &sig[j]);
  3956. }
  3957. fputs(buf, dsaresp);
  3958. digest.type = siBuffer;
  3959. digest.data = sha1;
  3960. digest.len = sizeof sha1;
  3961. signature.type = siBuffer;
  3962. signature.data = sig;
  3963. signature.len = sizeof sig;
  3964. if (DSA_VerifyDigest(&pubkey, &signature, &digest) == SECSuccess) {
  3965. fprintf(dsaresp, "Result = P\n");
  3966. } else {
  3967. fprintf(dsaresp, "Result = F\n");
  3968. }
  3969. continue;
  3970. }
  3971. }
  3972. loser:
  3973. fclose(dsareq);
  3974. if (pubkey.params.prime.data) { /* P */
  3975. SECITEM_ZfreeItem(&pubkey.params.prime, PR_FALSE);
  3976. }
  3977. if (pubkey.params.subPrime.data) { /* Q */
  3978. SECITEM_ZfreeItem(&pubkey.params.subPrime, PR_FALSE);
  3979. }
  3980. if (pubkey.params.base.data) { /* G */
  3981. SECITEM_ZfreeItem(&pubkey.params.base, PR_FALSE);
  3982. }
  3983. if (pubkey.publicValue.data) { /* Y */
  3984. SECITEM_ZfreeItem(&pubkey.publicValue, PR_FALSE);
  3985. }
  3986. }
  3987. /*
  3988. * Perform the RSA Signature Generation Test.
  3989. *
  3990. * reqfn is the pathname of the REQUEST file.
  3991. *
  3992. * The output RESPONSE file is written to stdout.
  3993. */
  3994. void
  3995. rsa_siggen_test(char *reqfn)
  3996. {
  3997. char buf[2*RSA_MAX_TEST_MODULUS_BYTES+1];
  3998. /* buf holds one line from the input REQUEST file
  3999. * or to the output RESPONSE file.
  4000. * 2x for HEX output + 1 for \n
  4001. */
  4002. FILE *rsareq; /* input stream from the REQUEST file */
  4003. FILE *rsaresp; /* output stream to the RESPONSE file */
  4004. int i, j;
  4005. unsigned char sha[HASH_LENGTH_MAX]; /* SHA digest */
  4006. unsigned int shaLength = 0; /* length of SHA */
  4007. HASH_HashType shaAlg = HASH_AlgNULL; /* type of SHA Alg */
  4008. SECOidTag shaOid = SEC_OID_UNKNOWN;
  4009. int modulus; /* the Modulus size */
  4010. int publicExponent = DEFAULT_RSA_PUBLIC_EXPONENT;
  4011. SECItem pe = {0, 0, 0 };
  4012. unsigned char pubEx[4];
  4013. int peCount = 0;
  4014. RSAPrivateKey *rsaBlapiPrivKey = NULL; /* holds RSA private and
  4015. * public keys */
  4016. RSAPublicKey *rsaBlapiPublicKey = NULL; /* hold RSA public key */
  4017. rsareq = fopen(reqfn, "r");
  4018. rsaresp = stdout;
  4019. /* calculate the exponent */
  4020. for (i=0; i < 4; i++) {
  4021. if (peCount || (publicExponent &
  4022. ((unsigned long)0xff000000L >> (i*8)))) {
  4023. pubEx[peCount] =
  4024. (unsigned char)((publicExponent >> (3-i)*8) & 0xff);
  4025. peCount++;
  4026. }
  4027. }
  4028. pe.len = peCount;
  4029. pe.data = &pubEx[0];
  4030. pe.type = siBuffer;
  4031. while (fgets(buf, sizeof buf, rsareq) != NULL) {
  4032. /* a comment or blank line */
  4033. if (buf[0] == '#' || buf[0] == '\n') {
  4034. fputs(buf, rsaresp);
  4035. continue;
  4036. }
  4037. /* [mod = ...] */
  4038. if (buf[0] == '[') {
  4039. if (sscanf(buf, "[mod = %d]", &modulus) != 1) {
  4040. goto loser;
  4041. }
  4042. if (modulus > RSA_MAX_TEST_MODULUS_BITS) {
  4043. fprintf(rsaresp,"ERROR: modulus greater than test maximum\n");
  4044. goto loser;
  4045. }
  4046. fputs(buf, rsaresp);
  4047. if (rsaBlapiPrivKey != NULL) {
  4048. PORT_FreeArena(rsaBlapiPrivKey->arena, PR_TRUE);
  4049. rsaBlapiPrivKey = NULL;
  4050. rsaBlapiPublicKey = NULL;
  4051. }
  4052. rsaBlapiPrivKey = RSA_NewKey(modulus, &pe);
  4053. if (rsaBlapiPrivKey == NULL) {
  4054. fprintf(rsaresp, "Error unable to create RSA key\n");
  4055. goto loser;
  4056. }
  4057. to_hex_str(buf, rsaBlapiPrivKey->modulus.data,
  4058. rsaBlapiPrivKey->modulus.len);
  4059. fprintf(rsaresp, "\nn = %s\n\n", buf);
  4060. to_hex_str(buf, rsaBlapiPrivKey->publicExponent.data,
  4061. rsaBlapiPrivKey->publicExponent.len);
  4062. fprintf(rsaresp, "e = %s\n", buf);
  4063. /* convert private key to public key. Memory
  4064. * is freed with private key's arena */
  4065. rsaBlapiPublicKey = (RSAPublicKey *)PORT_ArenaAlloc(
  4066. rsaBlapiPrivKey->arena,
  4067. sizeof(RSAPublicKey));
  4068. rsaBlapiPublicKey->modulus.len = rsaBlapiPrivKey->modulus.len;
  4069. rsaBlapiPublicKey->modulus.data = rsaBlapiPrivKey->modulus.data;
  4070. rsaBlapiPublicKey->publicExponent.len =
  4071. rsaBlapiPrivKey->publicExponent.len;
  4072. rsaBlapiPublicKey->publicExponent.data =
  4073. rsaBlapiPrivKey->publicExponent.data;
  4074. continue;
  4075. }
  4076. /* SHAAlg = ... */
  4077. if (strncmp(buf, "SHAAlg", 6) == 0) {
  4078. i = 6;
  4079. while (isspace(buf[i]) || buf[i] == '=') {
  4080. i++;
  4081. }
  4082. /* set the SHA Algorithm */
  4083. if (strncmp(&buf[i], "SHA1", 4) == 0) {
  4084. shaAlg = HASH_AlgSHA1;
  4085. } else if (strncmp(&buf[i], "SHA256", 6) == 0) {
  4086. shaAlg = HASH_AlgSHA256;
  4087. } else if (strncmp(&buf[i], "SHA384", 6)== 0) {
  4088. shaAlg = HASH_AlgSHA384;
  4089. } else if (strncmp(&buf[i], "SHA512", 6) == 0) {
  4090. shaAlg = HASH_AlgSHA512;
  4091. } else {
  4092. fprintf(rsaresp, "ERROR: Unable to find SHAAlg type");
  4093. goto loser;
  4094. }
  4095. fputs(buf, rsaresp);
  4096. continue;
  4097. }
  4098. /* Msg = ... */
  4099. if (strncmp(buf, "Msg", 3) == 0) {
  4100. unsigned char msg[128]; /* MAX msg 128 */
  4101. unsigned int rsa_bytes_signed;
  4102. unsigned char rsa_computed_signature[RSA_MAX_TEST_MODULUS_BYTES];
  4103. SECStatus rv = SECFailure;
  4104. NSSLOWKEYPublicKey * rsa_public_key;
  4105. NSSLOWKEYPrivateKey * rsa_private_key;
  4106. NSSLOWKEYPrivateKey low_RSA_private_key = { NULL,
  4107. NSSLOWKEYRSAKey, };
  4108. NSSLOWKEYPublicKey low_RSA_public_key = { NULL,
  4109. NSSLOWKEYRSAKey, };
  4110. low_RSA_private_key.u.rsa = *rsaBlapiPrivKey;
  4111. low_RSA_public_key.u.rsa = *rsaBlapiPublicKey;
  4112. rsa_private_key = &low_RSA_private_key;
  4113. rsa_public_key = &low_RSA_public_key;
  4114. memset(sha, 0, sizeof sha);
  4115. memset(msg, 0, sizeof msg);
  4116. rsa_bytes_signed = 0;
  4117. memset(rsa_computed_signature, 0, sizeof rsa_computed_signature);
  4118. i = 3;
  4119. while (isspace(buf[i]) || buf[i] == '=') {
  4120. i++;
  4121. }
  4122. for (j=0; isxdigit(buf[i]) && j < sizeof(msg); i+=2,j++) {
  4123. hex_to_byteval(&buf[i], &msg[j]);
  4124. }
  4125. if (shaAlg == HASH_AlgSHA1) {
  4126. if (SHA1_HashBuf(sha, msg, j) != SECSuccess) {
  4127. fprintf(rsaresp, "ERROR: Unable to generate SHA1");
  4128. goto loser;
  4129. }
  4130. shaLength = SHA1_LENGTH;
  4131. shaOid = SEC_OID_SHA1;
  4132. } else if (shaAlg == HASH_AlgSHA256) {
  4133. if (SHA256_HashBuf(sha, msg, j) != SECSuccess) {
  4134. fprintf(rsaresp, "ERROR: Unable to generate SHA256");
  4135. goto loser;
  4136. }
  4137. shaLength = SHA256_LENGTH;
  4138. shaOid = SEC_OID_SHA256;
  4139. } else if (shaAlg == HASH_AlgSHA384) {
  4140. if (SHA384_HashBuf(sha, msg, j) != SECSuccess) {
  4141. fprintf(rsaresp, "ERROR: Unable to generate SHA384");
  4142. goto loser;
  4143. }
  4144. shaLength = SHA384_LENGTH;
  4145. shaOid = SEC_OID_SHA384;
  4146. } else if (shaAlg == HASH_AlgSHA512) {
  4147. if (SHA512_HashBuf(sha, msg, j) != SECSuccess) {
  4148. fprintf(rsaresp, "ERROR: Unable to generate SHA512");
  4149. goto loser;
  4150. }
  4151. shaLength = SHA512_LENGTH;
  4152. shaOid = SEC_OID_SHA512;
  4153. } else {
  4154. fprintf(rsaresp, "ERROR: SHAAlg not defined.");
  4155. goto loser;
  4156. }
  4157. /* Perform RSA signature with the RSA private key. */
  4158. rv = RSA_HashSign( shaOid,
  4159. rsa_private_key,
  4160. rsa_computed_signature,
  4161. &rsa_bytes_signed,
  4162. nsslowkey_PrivateModulusLen(rsa_private_key),
  4163. sha,
  4164. shaLength);
  4165. if( rv != SECSuccess ) {
  4166. fprintf(rsaresp, "ERROR: RSA_HashSign failed");
  4167. goto loser;
  4168. }
  4169. /* Output the signature */
  4170. fputs(buf, rsaresp);
  4171. to_hex_str(buf, rsa_computed_signature, rsa_bytes_signed);
  4172. fprintf(rsaresp, "S = %s\n", buf);
  4173. /* Perform RSA verification with the RSA public key. */
  4174. rv = RSA_HashCheckSign( shaOid,
  4175. rsa_public_key,
  4176. rsa_computed_signature,
  4177. rsa_bytes_signed,
  4178. sha,
  4179. shaLength);
  4180. if( rv != SECSuccess ) {
  4181. fprintf(rsaresp, "ERROR: RSA_HashCheckSign failed");
  4182. goto loser;
  4183. }
  4184. continue;
  4185. }
  4186. }
  4187. loser:
  4188. fclose(rsareq);
  4189. if (rsaBlapiPrivKey != NULL) {
  4190. /* frees private and public key */
  4191. PORT_FreeArena(rsaBlapiPrivKey->arena, PR_TRUE);
  4192. rsaBlapiPrivKey = NULL;
  4193. rsaBlapiPublicKey = NULL;
  4194. }
  4195. }
  4196. /*
  4197. * Perform the RSA Signature Verification Test.
  4198. *
  4199. * reqfn is the pathname of the REQUEST file.
  4200. *
  4201. * The output RESPONSE file is written to stdout.
  4202. */
  4203. void
  4204. rsa_sigver_test(char *reqfn)
  4205. {
  4206. char buf[2*RSA_MAX_TEST_MODULUS_BYTES+7];
  4207. /* buf holds one line from the input REQUEST file
  4208. * or to the output RESPONSE file.
  4209. * s = 2x for HEX output + 1 for \n
  4210. */
  4211. FILE *rsareq; /* input stream from the REQUEST file */
  4212. FILE *rsaresp; /* output stream to the RESPONSE file */
  4213. int i, j;
  4214. unsigned char sha[HASH_LENGTH_MAX]; /* SHA digest */
  4215. unsigned int shaLength = 0; /* actual length of the digest */
  4216. HASH_HashType shaAlg = HASH_AlgNULL;
  4217. SECOidTag shaOid = SEC_OID_UNKNOWN;
  4218. int modulus = 0; /* the Modulus size */
  4219. unsigned char signature[513]; /* largest signature size + '\n' */
  4220. unsigned int signatureLength = 0; /* actual length of the signature */
  4221. PRBool keyvalid = PR_TRUE;
  4222. RSAPublicKey rsaBlapiPublicKey; /* hold RSA public key */
  4223. rsareq = fopen(reqfn, "r");
  4224. rsaresp = stdout;
  4225. memset(&rsaBlapiPublicKey, 0, sizeof(RSAPublicKey));
  4226. while (fgets(buf, sizeof buf, rsareq) != NULL) {
  4227. /* a comment or blank line */
  4228. if (buf[0] == '#' || buf[0] == '\n') {
  4229. fputs(buf, rsaresp);
  4230. continue;
  4231. }
  4232. /* [Mod = ...] */
  4233. if (buf[0] == '[') {
  4234. unsigned int flen; /* length in bytes of the field size */
  4235. if (rsaBlapiPublicKey.modulus.data) { /* n */
  4236. SECITEM_ZfreeItem(&rsaBlapiPublicKey.modulus, PR_FALSE);
  4237. }
  4238. if (sscanf(buf, "[mod = %d]", &modulus) != 1) {
  4239. goto loser;
  4240. }
  4241. if (modulus > RSA_MAX_TEST_MODULUS_BITS) {
  4242. fprintf(rsaresp,"ERROR: modulus greater than test maximum\n");
  4243. goto loser;
  4244. }
  4245. fputs(buf, rsaresp);
  4246. signatureLength = flen = modulus/8;
  4247. SECITEM_AllocItem(NULL, &rsaBlapiPublicKey.modulus, flen);
  4248. if (rsaBlapiPublicKey.modulus.data == NULL) {
  4249. goto loser;
  4250. }
  4251. continue;
  4252. }
  4253. /* n = ... modulus */
  4254. if (buf[0] == 'n') {
  4255. i = 1;
  4256. while (isspace(buf[i]) || buf[i] == '=') {
  4257. i++;
  4258. }
  4259. keyvalid = from_hex_str(&rsaBlapiPublicKey.modulus.data[0],
  4260. rsaBlapiPublicKey.modulus.len,
  4261. &buf[i]);
  4262. if (!keyvalid) {
  4263. fprintf(rsaresp, "ERROR: rsa_sigver n not valid.\n");
  4264. goto loser;
  4265. }
  4266. fputs(buf, rsaresp);
  4267. continue;
  4268. }
  4269. /* SHAAlg = ... */
  4270. if (strncmp(buf, "SHAAlg", 6) == 0) {
  4271. i = 6;
  4272. while (isspace(buf[i]) || buf[i] == '=') {
  4273. i++;
  4274. }
  4275. /* set the SHA Algorithm */
  4276. if (strncmp(&buf[i], "SHA1", 4) == 0) {
  4277. shaAlg = HASH_AlgSHA1;
  4278. } else if (strncmp(&buf[i], "SHA256", 6) == 0) {
  4279. shaAlg = HASH_AlgSHA256;
  4280. } else if (strncmp(&buf[i], "SHA384", 6) == 0) {
  4281. shaAlg = HASH_AlgSHA384;
  4282. } else if (strncmp(&buf[i], "SHA512", 6) == 0) {
  4283. shaAlg = HASH_AlgSHA512;
  4284. } else {
  4285. fprintf(rsaresp, "ERROR: Unable to find SHAAlg type");
  4286. goto loser;
  4287. }
  4288. fputs(buf, rsaresp);
  4289. continue;
  4290. }
  4291. /* e = ... public Key */
  4292. if (buf[0] == 'e') {
  4293. unsigned char data[RSA_MAX_TEST_EXPONENT_BYTES];
  4294. unsigned char t;
  4295. memset(data, 0, sizeof data);
  4296. if (rsaBlapiPublicKey.publicExponent.data) { /* e */
  4297. SECITEM_ZfreeItem(&rsaBlapiPublicKey.publicExponent, PR_FALSE);
  4298. }
  4299. i = 1;
  4300. while (isspace(buf[i]) || buf[i] == '=') {
  4301. i++;
  4302. }
  4303. /* skip leading zero's */
  4304. while (isxdigit(buf[i])) {
  4305. hex_to_byteval(&buf[i], &t);
  4306. if (t == 0) {
  4307. i+=2;
  4308. } else break;
  4309. }
  4310. /* get the exponent */
  4311. for (j=0; isxdigit(buf[i]) && j < sizeof data; i+=2,j++) {
  4312. hex_to_byteval(&buf[i], &data[j]);
  4313. }
  4314. if (j == 0) { j = 1; } /* to handle 1 byte length exponents */
  4315. SECITEM_AllocItem(NULL, &rsaBlapiPublicKey.publicExponent, j);
  4316. if (rsaBlapiPublicKey.publicExponent.data == NULL) {
  4317. goto loser;
  4318. }
  4319. for (i=0; i < j; i++) {
  4320. rsaBlapiPublicKey.publicExponent.data[i] = data[i];
  4321. }
  4322. fputs(buf, rsaresp);
  4323. continue;
  4324. }
  4325. /* Msg = ... */
  4326. if (strncmp(buf, "Msg", 3) == 0) {
  4327. unsigned char msg[128]; /* MAX msg 128 */
  4328. memset(sha, 0, sizeof sha);
  4329. memset(msg, 0, sizeof msg);
  4330. i = 3;
  4331. while (isspace(buf[i]) || buf[i] == '=') {
  4332. i++;
  4333. }
  4334. for (j=0; isxdigit(buf[i]) && j < sizeof msg; i+=2,j++) {
  4335. hex_to_byteval(&buf[i], &msg[j]);
  4336. }
  4337. if (shaAlg == HASH_AlgSHA1) {
  4338. if (SHA1_HashBuf(sha, msg, j) != SECSuccess) {
  4339. fprintf(rsaresp, "ERROR: Unable to generate SHA1");
  4340. goto loser;
  4341. }
  4342. shaLength = SHA1_LENGTH;
  4343. shaOid = SEC_OID_SHA1;
  4344. } else if (shaAlg == HASH_AlgSHA256) {
  4345. if (SHA256_HashBuf(sha, msg, j) != SECSuccess) {
  4346. fprintf(rsaresp, "ERROR: Unable to generate SHA256");
  4347. goto loser;
  4348. }
  4349. shaLength = SHA256_LENGTH;
  4350. shaOid = SEC_OID_SHA256;
  4351. } else if (shaAlg == HASH_AlgSHA384) {
  4352. if (SHA384_HashBuf(sha, msg, j) != SECSuccess) {
  4353. fprintf(rsaresp, "ERROR: Unable to generate SHA384");
  4354. goto loser;
  4355. }
  4356. shaLength = SHA384_LENGTH;
  4357. shaOid = SEC_OID_SHA384;
  4358. } else if (shaAlg == HASH_AlgSHA512) {
  4359. if (SHA512_HashBuf(sha, msg, j) != SECSuccess) {
  4360. fprintf(rsaresp, "ERROR: Unable to generate SHA512");
  4361. goto loser;
  4362. }
  4363. shaLength = SHA512_LENGTH;
  4364. shaOid = SEC_OID_SHA512;
  4365. } else {
  4366. fprintf(rsaresp, "ERROR: SHAAlg not defined.");
  4367. goto loser;
  4368. }
  4369. fputs(buf, rsaresp);
  4370. continue;
  4371. }
  4372. /* S = ... */
  4373. if (buf[0] == 'S') {
  4374. SECStatus rv = SECFailure;
  4375. NSSLOWKEYPublicKey * rsa_public_key;
  4376. NSSLOWKEYPublicKey low_RSA_public_key = { NULL,
  4377. NSSLOWKEYRSAKey, };
  4378. /* convert to a low RSA public key */
  4379. low_RSA_public_key.u.rsa = rsaBlapiPublicKey;
  4380. rsa_public_key = &low_RSA_public_key;
  4381. memset(signature, 0, sizeof(signature));
  4382. i = 1;
  4383. while (isspace(buf[i]) || buf[i] == '=') {
  4384. i++;
  4385. }
  4386. for (j=0; isxdigit(buf[i]) && j < sizeof signature; i+=2,j++) {
  4387. hex_to_byteval(&buf[i], &signature[j]);
  4388. }
  4389. signatureLength = j;
  4390. fputs(buf, rsaresp);
  4391. /* Perform RSA verification with the RSA public key. */
  4392. rv = RSA_HashCheckSign( shaOid,
  4393. rsa_public_key,
  4394. signature,
  4395. signatureLength,
  4396. sha,
  4397. shaLength);
  4398. if( rv == SECSuccess ) {
  4399. fputs("Result = P\n", rsaresp);
  4400. } else {
  4401. fputs("Result = F\n", rsaresp);
  4402. }
  4403. continue;
  4404. }
  4405. }
  4406. loser:
  4407. fclose(rsareq);
  4408. if (rsaBlapiPublicKey.modulus.data) { /* n */
  4409. SECITEM_ZfreeItem(&rsaBlapiPublicKey.modulus, PR_FALSE);
  4410. }
  4411. if (rsaBlapiPublicKey.publicExponent.data) { /* e */
  4412. SECITEM_ZfreeItem(&rsaBlapiPublicKey.publicExponent, PR_FALSE);
  4413. }
  4414. }
  4415. int main(int argc, char **argv)
  4416. {
  4417. if (argc < 2) exit (-1);
  4418. NSS_NoDB_Init(NULL);
  4419. /*************/
  4420. /* TDEA */
  4421. /*************/
  4422. if (strcmp(argv[1], "tdea") == 0) {
  4423. /* argv[2]=kat|mmt|mct argv[3]=ecb|cbc argv[4]=<test name>.req */
  4424. if (strcmp(argv[2], "kat") == 0) {
  4425. /* Known Answer Test (KAT) */
  4426. tdea_kat_mmt(argv[4]);
  4427. } else if (strcmp(argv[2], "mmt") == 0) {
  4428. /* Multi-block Message Test (MMT) */
  4429. tdea_kat_mmt(argv[4]);
  4430. } else if (strcmp(argv[2], "mct") == 0) {
  4431. /* Monte Carlo Test (MCT) */
  4432. if (strcmp(argv[3], "ecb") == 0) {
  4433. /* ECB mode */
  4434. tdea_mct(NSS_DES_EDE3, argv[4]);
  4435. } else if (strcmp(argv[3], "cbc") == 0) {
  4436. /* CBC mode */
  4437. tdea_mct(NSS_DES_EDE3_CBC, argv[4]);
  4438. }
  4439. }
  4440. /*************/
  4441. /* AES */
  4442. /*************/
  4443. } else if (strcmp(argv[1], "aes") == 0) {
  4444. /* argv[2]=kat|mmt|mct argv[3]=ecb|cbc argv[4]=<test name>.req */
  4445. if ( strcmp(argv[2], "kat") == 0) {
  4446. /* Known Answer Test (KAT) */
  4447. aes_kat_mmt(argv[4]);
  4448. } else if (strcmp(argv[2], "mmt") == 0) {
  4449. /* Multi-block Message Test (MMT) */
  4450. aes_kat_mmt(argv[4]);
  4451. } else if (strcmp(argv[2], "mct") == 0) {
  4452. /* Monte Carlo Test (MCT) */
  4453. if ( strcmp(argv[3], "ecb") == 0) {
  4454. /* ECB mode */
  4455. aes_ecb_mct(argv[4]);
  4456. } else if (strcmp(argv[3], "cbc") == 0) {
  4457. /* CBC mode */
  4458. aes_cbc_mct(argv[4]);
  4459. }
  4460. }
  4461. /*************/
  4462. /* SHA */
  4463. /*************/
  4464. } else if (strcmp(argv[1], "sha") == 0) {
  4465. sha_test(argv[2]);
  4466. /*************/
  4467. /* RSA */
  4468. /*************/
  4469. } else if (strcmp(argv[1], "rsa") == 0) {
  4470. /* argv[2]=siggen|sigver */
  4471. /* argv[3]=<test name>.req */
  4472. if (strcmp(argv[2], "siggen") == 0) {
  4473. /* Signature Generation Test */
  4474. rsa_siggen_test(argv[3]);
  4475. } else if (strcmp(argv[2], "sigver") == 0) {
  4476. /* Signature Verification Test */
  4477. rsa_sigver_test(argv[3]);
  4478. }
  4479. /*************/
  4480. /* HMAC */
  4481. /*************/
  4482. } else if (strcmp(argv[1], "hmac") == 0) {
  4483. hmac_test(argv[2]);
  4484. /*************/
  4485. /* DSA */
  4486. /*************/
  4487. } else if (strcmp(argv[1], "dsa") == 0) {
  4488. /* argv[2]=keypair|pqggen|pqgver|siggen|sigver */
  4489. /* argv[3]=<test name>.req */
  4490. if (strcmp(argv[2], "keypair") == 0) {
  4491. /* Key Pair Generation Test */
  4492. dsa_keypair_test(argv[3]);
  4493. } else if (strcmp(argv[2], "pqggen") == 0) {
  4494. /* Domain Parameter Generation Test */
  4495. dsa_pqggen_test(argv[3]);
  4496. } else if (strcmp(argv[2], "pqgver") == 0) {
  4497. /* Domain Parameter Validation Test */
  4498. dsa_pqgver_test(argv[3]);
  4499. } else if (strcmp(argv[2], "siggen") == 0) {
  4500. /* Signature Generation Test */
  4501. dsa_siggen_test(argv[3]);
  4502. } else if (strcmp(argv[2], "sigver") == 0) {
  4503. /* Signature Verification Test */
  4504. dsa_sigver_test(argv[3]);
  4505. }
  4506. #ifdef NSS_ENABLE_ECC
  4507. /*************/
  4508. /* ECDSA */
  4509. /*************/
  4510. } else if (strcmp(argv[1], "ecdsa") == 0) {
  4511. /* argv[2]=keypair|pkv|siggen|sigver argv[3]=<test name>.req */
  4512. if ( strcmp(argv[2], "keypair") == 0) {
  4513. /* Key Pair Generation Test */
  4514. ecdsa_keypair_test(argv[3]);
  4515. } else if (strcmp(argv[2], "pkv") == 0) {
  4516. /* Public Key Validation Test */
  4517. ecdsa_pkv_test(argv[3]);
  4518. } else if (strcmp(argv[2], "siggen") == 0) {
  4519. /* Signature Generation Test */
  4520. ecdsa_siggen_test(argv[3]);
  4521. } else if (strcmp(argv[2], "sigver") == 0) {
  4522. /* Signature Verification Test */
  4523. ecdsa_sigver_test(argv[3]);
  4524. }
  4525. #endif /* NSS_ENABLE_ECC */
  4526. /*************/
  4527. /* RNG */
  4528. /*************/
  4529. } else if (strcmp(argv[1], "rng") == 0) {
  4530. /* argv[2]=vst|mct argv[3]=<test name>.req */
  4531. if ( strcmp(argv[2], "vst") == 0) {
  4532. /* Variable Seed Test */
  4533. rng_vst(argv[3]);
  4534. } else if (strcmp(argv[2], "mct") == 0) {
  4535. /* Monte Carlo Test */
  4536. rng_mct(argv[3]);
  4537. }
  4538. } else if (strcmp(argv[1], "drbg") == 0) {
  4539. /* Variable Seed Test */
  4540. drbg(argv[2]);
  4541. }
  4542. return 0;
  4543. }