blob: 3203d976be7683626f8a1f96dc8bcf2d1d27ac8f [file] [log] [blame]
yuezonghe824eb0c2024-06-27 02:32:26 -07001/*
2 * Copyright 2017-2018 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 <string.h>
11#include <openssl/bio.h>
12#include <openssl/pem.h>
13
14#include "testutil.h"
15#include "internal/nelem.h"
16
17typedef struct {
18 const char *raw;
19 const char *encoded;
20} TESTDATA;
21
22static TESTDATA b64_pem_data[] = {
23 { "hello world",
24 "aGVsbG8gd29ybGQ=" },
25 { "a very ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong input",
26 "YSB2ZXJ5IG9vb29vb29vb29vb29vb29vb29vb29vb29vb29vb29vb29vb29vb29vb29vb29vb29vb29vb29vb29vb29vb29vb29vb29vb29vb29vb29vb29vb29vb29vb29uZyBpbnB1dA==" }
27};
28
29static const char *pemtype = "PEMTESTDATA";
30
31static int test_b64(int idx)
32{
33 BIO *b = BIO_new(BIO_s_mem());
34 char *name = NULL, *header = NULL;
35 unsigned char *data = NULL;
36 long len;
37 int ret = 0;
38 const char *raw = b64_pem_data[idx].raw;
39 const char *encoded = b64_pem_data[idx].encoded;
40
41 if (!TEST_ptr(b)
42 || !TEST_true(BIO_printf(b, "-----BEGIN %s-----\n", pemtype))
43 || !TEST_true(BIO_printf(b, "%s\n", encoded))
44 || !TEST_true(BIO_printf(b, "-----END %s-----\n", pemtype))
45 || !TEST_true(PEM_read_bio_ex(b, &name, &header, &data, &len,
46 PEM_FLAG_ONLY_B64)))
47 goto err;
48 if (!TEST_int_eq(memcmp(pemtype, name, strlen(pemtype)), 0)
49 || !TEST_int_eq(len, strlen(raw))
50 || !TEST_int_eq(memcmp(data, raw, strlen(raw)), 0))
51 goto err;
52 ret = 1;
53 err:
54 BIO_free(b);
55 OPENSSL_free(name);
56 OPENSSL_free(header);
57 OPENSSL_free(data);
58 return ret;
59}
60
61static int test_invalid(void)
62{
63 BIO *b = BIO_new(BIO_s_mem());
64 char *name = NULL, *header = NULL;
65 unsigned char *data = NULL;
66 long len;
67 const char *encoded = b64_pem_data[0].encoded;
68
69 if (!TEST_ptr(b)
70 || !TEST_true(BIO_printf(b, "-----BEGIN %s-----\n", pemtype))
71 || !TEST_true(BIO_printf(b, "%c%s\n", '\t', encoded))
72 || !TEST_true(BIO_printf(b, "-----END %s-----\n", pemtype))
73 /* Expected to fail due to non-base64 character */
74 || TEST_true(PEM_read_bio_ex(b, &name, &header, &data, &len,
75 PEM_FLAG_ONLY_B64))) {
76 BIO_free(b);
77 return 0;
78 }
79 BIO_free(b);
80 OPENSSL_free(name);
81 OPENSSL_free(header);
82 OPENSSL_free(data);
83 return 1;
84}
85
86int setup_tests(void)
87{
88 ADD_ALL_TESTS(test_b64, OSSL_NELEM(b64_pem_data));
89 ADD_TEST(test_invalid);
90 return 1;
91}