xref: /third_party/openssl/demos/pkcs12/pkwrite.c (revision e1051a39)
1e1051a39Sopenharmony_ci/*
2e1051a39Sopenharmony_ci * Copyright 2000-2020 The OpenSSL Project Authors. All Rights Reserved.
3e1051a39Sopenharmony_ci *
4e1051a39Sopenharmony_ci * Licensed under the Apache License 2.0 (the "License").  You may not use
5e1051a39Sopenharmony_ci * this file except in compliance with the License.  You can obtain a copy
6e1051a39Sopenharmony_ci * in the file LICENSE in the source distribution or at
7e1051a39Sopenharmony_ci * https://www.openssl.org/source/license.html
8e1051a39Sopenharmony_ci */
9e1051a39Sopenharmony_ci
10e1051a39Sopenharmony_ci#include <stdio.h>
11e1051a39Sopenharmony_ci#include <stdlib.h>
12e1051a39Sopenharmony_ci#include <openssl/pem.h>
13e1051a39Sopenharmony_ci#include <openssl/err.h>
14e1051a39Sopenharmony_ci#include <openssl/pkcs12.h>
15e1051a39Sopenharmony_ci
16e1051a39Sopenharmony_ci/* Simple PKCS#12 file creator */
17e1051a39Sopenharmony_ci
18e1051a39Sopenharmony_ciint main(int argc, char **argv)
19e1051a39Sopenharmony_ci{
20e1051a39Sopenharmony_ci    FILE *fp;
21e1051a39Sopenharmony_ci    EVP_PKEY *pkey;
22e1051a39Sopenharmony_ci    X509 *cert;
23e1051a39Sopenharmony_ci    PKCS12 *p12;
24e1051a39Sopenharmony_ci    if (argc != 5) {
25e1051a39Sopenharmony_ci        fprintf(stderr, "Usage: pkwrite infile password name p12file\n");
26e1051a39Sopenharmony_ci        exit(1);
27e1051a39Sopenharmony_ci    }
28e1051a39Sopenharmony_ci    OpenSSL_add_all_algorithms();
29e1051a39Sopenharmony_ci    ERR_load_crypto_strings();
30e1051a39Sopenharmony_ci    if ((fp = fopen(argv[1], "r")) == NULL) {
31e1051a39Sopenharmony_ci        fprintf(stderr, "Error opening file %s\n", argv[1]);
32e1051a39Sopenharmony_ci        exit(1);
33e1051a39Sopenharmony_ci    }
34e1051a39Sopenharmony_ci    cert = PEM_read_X509(fp, NULL, NULL, NULL);
35e1051a39Sopenharmony_ci    rewind(fp);
36e1051a39Sopenharmony_ci    pkey = PEM_read_PrivateKey(fp, NULL, NULL, NULL);
37e1051a39Sopenharmony_ci    fclose(fp);
38e1051a39Sopenharmony_ci    p12 = PKCS12_create(argv[2], argv[3], pkey, cert, NULL, 0, 0, 0, 0, 0);
39e1051a39Sopenharmony_ci    if (!p12) {
40e1051a39Sopenharmony_ci        fprintf(stderr, "Error creating PKCS#12 structure\n");
41e1051a39Sopenharmony_ci        ERR_print_errors_fp(stderr);
42e1051a39Sopenharmony_ci        exit(1);
43e1051a39Sopenharmony_ci    }
44e1051a39Sopenharmony_ci    if ((fp = fopen(argv[4], "wb")) == NULL) {
45e1051a39Sopenharmony_ci        fprintf(stderr, "Error opening file %s\n", argv[4]);
46e1051a39Sopenharmony_ci        ERR_print_errors_fp(stderr);
47e1051a39Sopenharmony_ci        exit(1);
48e1051a39Sopenharmony_ci    }
49e1051a39Sopenharmony_ci    i2d_PKCS12_fp(fp, p12);
50e1051a39Sopenharmony_ci    PKCS12_free(p12);
51e1051a39Sopenharmony_ci    fclose(fp);
52e1051a39Sopenharmony_ci    return 0;
53e1051a39Sopenharmony_ci}
54