2 * Copyright 2016-2017 The OpenSSL Project Authors. All Rights Reserved.
4 * Licensed under the OpenSSL licenses, (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 * https://www.openssl.org/source/license.html
8 * or in the file LICENSE in the source distribution.
15 #include <openssl/x509.h>
16 #include <openssl/pem.h>
17 #include <openssl/conf.h>
18 #include <openssl/err.h>
23 /* List of files, from argv */
26 static int test_certs(int num)
31 unsigned char *data = 0;
33 typedef X509 *(*d2i_X509_t)(X509 **, const unsigned char **, long);
34 typedef int (*i2d_X509_t)(X509 *, unsigned char **);
36 BIO *fp = BIO_new_file(files[num], "r");
42 !err && PEM_read_bio(fp, &name, &header, &data, &len);
44 int trusted = strcmp(name, PEM_STRING_X509_TRUSTED) == 0;
45 d2i_X509_t d2i = trusted ? d2i_X509_AUX : d2i_X509;
46 i2d_X509_t i2d = trusted ? i2d_X509_AUX : i2d_X509;
48 const unsigned char *p = data;
49 unsigned char *buf = NULL;
54 && strcmp(name, PEM_STRING_X509) != 0
55 && strcmp(name, PEM_STRING_X509_OLD) != 0) {
56 TEST_error("unexpected PEM object: %s", name);
60 cert = d2i(NULL, &p, len);
62 if (cert == NULL || (p - data) != len) {
63 TEST_error("error parsing input %s", name);
68 /* Test traditional 2-pass encoding into caller allocated buffer */
69 enclen = i2d(cert, NULL);
71 TEST_error("encoded length %ld of %s != input length %ld",
76 if ((buf = bufp = OPENSSL_malloc(len)) == NULL) {
77 TEST_perror("malloc");
81 enclen = i2d(cert, &bufp);
83 TEST_error("encoded length %ld of %s != input length %ld",
88 enclen = (long) (bufp - buf);
90 TEST_error("unexpected buffer position after encoding %s", name);
94 if (memcmp(buf, data, len) != 0) {
95 TEST_error("encoded content of %s does not match input", name);
102 /* Test 1-pass encoding into library allocated buffer */
103 enclen = i2d(cert, &buf);
105 TEST_error("encoded length %ld of %s != input length %ld",
110 if (memcmp(buf, data, len) != 0) {
111 TEST_error("encoded content of %s does not match input", name);
117 /* Encode just the cert and compare with initial encoding */
121 /* Test 1-pass encoding into library allocated buffer */
122 enclen = i2d(cert, &buf);
124 TEST_error("encoded length %ld of %s > input length %ld",
129 if (memcmp(buf, data, enclen) != 0) {
130 TEST_error("encoded cert content does not match input");
137 * If any of these were null, PEM_read() would have failed.
143 OPENSSL_free(header);
148 if (ERR_GET_REASON(ERR_peek_last_error()) == PEM_R_NO_START_LINE) {
149 /* Reached end of PEM file */
156 /* Some other PEM read error */
160 int test_main(int argc, char *argv[])
163 TEST_error("usage: %s certfile...", argv[0]);
168 ADD_ALL_TESTS(test_certs, argc - 1);
169 return run_tests(argv[0]);