Fix documentation error in x509 app certopt flag
[openssl.git] / test / evp_test.c
1 /*
2  * Copyright 2015-2016 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the OpenSSL license (the "License").  You may not use
5  * this file except in compliance with the License.  You can obtain a copy
6  * in the file LICENSE in the source distribution or at
7  * https://www.openssl.org/source/license.html
8  */
9
10 #include <stdio.h>
11 #include <string.h>
12 #include <stdlib.h>
13 #include <ctype.h>
14 #include <openssl/evp.h>
15 #include <openssl/pem.h>
16 #include <openssl/err.h>
17 #include <openssl/x509v3.h>
18 #include <openssl/pkcs12.h>
19 #include <openssl/kdf.h>
20 #include "internal/numbers.h"
21
22 /* Remove spaces from beginning and end of a string */
23
24 static void remove_space(char **pval)
25 {
26     unsigned char *p = (unsigned char *)*pval;
27
28     while (isspace(*p))
29         p++;
30
31     *pval = (char *)p;
32
33     p = p + strlen(*pval) - 1;
34
35     /* Remove trailing space */
36     while (isspace(*p))
37         *p-- = 0;
38 }
39
40 /*
41  * Given a line of the form:
42  *      name = value # comment
43  * extract name and value. NB: modifies passed buffer.
44  */
45
46 static int parse_line(char **pkw, char **pval, char *linebuf)
47 {
48     char *p;
49
50     p = linebuf + strlen(linebuf) - 1;
51
52     if (*p != '\n') {
53         fprintf(stderr, "FATAL: missing EOL\n");
54         exit(1);
55     }
56
57     /* Look for # */
58
59     p = strchr(linebuf, '#');
60
61     if (p)
62         *p = '\0';
63
64     /* Look for = sign */
65     p = strchr(linebuf, '=');
66
67     /* If no '=' exit */
68     if (!p)
69         return 0;
70
71     *p++ = '\0';
72
73     *pkw = linebuf;
74     *pval = p;
75
76     /* Remove spaces from keyword and value */
77     remove_space(pkw);
78     remove_space(pval);
79
80     return 1;
81 }
82
83 /*
84  * Unescape some escape sequences in string literals.
85  * Return the result in a newly allocated buffer.
86  * Currently only supports '\n'.
87  * If the input length is 0, returns a valid 1-byte buffer, but sets
88  * the length to 0.
89  */
90 static unsigned char* unescape(const char *input, size_t input_len,
91                                size_t *out_len)
92 {
93     unsigned char *ret, *p;
94     size_t i;
95     if (input_len == 0) {
96         *out_len = 0;
97         return OPENSSL_zalloc(1);
98     }
99
100     /* Escaping is non-expanding; over-allocate original size for simplicity. */
101     ret = p = OPENSSL_malloc(input_len);
102     if (ret == NULL)
103         return NULL;
104
105     for (i = 0; i < input_len; i++) {
106         if (input[i] == '\\') {
107             if (i == input_len - 1 || input[i+1] != 'n')
108                 goto err;
109             *p++ = '\n';
110             i++;
111         } else {
112             *p++ = input[i];
113         }
114     }
115
116     *out_len = p - ret;
117     return ret;
118
119  err:
120     OPENSSL_free(ret);
121     return NULL;
122 }
123
124 /* For a hex string "value" convert to a binary allocated buffer */
125 static int test_bin(const char *value, unsigned char **buf, size_t *buflen)
126 {
127     long len;
128
129     *buflen = 0;
130     if (!*value) {
131         /*
132          * Don't return NULL for zero length buffer.
133          * This is needed for some tests with empty keys: HMAC_Init_ex() expects
134          * a non-NULL key buffer even if the key length is 0, in order to detect
135          * key reset.
136          */
137         *buf = OPENSSL_malloc(1);
138         if (!*buf)
139             return 0;
140         **buf = 0;
141         *buflen = 0;
142         return 1;
143     }
144     /* Check for string literal */
145     if (value[0] == '"') {
146         size_t vlen;
147         value++;
148         vlen = strlen(value);
149         if (value[vlen - 1] != '"')
150             return 0;
151         vlen--;
152         *buf = unescape(value, vlen, buflen);
153         if (*buf == NULL)
154             return 0;
155         return 1;
156     }
157
158     *buf = OPENSSL_hexstr2buf(value, &len);
159     if (!*buf) {
160         fprintf(stderr, "Value=%s\n", value);
161         ERR_print_errors_fp(stderr);
162         return -1;
163     }
164     /* Size of input buffer means we'll never overflow */
165     *buflen = len;
166     return 1;
167 }
168 #ifndef OPENSSL_NO_SCRYPT
169 /* Currently only used by scrypt tests */
170 /* Parse unsigned decimal 64 bit integer value */
171 static int test_uint64(const char *value, uint64_t *pr)
172 {
173     const char *p = value;
174     if (!*p) {
175         fprintf(stderr, "Invalid empty integer value\n");
176         return -1;
177     }
178     *pr = 0;
179     while (*p) {
180         if (*pr > UINT64_MAX/10) {
181             fprintf(stderr, "Integer string overflow value=%s\n", value);
182             return -1;
183         }
184         *pr *= 10;
185         if (*p < '0' || *p > '9') {
186             fprintf(stderr, "Invalid integer string value=%s\n", value);
187             return -1;
188         }
189         *pr += *p - '0';
190         p++;
191     }
192     return 1;
193 }
194 #endif
195
196 /* Structure holding test information */
197 struct evp_test {
198     /* file being read */
199     BIO *in;
200     /* List of public and private keys */
201     struct key_list *private;
202     struct key_list *public;
203     /* method for this test */
204     const struct evp_test_method *meth;
205     /* current line being processed */
206     unsigned int line;
207     /* start line of current test */
208     unsigned int start_line;
209     /* Error string for test */
210     const char *err, *aux_err;
211     /* Expected error value of test */
212     char *expected_err;
213     /* Number of tests */
214     int ntests;
215     /* Error count */
216     int errors;
217     /* Number of tests skipped */
218     int nskip;
219     /* If output mismatch expected and got value */
220     unsigned char *out_received;
221     size_t out_received_len;
222     unsigned char *out_expected;
223     size_t out_expected_len;
224     /* test specific data */
225     void *data;
226     /* Current test should be skipped */
227     int skip;
228 };
229
230 struct key_list {
231     char *name;
232     EVP_PKEY *key;
233     struct key_list *next;
234 };
235
236 /* Test method structure */
237 struct evp_test_method {
238     /* Name of test as it appears in file */
239     const char *name;
240     /* Initialise test for "alg" */
241     int (*init) (struct evp_test * t, const char *alg);
242     /* Clean up method */
243     void (*cleanup) (struct evp_test * t);
244     /* Test specific name value pair processing */
245     int (*parse) (struct evp_test * t, const char *name, const char *value);
246     /* Run the test itself */
247     int (*run_test) (struct evp_test * t);
248 };
249
250 static const struct evp_test_method digest_test_method, cipher_test_method;
251 static const struct evp_test_method mac_test_method;
252 static const struct evp_test_method psign_test_method, pverify_test_method;
253 static const struct evp_test_method pdecrypt_test_method;
254 static const struct evp_test_method pverify_recover_test_method;
255 static const struct evp_test_method pderive_test_method;
256 static const struct evp_test_method pbe_test_method;
257 static const struct evp_test_method encode_test_method;
258 static const struct evp_test_method kdf_test_method;
259
260 static const struct evp_test_method *evp_test_list[] = {
261     &digest_test_method,
262     &cipher_test_method,
263     &mac_test_method,
264     &psign_test_method,
265     &pverify_test_method,
266     &pdecrypt_test_method,
267     &pverify_recover_test_method,
268     &pderive_test_method,
269     &pbe_test_method,
270     &encode_test_method,
271     &kdf_test_method,
272     NULL
273 };
274
275 static const struct evp_test_method *evp_find_test(const char *name)
276 {
277     const struct evp_test_method **tt;
278
279     for (tt = evp_test_list; *tt; tt++) {
280         if (strcmp(name, (*tt)->name) == 0)
281             return *tt;
282     }
283     return NULL;
284 }
285
286 static void hex_print(const char *name, const unsigned char *buf, size_t len)
287 {
288     size_t i;
289     fprintf(stderr, "%s ", name);
290     for (i = 0; i < len; i++)
291         fprintf(stderr, "%02X", buf[i]);
292     fputs("\n", stderr);
293 }
294
295 static void free_expected(struct evp_test *t)
296 {
297     OPENSSL_free(t->expected_err);
298     t->expected_err = NULL;
299     OPENSSL_free(t->out_expected);
300     OPENSSL_free(t->out_received);
301     t->out_expected = NULL;
302     t->out_received = NULL;
303     t->out_expected_len = 0;
304     t->out_received_len = 0;
305     /* Literals. */
306     t->err = NULL;
307 }
308
309 static void print_expected(struct evp_test *t)
310 {
311     if (t->out_expected == NULL && t->out_received == NULL)
312         return;
313     hex_print("Expected:", t->out_expected, t->out_expected_len);
314     hex_print("Got:     ", t->out_received, t->out_received_len);
315     free_expected(t);
316 }
317
318 static int check_test_error(struct evp_test *t)
319 {
320     if (!t->err && !t->expected_err)
321         return 1;
322     if (t->err && !t->expected_err) {
323         if (t->aux_err != NULL) {
324             fprintf(stderr, "Test line %d(%s): unexpected error %s\n",
325                     t->start_line, t->aux_err, t->err);
326         } else {
327             fprintf(stderr, "Test line %d: unexpected error %s\n",
328                     t->start_line, t->err);
329         }
330         print_expected(t);
331         return 0;
332     }
333     if (!t->err && t->expected_err) {
334         fprintf(stderr, "Test line %d: succeeded expecting %s\n",
335                 t->start_line, t->expected_err);
336         return 0;
337     }
338     if (strcmp(t->err, t->expected_err) == 0)
339         return 1;
340
341     fprintf(stderr, "Test line %d: expecting %s got %s\n",
342             t->start_line, t->expected_err, t->err);
343     return 0;
344 }
345
346 /* Setup a new test, run any existing test */
347
348 static int setup_test(struct evp_test *t, const struct evp_test_method *tmeth)
349 {
350     /* If we already have a test set up run it */
351     if (t->meth) {
352         t->ntests++;
353         if (t->skip) {
354             t->meth = tmeth;
355             t->nskip++;
356             return 1;
357         }
358         t->err = NULL;
359         if (t->meth->run_test(t) != 1) {
360             fprintf(stderr, "%s test error line %d\n",
361                     t->meth->name, t->start_line);
362             return 0;
363         }
364         if (!check_test_error(t)) {
365             if (t->err)
366                 ERR_print_errors_fp(stderr);
367             t->errors++;
368         }
369         ERR_clear_error();
370         t->meth->cleanup(t);
371         OPENSSL_free(t->data);
372         t->data = NULL;
373         OPENSSL_free(t->expected_err);
374         t->expected_err = NULL;
375         free_expected(t);
376     }
377     t->meth = tmeth;
378     return 1;
379 }
380
381 static int find_key(EVP_PKEY **ppk, const char *name, struct key_list *lst)
382 {
383     for (; lst; lst = lst->next) {
384         if (strcmp(lst->name, name) == 0) {
385             if (ppk)
386                 *ppk = lst->key;
387             return 1;
388         }
389     }
390     return 0;
391 }
392
393 static void free_key_list(struct key_list *lst)
394 {
395     while (lst != NULL) {
396         struct key_list *ltmp;
397         EVP_PKEY_free(lst->key);
398         OPENSSL_free(lst->name);
399         ltmp = lst->next;
400         OPENSSL_free(lst);
401         lst = ltmp;
402     }
403 }
404
405 static int check_unsupported()
406 {
407     long err = ERR_peek_error();
408     if (ERR_GET_LIB(err) == ERR_LIB_EVP
409         && ERR_GET_REASON(err) == EVP_R_UNSUPPORTED_ALGORITHM) {
410         ERR_clear_error();
411         return 1;
412     }
413     return 0;
414 }
415
416 static int process_test(struct evp_test *t, char *buf, int verbose)
417 {
418     char *keyword = NULL, *value = NULL;
419     int rv = 0, add_key = 0;
420     long save_pos = 0;
421     struct key_list **lst = NULL, *key = NULL;
422     EVP_PKEY *pk = NULL;
423     const struct evp_test_method *tmeth = NULL;
424     if (verbose)
425         fputs(buf, stdout);
426     if (!parse_line(&keyword, &value, buf))
427         return 1;
428     if (strcmp(keyword, "PrivateKey") == 0) {
429         save_pos = BIO_tell(t->in);
430         pk = PEM_read_bio_PrivateKey(t->in, NULL, 0, NULL);
431         if (pk == NULL && !check_unsupported()) {
432             fprintf(stderr, "Error reading private key %s\n", value);
433             ERR_print_errors_fp(stderr);
434             return 0;
435         }
436         lst = &t->private;
437         add_key = 1;
438     }
439     if (strcmp(keyword, "PublicKey") == 0) {
440         save_pos = BIO_tell(t->in);
441         pk = PEM_read_bio_PUBKEY(t->in, NULL, 0, NULL);
442         if (pk == NULL && !check_unsupported()) {
443             fprintf(stderr, "Error reading public key %s\n", value);
444             ERR_print_errors_fp(stderr);
445             return 0;
446         }
447         lst = &t->public;
448         add_key = 1;
449     }
450     /* If we have a key add to list */
451     if (add_key) {
452         char tmpbuf[80];
453         if (find_key(NULL, value, *lst)) {
454             fprintf(stderr, "Duplicate key %s\n", value);
455             return 0;
456         }
457         key = OPENSSL_malloc(sizeof(*key));
458         if (!key)
459             return 0;
460         key->name = OPENSSL_strdup(value);
461         key->key = pk;
462         key->next = *lst;
463         *lst = key;
464         /* Rewind input, read to end and update line numbers */
465         (void)BIO_seek(t->in, save_pos);
466         while (BIO_gets(t->in,tmpbuf, sizeof(tmpbuf))) {
467             t->line++;
468             if (strncmp(tmpbuf, "-----END", 8) == 0)
469                 return 1;
470         }
471         fprintf(stderr, "Can't find key end\n");
472         return 0;
473     }
474
475     /* See if keyword corresponds to a test start */
476     tmeth = evp_find_test(keyword);
477     if (tmeth) {
478         if (!setup_test(t, tmeth))
479             return 0;
480         t->start_line = t->line;
481         t->skip = 0;
482         if (!tmeth->init(t, value)) {
483             fprintf(stderr, "Unknown %s: %s\n", keyword, value);
484             return 0;
485         }
486         return 1;
487     } else if (t->skip) {
488         return 1;
489     } else if (strcmp(keyword, "Result") == 0) {
490         if (t->expected_err) {
491             fprintf(stderr, "Line %d: multiple result lines\n", t->line);
492             return 0;
493         }
494         t->expected_err = OPENSSL_strdup(value);
495         if (!t->expected_err)
496             return 0;
497     } else {
498         /* Must be test specific line: try to parse it */
499         if (t->meth)
500             rv = t->meth->parse(t, keyword, value);
501
502         if (rv == 0)
503             fprintf(stderr, "line %d: unexpected keyword %s\n",
504                     t->line, keyword);
505
506         if (rv < 0)
507             fprintf(stderr, "line %d: error processing keyword %s\n",
508                     t->line, keyword);
509         if (rv <= 0)
510             return 0;
511     }
512     return 1;
513 }
514
515 static int check_var_length_output(struct evp_test *t,
516                                    const unsigned char *expected,
517                                    size_t expected_len,
518                                    const unsigned char *received,
519                                    size_t received_len)
520 {
521     if (expected_len == received_len &&
522         memcmp(expected, received, expected_len) == 0) {
523         return 0;
524     }
525
526     /* The result printing code expects a non-NULL buffer. */
527     t->out_expected = OPENSSL_memdup(expected, expected_len ? expected_len : 1);
528     t->out_expected_len = expected_len;
529     t->out_received = OPENSSL_memdup(received, received_len ? received_len : 1);
530     t->out_received_len = received_len;
531     if (t->out_expected == NULL || t->out_received == NULL) {
532         fprintf(stderr, "Memory allocation error!\n");
533         exit(1);
534     }
535     return 1;
536 }
537
538 static int check_output(struct evp_test *t,
539                         const unsigned char *expected,
540                         const unsigned char *received,
541                         size_t len)
542 {
543     return check_var_length_output(t, expected, len, received, len);
544 }
545
546 int main(int argc, char **argv)
547 {
548     BIO *in = NULL;
549     char buf[10240];
550     struct evp_test t;
551
552     if (argc != 2) {
553         fprintf(stderr, "usage: evp_test testfile.txt\n");
554         return 1;
555     }
556
557     CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON);
558
559     memset(&t, 0, sizeof(t));
560     t.start_line = -1;
561     in = BIO_new_file(argv[1], "r");
562     t.in = in;
563     while (BIO_gets(in, buf, sizeof(buf))) {
564         t.line++;
565         if (!process_test(&t, buf, 0))
566             exit(1);
567     }
568     /* Run any final test we have */
569     if (!setup_test(&t, NULL))
570         exit(1);
571     fprintf(stderr, "%d tests completed with %d errors, %d skipped\n",
572             t.ntests, t.errors, t.nskip);
573     free_key_list(t.public);
574     free_key_list(t.private);
575     BIO_free(in);
576
577 #ifndef OPENSSL_NO_CRYPTO_MDEBUG
578     if (CRYPTO_mem_leaks_fp(stderr) <= 0)
579         return 1;
580 #endif
581     if (t.errors)
582         return 1;
583     return 0;
584 }
585
586 static void test_free(void *d)
587 {
588     OPENSSL_free(d);
589 }
590
591 /* Message digest tests */
592
593 struct digest_data {
594     /* Digest this test is for */
595     const EVP_MD *digest;
596     /* Input to digest */
597     unsigned char *input;
598     size_t input_len;
599     /* Repeat count for input */
600     size_t nrpt;
601     /* Expected output */
602     unsigned char *output;
603     size_t output_len;
604 };
605
606 static int digest_test_init(struct evp_test *t, const char *alg)
607 {
608     const EVP_MD *digest;
609     struct digest_data *mdat;
610     digest = EVP_get_digestbyname(alg);
611     if (!digest) {
612         /* If alg has an OID assume disabled algorithm */
613         if (OBJ_sn2nid(alg) != NID_undef || OBJ_ln2nid(alg) != NID_undef) {
614             t->skip = 1;
615             return 1;
616         }
617         return 0;
618     }
619     mdat = OPENSSL_malloc(sizeof(*mdat));
620     mdat->digest = digest;
621     mdat->input = NULL;
622     mdat->output = NULL;
623     mdat->nrpt = 1;
624     t->data = mdat;
625     return 1;
626 }
627
628 static void digest_test_cleanup(struct evp_test *t)
629 {
630     struct digest_data *mdat = t->data;
631     test_free(mdat->input);
632     test_free(mdat->output);
633 }
634
635 static int digest_test_parse(struct evp_test *t,
636                              const char *keyword, const char *value)
637 {
638     struct digest_data *mdata = t->data;
639     if (strcmp(keyword, "Input") == 0)
640         return test_bin(value, &mdata->input, &mdata->input_len);
641     if (strcmp(keyword, "Output") == 0)
642         return test_bin(value, &mdata->output, &mdata->output_len);
643     if (strcmp(keyword, "Count") == 0) {
644         long nrpt = atoi(value);
645         if (nrpt <= 0)
646             return 0;
647         mdata->nrpt = (size_t)nrpt;
648         return 1;
649     }
650     return 0;
651 }
652
653 static int digest_test_run(struct evp_test *t)
654 {
655     struct digest_data *mdata = t->data;
656     size_t i;
657     const char *err = "INTERNAL_ERROR";
658     EVP_MD_CTX *mctx;
659     unsigned char md[EVP_MAX_MD_SIZE];
660     unsigned int md_len;
661     mctx = EVP_MD_CTX_new();
662     if (!mctx)
663         goto err;
664     err = "DIGESTINIT_ERROR";
665     if (!EVP_DigestInit_ex(mctx, mdata->digest, NULL))
666         goto err;
667     err = "DIGESTUPDATE_ERROR";
668     for (i = 0; i < mdata->nrpt; i++) {
669         if (!EVP_DigestUpdate(mctx, mdata->input, mdata->input_len))
670             goto err;
671     }
672     err = "DIGESTFINAL_ERROR";
673     if (!EVP_DigestFinal(mctx, md, &md_len))
674         goto err;
675     err = "DIGEST_LENGTH_MISMATCH";
676     if (md_len != mdata->output_len)
677         goto err;
678     err = "DIGEST_MISMATCH";
679     if (check_output(t, mdata->output, md, md_len))
680         goto err;
681     err = NULL;
682  err:
683     EVP_MD_CTX_free(mctx);
684     t->err = err;
685     return 1;
686 }
687
688 static const struct evp_test_method digest_test_method = {
689     "Digest",
690     digest_test_init,
691     digest_test_cleanup,
692     digest_test_parse,
693     digest_test_run
694 };
695
696 /* Cipher tests */
697 struct cipher_data {
698     const EVP_CIPHER *cipher;
699     int enc;
700     /* EVP_CIPH_GCM_MODE, EVP_CIPH_CCM_MODE or EVP_CIPH_OCB_MODE if AEAD */
701     int aead;
702     unsigned char *key;
703     size_t key_len;
704     unsigned char *iv;
705     size_t iv_len;
706     unsigned char *plaintext;
707     size_t plaintext_len;
708     unsigned char *ciphertext;
709     size_t ciphertext_len;
710     /* GCM, CCM only */
711     unsigned char *aad;
712     size_t aad_len;
713     unsigned char *tag;
714     size_t tag_len;
715 };
716
717 static int cipher_test_init(struct evp_test *t, const char *alg)
718 {
719     const EVP_CIPHER *cipher;
720     struct cipher_data *cdat = t->data;
721     cipher = EVP_get_cipherbyname(alg);
722     if (!cipher) {
723         /* If alg has an OID assume disabled algorithm */
724         if (OBJ_sn2nid(alg) != NID_undef || OBJ_ln2nid(alg) != NID_undef) {
725             t->skip = 1;
726             return 1;
727         }
728         return 0;
729     }
730     cdat = OPENSSL_malloc(sizeof(*cdat));
731     cdat->cipher = cipher;
732     cdat->enc = -1;
733     cdat->key = NULL;
734     cdat->iv = NULL;
735     cdat->ciphertext = NULL;
736     cdat->plaintext = NULL;
737     cdat->aad = NULL;
738     cdat->tag = NULL;
739     t->data = cdat;
740     if (EVP_CIPHER_mode(cipher) == EVP_CIPH_GCM_MODE
741         || EVP_CIPHER_mode(cipher) == EVP_CIPH_OCB_MODE
742         || EVP_CIPHER_mode(cipher) == EVP_CIPH_CCM_MODE)
743         cdat->aead = EVP_CIPHER_mode(cipher);
744     else if (EVP_CIPHER_flags(cipher) & EVP_CIPH_FLAG_AEAD_CIPHER)
745         cdat->aead = -1;
746     else
747         cdat->aead = 0;
748
749     return 1;
750 }
751
752 static void cipher_test_cleanup(struct evp_test *t)
753 {
754     struct cipher_data *cdat = t->data;
755     test_free(cdat->key);
756     test_free(cdat->iv);
757     test_free(cdat->ciphertext);
758     test_free(cdat->plaintext);
759     test_free(cdat->aad);
760     test_free(cdat->tag);
761 }
762
763 static int cipher_test_parse(struct evp_test *t, const char *keyword,
764                              const char *value)
765 {
766     struct cipher_data *cdat = t->data;
767     if (strcmp(keyword, "Key") == 0)
768         return test_bin(value, &cdat->key, &cdat->key_len);
769     if (strcmp(keyword, "IV") == 0)
770         return test_bin(value, &cdat->iv, &cdat->iv_len);
771     if (strcmp(keyword, "Plaintext") == 0)
772         return test_bin(value, &cdat->plaintext, &cdat->plaintext_len);
773     if (strcmp(keyword, "Ciphertext") == 0)
774         return test_bin(value, &cdat->ciphertext, &cdat->ciphertext_len);
775     if (cdat->aead) {
776         if (strcmp(keyword, "AAD") == 0)
777             return test_bin(value, &cdat->aad, &cdat->aad_len);
778         if (strcmp(keyword, "Tag") == 0)
779             return test_bin(value, &cdat->tag, &cdat->tag_len);
780     }
781
782     if (strcmp(keyword, "Operation") == 0) {
783         if (strcmp(value, "ENCRYPT") == 0)
784             cdat->enc = 1;
785         else if (strcmp(value, "DECRYPT") == 0)
786             cdat->enc = 0;
787         else
788             return 0;
789         return 1;
790     }
791     return 0;
792 }
793
794 static int cipher_test_enc(struct evp_test *t, int enc,
795                            size_t out_misalign, size_t inp_misalign)
796 {
797     struct cipher_data *cdat = t->data;
798     unsigned char *in, *out, *tmp = NULL;
799     size_t in_len, out_len;
800     int tmplen, tmpflen;
801     EVP_CIPHER_CTX *ctx = NULL;
802     const char *err;
803     err = "INTERNAL_ERROR";
804     ctx = EVP_CIPHER_CTX_new();
805     if (!ctx)
806         goto err;
807     EVP_CIPHER_CTX_set_flags(ctx, EVP_CIPHER_CTX_FLAG_WRAP_ALLOW);
808     if (enc) {
809         in = cdat->plaintext;
810         in_len = cdat->plaintext_len;
811         out = cdat->ciphertext;
812         out_len = cdat->ciphertext_len;
813     } else {
814         in = cdat->ciphertext;
815         in_len = cdat->ciphertext_len;
816         out = cdat->plaintext;
817         out_len = cdat->plaintext_len;
818     }
819     if (inp_misalign == (size_t)-1) {
820         /*
821          * Exercise in-place encryption
822          */
823         tmp = OPENSSL_malloc(out_misalign + in_len + 2 * EVP_MAX_BLOCK_LENGTH);
824         if (!tmp)
825             goto err;
826         in = memcpy(tmp + out_misalign, in, in_len);
827     } else {
828         inp_misalign += 16 - ((out_misalign + in_len) & 15);
829         /*
830          * 'tmp' will store both output and copy of input. We make the copy
831          * of input to specifically aligned part of 'tmp'. So we just
832          * figured out how much padding would ensure the required alignment,
833          * now we allocate extended buffer and finally copy the input just
834          * past inp_misalign in expression below. Output will be written
835          * past out_misalign...
836          */
837         tmp = OPENSSL_malloc(out_misalign + in_len + 2 * EVP_MAX_BLOCK_LENGTH +
838                              inp_misalign + in_len);
839         if (!tmp)
840             goto err;
841         in = memcpy(tmp + out_misalign + in_len + 2 * EVP_MAX_BLOCK_LENGTH +
842                     inp_misalign, in, in_len);
843     }
844     err = "CIPHERINIT_ERROR";
845     if (!EVP_CipherInit_ex(ctx, cdat->cipher, NULL, NULL, NULL, enc))
846         goto err;
847     err = "INVALID_IV_LENGTH";
848     if (cdat->iv) {
849         if (cdat->aead) {
850             if (!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_IVLEN,
851                                      cdat->iv_len, 0))
852                 goto err;
853         } else if (cdat->iv_len != (size_t)EVP_CIPHER_CTX_iv_length(ctx))
854             goto err;
855     }
856     if (cdat->aead) {
857         unsigned char *tag;
858         /*
859          * If encrypting or OCB just set tag length initially, otherwise
860          * set tag length and value.
861          */
862         if (enc || cdat->aead == EVP_CIPH_OCB_MODE) {
863             err = "TAG_LENGTH_SET_ERROR";
864             tag = NULL;
865         } else {
866             err = "TAG_SET_ERROR";
867             tag = cdat->tag;
868         }
869         if (tag || cdat->aead != EVP_CIPH_GCM_MODE) {
870             if (!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_TAG,
871                                      cdat->tag_len, tag))
872                 goto err;
873         }
874     }
875
876     err = "INVALID_KEY_LENGTH";
877     if (!EVP_CIPHER_CTX_set_key_length(ctx, cdat->key_len))
878         goto err;
879     err = "KEY_SET_ERROR";
880     if (!EVP_CipherInit_ex(ctx, NULL, NULL, cdat->key, cdat->iv, -1))
881         goto err;
882
883     if (!enc && cdat->aead == EVP_CIPH_OCB_MODE) {
884         if (!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_TAG,
885                                  cdat->tag_len, cdat->tag)) {
886             err = "TAG_SET_ERROR";
887             goto err;
888         }
889     }
890
891     if (cdat->aead == EVP_CIPH_CCM_MODE) {
892         if (!EVP_CipherUpdate(ctx, NULL, &tmplen, NULL, out_len)) {
893             err = "CCM_PLAINTEXT_LENGTH_SET_ERROR";
894             goto err;
895         }
896     }
897     if (cdat->aad) {
898         if (!EVP_CipherUpdate(ctx, NULL, &tmplen, cdat->aad, cdat->aad_len)) {
899             err = "AAD_SET_ERROR";
900             goto err;
901         }
902     }
903     EVP_CIPHER_CTX_set_padding(ctx, 0);
904     err = "CIPHERUPDATE_ERROR";
905     if (!EVP_CipherUpdate(ctx, tmp + out_misalign, &tmplen, in, in_len))
906         goto err;
907     if (cdat->aead == EVP_CIPH_CCM_MODE)
908         tmpflen = 0;
909     else {
910         err = "CIPHERFINAL_ERROR";
911         if (!EVP_CipherFinal_ex(ctx, tmp + out_misalign + tmplen, &tmpflen))
912             goto err;
913     }
914     err = "LENGTH_MISMATCH";
915     if (out_len != (size_t)(tmplen + tmpflen))
916         goto err;
917     err = "VALUE_MISMATCH";
918     if (check_output(t, out, tmp + out_misalign, out_len))
919         goto err;
920     if (enc && cdat->aead) {
921         unsigned char rtag[16];
922         if (cdat->tag_len > sizeof(rtag)) {
923             err = "TAG_LENGTH_INTERNAL_ERROR";
924             goto err;
925         }
926         if (!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_GET_TAG,
927                                  cdat->tag_len, rtag)) {
928             err = "TAG_RETRIEVE_ERROR";
929             goto err;
930         }
931         if (check_output(t, cdat->tag, rtag, cdat->tag_len)) {
932             err = "TAG_VALUE_MISMATCH";
933             goto err;
934         }
935     }
936     err = NULL;
937  err:
938     OPENSSL_free(tmp);
939     EVP_CIPHER_CTX_free(ctx);
940     t->err = err;
941     return err ? 0 : 1;
942 }
943
944 static int cipher_test_run(struct evp_test *t)
945 {
946     struct cipher_data *cdat = t->data;
947     int rv;
948     size_t out_misalign, inp_misalign;
949
950     if (!cdat->key) {
951         t->err = "NO_KEY";
952         return 0;
953     }
954     if (!cdat->iv && EVP_CIPHER_iv_length(cdat->cipher)) {
955         /* IV is optional and usually omitted in wrap mode */
956         if (EVP_CIPHER_mode(cdat->cipher) != EVP_CIPH_WRAP_MODE) {
957             t->err = "NO_IV";
958             return 0;
959         }
960     }
961     if (cdat->aead && !cdat->tag) {
962         t->err = "NO_TAG";
963         return 0;
964     }
965     for (out_misalign = 0; out_misalign <= 1; out_misalign++) {
966         static char aux_err[64];
967         t->aux_err = aux_err;
968         for (inp_misalign = (size_t)-1; inp_misalign != 2; inp_misalign++) {
969             if (inp_misalign == (size_t)-1) {
970                 /* kludge: inp_misalign == -1 means "exercise in-place" */
971                 BIO_snprintf(aux_err, sizeof(aux_err), "%s in-place",
972                              out_misalign ? "misaligned" : "aligned");
973             } else {
974                 BIO_snprintf(aux_err, sizeof(aux_err), "%s output and %s input",
975                              out_misalign ? "misaligned" : "aligned",
976                              inp_misalign ? "misaligned" : "aligned");
977             }
978             if (cdat->enc) {
979                 rv = cipher_test_enc(t, 1, out_misalign, inp_misalign);
980                 /* Not fatal errors: return */
981                 if (rv != 1) {
982                     if (rv < 0)
983                         return 0;
984                     return 1;
985                 }
986             }
987             if (cdat->enc != 1) {
988                 rv = cipher_test_enc(t, 0, out_misalign, inp_misalign);
989                 /* Not fatal errors: return */
990                 if (rv != 1) {
991                     if (rv < 0)
992                         return 0;
993                     return 1;
994                 }
995             }
996         }
997     }
998     t->aux_err = NULL;
999
1000     return 1;
1001 }
1002
1003 static const struct evp_test_method cipher_test_method = {
1004     "Cipher",
1005     cipher_test_init,
1006     cipher_test_cleanup,
1007     cipher_test_parse,
1008     cipher_test_run
1009 };
1010
1011 struct mac_data {
1012     /* MAC type */
1013     int type;
1014     /* Algorithm string for this MAC */
1015     char *alg;
1016     /* MAC key */
1017     unsigned char *key;
1018     size_t key_len;
1019     /* Input to MAC */
1020     unsigned char *input;
1021     size_t input_len;
1022     /* Expected output */
1023     unsigned char *output;
1024     size_t output_len;
1025 };
1026
1027 static int mac_test_init(struct evp_test *t, const char *alg)
1028 {
1029     int type;
1030     struct mac_data *mdat;
1031     if (strcmp(alg, "HMAC") == 0) {
1032         type = EVP_PKEY_HMAC;
1033     } else if (strcmp(alg, "CMAC") == 0) {
1034 #ifndef OPENSSL_NO_CMAC
1035         type = EVP_PKEY_CMAC;
1036 #else
1037         t->skip = 1;
1038         return 1;
1039 #endif
1040     } else
1041         return 0;
1042
1043     mdat = OPENSSL_malloc(sizeof(*mdat));
1044     mdat->type = type;
1045     mdat->alg = NULL;
1046     mdat->key = NULL;
1047     mdat->input = NULL;
1048     mdat->output = NULL;
1049     t->data = mdat;
1050     return 1;
1051 }
1052
1053 static void mac_test_cleanup(struct evp_test *t)
1054 {
1055     struct mac_data *mdat = t->data;
1056     test_free(mdat->alg);
1057     test_free(mdat->key);
1058     test_free(mdat->input);
1059     test_free(mdat->output);
1060 }
1061
1062 static int mac_test_parse(struct evp_test *t,
1063                           const char *keyword, const char *value)
1064 {
1065     struct mac_data *mdata = t->data;
1066     if (strcmp(keyword, "Key") == 0)
1067         return test_bin(value, &mdata->key, &mdata->key_len);
1068     if (strcmp(keyword, "Algorithm") == 0) {
1069         mdata->alg = OPENSSL_strdup(value);
1070         if (!mdata->alg)
1071             return 0;
1072         return 1;
1073     }
1074     if (strcmp(keyword, "Input") == 0)
1075         return test_bin(value, &mdata->input, &mdata->input_len);
1076     if (strcmp(keyword, "Output") == 0)
1077         return test_bin(value, &mdata->output, &mdata->output_len);
1078     return 0;
1079 }
1080
1081 static int mac_test_run(struct evp_test *t)
1082 {
1083     struct mac_data *mdata = t->data;
1084     const char *err = "INTERNAL_ERROR";
1085     EVP_MD_CTX *mctx = NULL;
1086     EVP_PKEY_CTX *pctx = NULL, *genctx = NULL;
1087     EVP_PKEY *key = NULL;
1088     const EVP_MD *md = NULL;
1089     unsigned char *mac = NULL;
1090     size_t mac_len;
1091
1092 #ifdef OPENSSL_NO_DES
1093     if (strstr(mdata->alg, "DES") != NULL) {
1094         /* Skip DES */
1095         err = NULL;
1096         goto err;
1097     }
1098 #endif
1099
1100     err = "MAC_PKEY_CTX_ERROR";
1101     genctx = EVP_PKEY_CTX_new_id(mdata->type, NULL);
1102     if (!genctx)
1103         goto err;
1104
1105     err = "MAC_KEYGEN_INIT_ERROR";
1106     if (EVP_PKEY_keygen_init(genctx) <= 0)
1107         goto err;
1108     if (mdata->type == EVP_PKEY_CMAC) {
1109         err = "MAC_ALGORITHM_SET_ERROR";
1110         if (EVP_PKEY_CTX_ctrl_str(genctx, "cipher", mdata->alg) <= 0)
1111             goto err;
1112     }
1113
1114     err = "MAC_KEY_SET_ERROR";
1115     if (EVP_PKEY_CTX_set_mac_key(genctx, mdata->key, mdata->key_len) <= 0)
1116         goto err;
1117
1118     err = "MAC_KEY_GENERATE_ERROR";
1119     if (EVP_PKEY_keygen(genctx, &key) <= 0)
1120         goto err;
1121     if (mdata->type == EVP_PKEY_HMAC) {
1122         err = "MAC_ALGORITHM_SET_ERROR";
1123         md = EVP_get_digestbyname(mdata->alg);
1124         if (!md)
1125             goto err;
1126     }
1127     mctx = EVP_MD_CTX_new();
1128     if (!mctx)
1129         goto err;
1130     err = "DIGESTSIGNINIT_ERROR";
1131     if (!EVP_DigestSignInit(mctx, &pctx, md, NULL, key))
1132         goto err;
1133
1134     err = "DIGESTSIGNUPDATE_ERROR";
1135     if (!EVP_DigestSignUpdate(mctx, mdata->input, mdata->input_len))
1136         goto err;
1137     err = "DIGESTSIGNFINAL_LENGTH_ERROR";
1138     if (!EVP_DigestSignFinal(mctx, NULL, &mac_len))
1139         goto err;
1140     mac = OPENSSL_malloc(mac_len);
1141     if (!mac) {
1142         fprintf(stderr, "Error allocating mac buffer!\n");
1143         exit(1);
1144     }
1145     if (!EVP_DigestSignFinal(mctx, mac, &mac_len))
1146         goto err;
1147     err = "MAC_LENGTH_MISMATCH";
1148     if (mac_len != mdata->output_len)
1149         goto err;
1150     err = "MAC_MISMATCH";
1151     if (check_output(t, mdata->output, mac, mac_len))
1152         goto err;
1153     err = NULL;
1154  err:
1155     EVP_MD_CTX_free(mctx);
1156     OPENSSL_free(mac);
1157     EVP_PKEY_CTX_free(genctx);
1158     EVP_PKEY_free(key);
1159     t->err = err;
1160     return 1;
1161 }
1162
1163 static const struct evp_test_method mac_test_method = {
1164     "MAC",
1165     mac_test_init,
1166     mac_test_cleanup,
1167     mac_test_parse,
1168     mac_test_run
1169 };
1170
1171 /*
1172  * Public key operations. These are all very similar and can share
1173  * a lot of common code.
1174  */
1175
1176 struct pkey_data {
1177     /* Context for this operation */
1178     EVP_PKEY_CTX *ctx;
1179     /* Key operation to perform */
1180     int (*keyop) (EVP_PKEY_CTX *ctx,
1181                   unsigned char *sig, size_t *siglen,
1182                   const unsigned char *tbs, size_t tbslen);
1183     /* Input to MAC */
1184     unsigned char *input;
1185     size_t input_len;
1186     /* Expected output */
1187     unsigned char *output;
1188     size_t output_len;
1189 };
1190
1191 /*
1192  * Perform public key operation setup: lookup key, allocated ctx and call
1193  * the appropriate initialisation function
1194  */
1195 static int pkey_test_init(struct evp_test *t, const char *name,
1196                           int use_public,
1197                           int (*keyopinit) (EVP_PKEY_CTX *ctx),
1198                           int (*keyop) (EVP_PKEY_CTX *ctx,
1199                                         unsigned char *sig, size_t *siglen,
1200                                         const unsigned char *tbs,
1201                                         size_t tbslen)
1202     )
1203 {
1204     struct pkey_data *kdata;
1205     EVP_PKEY *pkey = NULL;
1206     int rv = 0;
1207     if (use_public)
1208         rv = find_key(&pkey, name, t->public);
1209     if (!rv)
1210         rv = find_key(&pkey, name, t->private);
1211     if (!rv)
1212         return 0;
1213     if (!pkey) {
1214         t->skip = 1;
1215         return 1;
1216     }
1217
1218     kdata = OPENSSL_malloc(sizeof(*kdata));
1219     if (!kdata) {
1220         EVP_PKEY_free(pkey);
1221         return 0;
1222     }
1223     kdata->ctx = NULL;
1224     kdata->input = NULL;
1225     kdata->output = NULL;
1226     kdata->keyop = keyop;
1227     t->data = kdata;
1228     kdata->ctx = EVP_PKEY_CTX_new(pkey, NULL);
1229     if (!kdata->ctx)
1230         return 0;
1231     if (keyopinit(kdata->ctx) <= 0)
1232         return 0;
1233     return 1;
1234 }
1235
1236 static void pkey_test_cleanup(struct evp_test *t)
1237 {
1238     struct pkey_data *kdata = t->data;
1239
1240     OPENSSL_free(kdata->input);
1241     OPENSSL_free(kdata->output);
1242     EVP_PKEY_CTX_free(kdata->ctx);
1243 }
1244
1245 static int pkey_test_ctrl(EVP_PKEY_CTX *pctx, const char *value)
1246 {
1247     int rv;
1248     char *p, *tmpval;
1249
1250     tmpval = OPENSSL_strdup(value);
1251     if (tmpval == NULL)
1252         return 0;
1253     p = strchr(tmpval, ':');
1254     if (p != NULL)
1255         *p++ = 0;
1256     rv = EVP_PKEY_CTX_ctrl_str(pctx, tmpval, p);
1257     OPENSSL_free(tmpval);
1258     return rv > 0;
1259 }
1260
1261 static int pkey_test_parse(struct evp_test *t,
1262                            const char *keyword, const char *value)
1263 {
1264     struct pkey_data *kdata = t->data;
1265     if (strcmp(keyword, "Input") == 0)
1266         return test_bin(value, &kdata->input, &kdata->input_len);
1267     if (strcmp(keyword, "Output") == 0)
1268         return test_bin(value, &kdata->output, &kdata->output_len);
1269     if (strcmp(keyword, "Ctrl") == 0)
1270         return pkey_test_ctrl(kdata->ctx, value);
1271     return 0;
1272 }
1273
1274 static int pkey_test_run(struct evp_test *t)
1275 {
1276     struct pkey_data *kdata = t->data;
1277     unsigned char *out = NULL;
1278     size_t out_len;
1279     const char *err = "KEYOP_LENGTH_ERROR";
1280     if (kdata->keyop(kdata->ctx, NULL, &out_len, kdata->input,
1281                      kdata->input_len) <= 0)
1282         goto err;
1283     out = OPENSSL_malloc(out_len);
1284     if (!out) {
1285         fprintf(stderr, "Error allocating output buffer!\n");
1286         exit(1);
1287     }
1288     err = "KEYOP_ERROR";
1289     if (kdata->keyop
1290         (kdata->ctx, out, &out_len, kdata->input, kdata->input_len) <= 0)
1291         goto err;
1292     err = "KEYOP_LENGTH_MISMATCH";
1293     if (out_len != kdata->output_len)
1294         goto err;
1295     err = "KEYOP_MISMATCH";
1296     if (check_output(t, kdata->output, out, out_len))
1297         goto err;
1298     err = NULL;
1299  err:
1300     OPENSSL_free(out);
1301     t->err = err;
1302     return 1;
1303 }
1304
1305 static int sign_test_init(struct evp_test *t, const char *name)
1306 {
1307     return pkey_test_init(t, name, 0, EVP_PKEY_sign_init, EVP_PKEY_sign);
1308 }
1309
1310 static const struct evp_test_method psign_test_method = {
1311     "Sign",
1312     sign_test_init,
1313     pkey_test_cleanup,
1314     pkey_test_parse,
1315     pkey_test_run
1316 };
1317
1318 static int verify_recover_test_init(struct evp_test *t, const char *name)
1319 {
1320     return pkey_test_init(t, name, 1, EVP_PKEY_verify_recover_init,
1321                           EVP_PKEY_verify_recover);
1322 }
1323
1324 static const struct evp_test_method pverify_recover_test_method = {
1325     "VerifyRecover",
1326     verify_recover_test_init,
1327     pkey_test_cleanup,
1328     pkey_test_parse,
1329     pkey_test_run
1330 };
1331
1332 static int decrypt_test_init(struct evp_test *t, const char *name)
1333 {
1334     return pkey_test_init(t, name, 0, EVP_PKEY_decrypt_init,
1335                           EVP_PKEY_decrypt);
1336 }
1337
1338 static const struct evp_test_method pdecrypt_test_method = {
1339     "Decrypt",
1340     decrypt_test_init,
1341     pkey_test_cleanup,
1342     pkey_test_parse,
1343     pkey_test_run
1344 };
1345
1346 static int verify_test_init(struct evp_test *t, const char *name)
1347 {
1348     return pkey_test_init(t, name, 1, EVP_PKEY_verify_init, 0);
1349 }
1350
1351 static int verify_test_run(struct evp_test *t)
1352 {
1353     struct pkey_data *kdata = t->data;
1354     if (EVP_PKEY_verify(kdata->ctx, kdata->output, kdata->output_len,
1355                         kdata->input, kdata->input_len) <= 0)
1356         t->err = "VERIFY_ERROR";
1357     return 1;
1358 }
1359
1360 static const struct evp_test_method pverify_test_method = {
1361     "Verify",
1362     verify_test_init,
1363     pkey_test_cleanup,
1364     pkey_test_parse,
1365     verify_test_run
1366 };
1367
1368
1369 static int pderive_test_init(struct evp_test *t, const char *name)
1370 {
1371     return pkey_test_init(t, name, 0, EVP_PKEY_derive_init, 0);
1372 }
1373
1374 static int pderive_test_parse(struct evp_test *t,
1375                               const char *keyword, const char *value)
1376 {
1377     struct pkey_data *kdata = t->data;
1378
1379     if (strcmp(keyword, "PeerKey") == 0) {
1380         EVP_PKEY *peer;
1381         if (find_key(&peer, value, t->public) == 0)
1382             return 0;
1383         if (EVP_PKEY_derive_set_peer(kdata->ctx, peer) <= 0)
1384             return 0;
1385         return 1;
1386     }
1387     if (strcmp(keyword, "SharedSecret") == 0)
1388         return test_bin(value, &kdata->output, &kdata->output_len);
1389     if (strcmp(keyword, "Ctrl") == 0)
1390         return pkey_test_ctrl(kdata->ctx, value);
1391     return 0;
1392 }
1393
1394 static int pderive_test_run(struct evp_test *t)
1395 {
1396     struct pkey_data *kdata = t->data;
1397     unsigned char *out = NULL;
1398     size_t out_len;
1399     const char *err = "INTERNAL_ERROR";
1400
1401     out_len = kdata->output_len;
1402     out = OPENSSL_malloc(out_len);
1403     if (!out) {
1404         fprintf(stderr, "Error allocating output buffer!\n");
1405         exit(1);
1406     }
1407     err = "DERIVE_ERROR";
1408     if (EVP_PKEY_derive(kdata->ctx, out, &out_len) <= 0)
1409         goto err;
1410     err = "SHARED_SECRET_LENGTH_MISMATCH";
1411     if (out_len != kdata->output_len)
1412         goto err;
1413     err = "SHARED_SECRET_MISMATCH";
1414     if (check_output(t, kdata->output, out, out_len))
1415         goto err;
1416     err = NULL;
1417  err:
1418     OPENSSL_free(out);
1419     t->err = err;
1420     return 1;
1421 }
1422
1423 static const struct evp_test_method pderive_test_method = {
1424     "Derive",
1425     pderive_test_init,
1426     pkey_test_cleanup,
1427     pderive_test_parse,
1428     pderive_test_run
1429 };
1430
1431 /* PBE tests */
1432
1433 #define PBE_TYPE_SCRYPT 1
1434 #define PBE_TYPE_PBKDF2 2
1435 #define PBE_TYPE_PKCS12 3
1436
1437 struct pbe_data {
1438
1439     int pbe_type;
1440
1441     /* scrypt parameters */
1442     uint64_t N, r, p, maxmem;
1443
1444     /* PKCS#12 parameters */
1445     int id, iter;
1446     const EVP_MD *md;
1447
1448     /* password */
1449     unsigned char *pass;
1450     size_t pass_len;
1451
1452     /* salt */
1453     unsigned char *salt;
1454     size_t salt_len;
1455
1456     /* Expected output */
1457     unsigned char *key;
1458     size_t key_len;
1459 };
1460
1461 #ifndef OPENSSL_NO_SCRYPT
1462 static int scrypt_test_parse(struct evp_test *t,
1463                              const char *keyword, const char *value)
1464 {
1465     struct pbe_data *pdata = t->data;
1466
1467     if (strcmp(keyword, "N") == 0)
1468         return test_uint64(value, &pdata->N);
1469     if (strcmp(keyword, "p") == 0)
1470         return test_uint64(value, &pdata->p);
1471     if (strcmp(keyword, "r") == 0)
1472         return test_uint64(value, &pdata->r);
1473     if (strcmp(keyword, "maxmem") == 0)
1474         return test_uint64(value, &pdata->maxmem);
1475     return 0;
1476 }
1477 #endif
1478
1479 static int pbkdf2_test_parse(struct evp_test *t,
1480                              const char *keyword, const char *value)
1481 {
1482     struct pbe_data *pdata = t->data;
1483
1484     if (strcmp(keyword, "iter") == 0) {
1485         pdata->iter = atoi(value);
1486         if (pdata->iter <= 0)
1487             return 0;
1488         return 1;
1489     }
1490     if (strcmp(keyword, "MD") == 0) {
1491         pdata->md = EVP_get_digestbyname(value);
1492         if (pdata->md == NULL)
1493             return 0;
1494         return 1;
1495     }
1496     return 0;
1497 }
1498
1499 static int pkcs12_test_parse(struct evp_test *t,
1500                              const char *keyword, const char *value)
1501 {
1502     struct pbe_data *pdata = t->data;
1503
1504     if (strcmp(keyword, "id") == 0) {
1505         pdata->id = atoi(value);
1506         if (pdata->id <= 0)
1507             return 0;
1508         return 1;
1509     }
1510     return pbkdf2_test_parse(t, keyword, value);
1511 }
1512
1513 static int pbe_test_init(struct evp_test *t, const char *alg)
1514 {
1515     struct pbe_data *pdat;
1516     int pbe_type = 0;
1517
1518     if (strcmp(alg, "scrypt") == 0) {
1519 #ifndef OPENSSL_NO_SCRYPT
1520         pbe_type = PBE_TYPE_SCRYPT;
1521 #else
1522         t->skip = 1;
1523         return 1;
1524 #endif
1525     } else if (strcmp(alg, "pbkdf2") == 0) {
1526         pbe_type = PBE_TYPE_PBKDF2;
1527     } else if (strcmp(alg, "pkcs12") == 0) {
1528         pbe_type = PBE_TYPE_PKCS12;
1529     } else {
1530         fprintf(stderr, "Unknown pbe algorithm %s\n", alg);
1531     }
1532     pdat = OPENSSL_malloc(sizeof(*pdat));
1533     pdat->pbe_type = pbe_type;
1534     pdat->pass = NULL;
1535     pdat->salt = NULL;
1536     pdat->N = 0;
1537     pdat->r = 0;
1538     pdat->p = 0;
1539     pdat->maxmem = 0;
1540     pdat->id = 0;
1541     pdat->iter = 0;
1542     pdat->md = NULL;
1543     t->data = pdat;
1544     return 1;
1545 }
1546
1547 static void pbe_test_cleanup(struct evp_test *t)
1548 {
1549     struct pbe_data *pdat = t->data;
1550     test_free(pdat->pass);
1551     test_free(pdat->salt);
1552     test_free(pdat->key);
1553 }
1554
1555 static int pbe_test_parse(struct evp_test *t,
1556                              const char *keyword, const char *value)
1557 {
1558     struct pbe_data *pdata = t->data;
1559
1560     if (strcmp(keyword, "Password") == 0)
1561         return test_bin(value, &pdata->pass, &pdata->pass_len);
1562     if (strcmp(keyword, "Salt") == 0)
1563         return test_bin(value, &pdata->salt, &pdata->salt_len);
1564     if (strcmp(keyword, "Key") == 0)
1565         return test_bin(value, &pdata->key, &pdata->key_len);
1566     if (pdata->pbe_type == PBE_TYPE_PBKDF2)
1567         return pbkdf2_test_parse(t, keyword, value);
1568     else if (pdata->pbe_type == PBE_TYPE_PKCS12)
1569         return pkcs12_test_parse(t, keyword, value);
1570 #ifndef OPENSSL_NO_SCRYPT
1571     else if (pdata->pbe_type == PBE_TYPE_SCRYPT)
1572         return scrypt_test_parse(t, keyword, value);
1573 #endif
1574     return 0;
1575 }
1576
1577 static int pbe_test_run(struct evp_test *t)
1578 {
1579     struct pbe_data *pdata = t->data;
1580     const char *err = "INTERNAL_ERROR";
1581     unsigned char *key;
1582
1583     key = OPENSSL_malloc(pdata->key_len);
1584     if (!key)
1585         goto err;
1586     if (pdata->pbe_type == PBE_TYPE_PBKDF2) {
1587         err = "PBKDF2_ERROR";
1588         if (PKCS5_PBKDF2_HMAC((char *)pdata->pass, pdata->pass_len,
1589                               pdata->salt, pdata->salt_len,
1590                               pdata->iter, pdata->md,
1591                               pdata->key_len, key) == 0)
1592             goto err;
1593 #ifndef OPENSSL_NO_SCRYPT
1594     } else if (pdata->pbe_type == PBE_TYPE_SCRYPT) {
1595         err = "SCRYPT_ERROR";
1596         if (EVP_PBE_scrypt((const char *)pdata->pass, pdata->pass_len,
1597                            pdata->salt, pdata->salt_len,
1598                            pdata->N, pdata->r, pdata->p, pdata->maxmem,
1599                            key, pdata->key_len) == 0)
1600             goto err;
1601 #endif
1602     } else if (pdata->pbe_type == PBE_TYPE_PKCS12) {
1603         err = "PKCS12_ERROR";
1604         if (PKCS12_key_gen_uni(pdata->pass, pdata->pass_len,
1605                                pdata->salt, pdata->salt_len,
1606                                pdata->id, pdata->iter, pdata->key_len,
1607                                key, pdata->md) == 0)
1608             goto err;
1609     }
1610     err = "KEY_MISMATCH";
1611     if (check_output(t, pdata->key, key, pdata->key_len))
1612         goto err;
1613     err = NULL;
1614     err:
1615     OPENSSL_free(key);
1616     t->err = err;
1617     return 1;
1618 }
1619
1620 static const struct evp_test_method pbe_test_method = {
1621     "PBE",
1622     pbe_test_init,
1623     pbe_test_cleanup,
1624     pbe_test_parse,
1625     pbe_test_run
1626 };
1627
1628 /* Base64 tests */
1629
1630 typedef enum {
1631     BASE64_CANONICAL_ENCODING = 0,
1632     BASE64_VALID_ENCODING = 1,
1633     BASE64_INVALID_ENCODING = 2
1634 } base64_encoding_type;
1635
1636 struct encode_data {
1637     /* Input to encoding */
1638     unsigned char *input;
1639     size_t input_len;
1640     /* Expected output */
1641     unsigned char *output;
1642     size_t output_len;
1643     base64_encoding_type encoding;
1644 };
1645
1646 static int encode_test_init(struct evp_test *t, const char *encoding)
1647 {
1648     struct encode_data *edata = OPENSSL_zalloc(sizeof(*edata));
1649
1650     if (strcmp(encoding, "canonical") == 0) {
1651         edata->encoding = BASE64_CANONICAL_ENCODING;
1652     } else if (strcmp(encoding, "valid") == 0) {
1653         edata->encoding = BASE64_VALID_ENCODING;
1654     } else if (strcmp(encoding, "invalid") == 0) {
1655         edata->encoding = BASE64_INVALID_ENCODING;
1656         t->expected_err = OPENSSL_strdup("DECODE_ERROR");
1657         if (t->expected_err == NULL)
1658             return 0;
1659     } else {
1660         fprintf(stderr, "Bad encoding: %s. Should be one of "
1661                 "{canonical, valid, invalid}\n", encoding);
1662         return 0;
1663     }
1664     t->data = edata;
1665     return 1;
1666 }
1667
1668 static void encode_test_cleanup(struct evp_test *t)
1669 {
1670     struct encode_data *edata = t->data;
1671     test_free(edata->input);
1672     test_free(edata->output);
1673     memset(edata, 0, sizeof(*edata));
1674 }
1675
1676 static int encode_test_parse(struct evp_test *t,
1677                              const char *keyword, const char *value)
1678 {
1679     struct encode_data *edata = t->data;
1680     if (strcmp(keyword, "Input") == 0)
1681         return test_bin(value, &edata->input, &edata->input_len);
1682     if (strcmp(keyword, "Output") == 0)
1683         return test_bin(value, &edata->output, &edata->output_len);
1684     return 0;
1685 }
1686
1687 static int encode_test_run(struct evp_test *t)
1688 {
1689     struct encode_data *edata = t->data;
1690     unsigned char *encode_out = NULL, *decode_out = NULL;
1691     int output_len, chunk_len;
1692     const char *err = "INTERNAL_ERROR";
1693     EVP_ENCODE_CTX *decode_ctx = EVP_ENCODE_CTX_new();
1694
1695     if (decode_ctx == NULL)
1696         goto err;
1697
1698     if (edata->encoding == BASE64_CANONICAL_ENCODING) {
1699         EVP_ENCODE_CTX *encode_ctx = EVP_ENCODE_CTX_new();
1700         if (encode_ctx == NULL)
1701             goto err;
1702         encode_out = OPENSSL_malloc(EVP_ENCODE_LENGTH(edata->input_len));
1703         if (encode_out == NULL)
1704             goto err;
1705
1706         EVP_EncodeInit(encode_ctx);
1707         EVP_EncodeUpdate(encode_ctx, encode_out, &chunk_len,
1708                          edata->input, edata->input_len);
1709         output_len = chunk_len;
1710
1711         EVP_EncodeFinal(encode_ctx, encode_out + chunk_len, &chunk_len);
1712         output_len += chunk_len;
1713
1714         EVP_ENCODE_CTX_free(encode_ctx);
1715
1716         if (check_var_length_output(t, edata->output, edata->output_len,
1717                                     encode_out, output_len)) {
1718             err = "BAD_ENCODING";
1719             goto err;
1720         }
1721     }
1722
1723     decode_out = OPENSSL_malloc(EVP_DECODE_LENGTH(edata->output_len));
1724     if (decode_out == NULL)
1725         goto err;
1726
1727     EVP_DecodeInit(decode_ctx);
1728     if (EVP_DecodeUpdate(decode_ctx, decode_out, &chunk_len, edata->output,
1729                          edata->output_len) < 0) {
1730         err = "DECODE_ERROR";
1731         goto err;
1732     }
1733     output_len = chunk_len;
1734
1735     if (EVP_DecodeFinal(decode_ctx, decode_out + chunk_len, &chunk_len) != 1) {
1736         err = "DECODE_ERROR";
1737         goto err;
1738     }
1739     output_len += chunk_len;
1740
1741     if (edata->encoding != BASE64_INVALID_ENCODING &&
1742         check_var_length_output(t, edata->input, edata->input_len,
1743                                 decode_out, output_len)) {
1744         err = "BAD_DECODING";
1745         goto err;
1746     }
1747
1748     err = NULL;
1749  err:
1750     t->err = err;
1751     OPENSSL_free(encode_out);
1752     OPENSSL_free(decode_out);
1753     EVP_ENCODE_CTX_free(decode_ctx);
1754     return 1;
1755 }
1756
1757 static const struct evp_test_method encode_test_method = {
1758     "Encoding",
1759     encode_test_init,
1760     encode_test_cleanup,
1761     encode_test_parse,
1762     encode_test_run,
1763 };
1764
1765 /* KDF operations */
1766
1767 struct kdf_data {
1768     /* Context for this operation */
1769     EVP_PKEY_CTX *ctx;
1770     /* Expected output */
1771     unsigned char *output;
1772     size_t output_len;
1773 };
1774
1775 /*
1776  * Perform public key operation setup: lookup key, allocated ctx and call
1777  * the appropriate initialisation function
1778  */
1779 static int kdf_test_init(struct evp_test *t, const char *name)
1780 {
1781     struct kdf_data *kdata;
1782
1783     kdata = OPENSSL_malloc(sizeof(*kdata));
1784     if (kdata == NULL)
1785         return 0;
1786     kdata->ctx = NULL;
1787     kdata->output = NULL;
1788     t->data = kdata;
1789     kdata->ctx = EVP_PKEY_CTX_new_id(OBJ_sn2nid(name), NULL);
1790     if (kdata->ctx == NULL)
1791         return 0;
1792     if (EVP_PKEY_derive_init(kdata->ctx) <= 0)
1793         return 0;
1794     return 1;
1795 }
1796
1797 static void kdf_test_cleanup(struct evp_test *t)
1798 {
1799     struct kdf_data *kdata = t->data;
1800     OPENSSL_free(kdata->output);
1801     EVP_PKEY_CTX_free(kdata->ctx);
1802 }
1803
1804 static int kdf_test_parse(struct evp_test *t,
1805                           const char *keyword, const char *value)
1806 {
1807     struct kdf_data *kdata = t->data;
1808     if (strcmp(keyword, "Output") == 0)
1809         return test_bin(value, &kdata->output, &kdata->output_len);
1810     if (strncmp(keyword, "Ctrl", 4) == 0)
1811         return pkey_test_ctrl(kdata->ctx, value);
1812     return 0;
1813 }
1814
1815 static int kdf_test_run(struct evp_test *t)
1816 {
1817     struct kdf_data *kdata = t->data;
1818     unsigned char *out = NULL;
1819     size_t out_len = kdata->output_len;
1820     const char *err = "INTERNAL_ERROR";
1821     out = OPENSSL_malloc(out_len);
1822     if (!out) {
1823         fprintf(stderr, "Error allocating output buffer!\n");
1824         exit(1);
1825     }
1826     err = "KDF_DERIVE_ERROR";
1827     if (EVP_PKEY_derive(kdata->ctx, out, &out_len) <= 0)
1828         goto err;
1829     err = "KDF_LENGTH_MISMATCH";
1830     if (out_len != kdata->output_len)
1831         goto err;
1832     err = "KDF_MISMATCH";
1833     if (check_output(t, kdata->output, out, out_len))
1834         goto err;
1835     err = NULL;
1836  err:
1837     OPENSSL_free(out);
1838     t->err = err;
1839     return 1;
1840 }
1841
1842 static const struct evp_test_method kdf_test_method = {
1843     "KDF",
1844     kdf_test_init,
1845     kdf_test_cleanup,
1846     kdf_test_parse,
1847     kdf_test_run
1848 };