openssl3.2 - 官方demo学习 - smime - smdec.c

发布时间:2024年01月19日

openssl3.2 - 官方demo学习 - smime - smdec.c

概述

从pem证书中得到x509*和私钥, 用私钥和证书解密MIME格式的PKCS7密文, 并保存解密后的明文
MIME的数据操作, 都是PKCS7相关的

笔记

/*!
\file smdec.c
\note 
openssl3.2 - 官方demo学习 - smime - smdec.c

从pem证书中得到x509*和私钥, 用私钥和证书解密MIME格式的PKCS7密文, 并保存解密后的明文
MIME的数据操作, 都是PKCS7相关的
*/

/*
 * Copyright 2007-2023 The OpenSSL Project Authors. All Rights Reserved.
 *
 * Licensed under the Apache License 2.0 (the "License").  You may not use
 * this file except in compliance with the License.  You can obtain a copy
 * in the file LICENSE in the source distribution or at
 * https://www.openssl.org/source/license.html
 */

/* Simple S/MIME signing example */
#include <openssl/pem.h>
#include <openssl/pkcs7.h>
#include <openssl/err.h>

#include "my_openSSL_lib.h"

int main(int argc, char **argv)
{
    BIO *_bio_sm = NULL, *_bio_out = NULL, *_bio_pem = NULL;
    X509 *_x509_pem = NULL;
    EVP_PKEY *_evp_pkey = NULL;
    PKCS7 *_pkcs7 = NULL;
    int ret = EXIT_FAILURE;

    OpenSSL_add_all_algorithms();
    ERR_load_crypto_strings();

    /* Read in recipient certificate and private key */
    _bio_pem = BIO_new_file("signer.pem", "r");

    if (!_bio_pem)
        goto err;

    _x509_pem = PEM_read_bio_X509(_bio_pem, NULL, 0, NULL);

    BIO_reset(_bio_pem);

    _evp_pkey = PEM_read_bio_PrivateKey(_bio_pem, NULL, 0, NULL);

    if (!_x509_pem || !_evp_pkey)
        goto err;

    /* Open content being signed */

    _bio_sm = BIO_new_file("smencr.txt", "r");

    if (!_bio_sm)
        goto err;

    /* Sign content */
    _pkcs7 = SMIME_read_PKCS7(_bio_sm, NULL);

    if (!_pkcs7)
        goto err;

    _bio_out = BIO_new_file("encrout.txt", "w");
    if (!_bio_out)
        goto err;

    /* Decrypt S/MIME message */
    if (!PKCS7_decrypt(_pkcs7, _evp_pkey, _x509_pem, _bio_out, 0))
        goto err;

    ret = EXIT_SUCCESS;

 err:
    if (ret != EXIT_SUCCESS) {
        fprintf(stderr, "Error Signing Data\n");
        ERR_print_errors_fp(stderr);
    }
    PKCS7_free(_pkcs7);
    X509_free(_x509_pem);
    EVP_PKEY_free(_evp_pkey);
    BIO_free(_bio_sm);
    BIO_free(_bio_out);
    BIO_free(_bio_pem);

    return ret;

}

END

文章来源:https://blog.csdn.net/LostSpeed/article/details/135642805
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。