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

发布时间:2024年01月17日

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

概述

读取X509证书, 用PKCS7加密明文(证书 + 明文 + 3DES_CBC), 保存为MIME格式的密文

openssl API的命名含义

BIO_new_file
“new” a “file”, return a “BIO” object

PEM_read_bio_X509() Read a certificate in PEM format from a BIO
data format is “PEM”, “read” from “bio”, return a object type is “X509”

笔记

/*!
\file smenc.c
\note
openssl3.2 - 官方demo学习 - smime - smenc.c
读取X509证书, 用PKCS7加密明文(证书 + 明文 + 3DES_CBC), 保存为MIME格式的密文

openssl API的命名含义

BIO_new_file
"new" a "file", return a "BIO" object

PEM_read_bio_X509() Read a certificate in PEM format from a BIO
data format is "PEM", "read" from "bio", return a object type is "X509"
*/

/*
 * 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 encrypt 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_in = NULL, * _bio_out = NULL, * _bio_t = NULL;
	X509* _x509_r = NULL;
	STACK_OF(X509)* _sk_x509 = NULL;
	PKCS7* _pkcs7 = NULL;
	int ret = EXIT_FAILURE;

	/*
	 * On OpenSSL 0.9.9 only:
	 * for streaming set PKCS7_STREAM
	 */
	int flags_encrypt = PKCS7_STREAM;

	OpenSSL_add_all_algorithms();
	ERR_load_crypto_strings();

	/* Read in recipient certificate */
	_bio_t = BIO_new_file("signer.pem", "r");

	if (!_bio_t)
		goto err;

	_x509_r = PEM_read_bio_X509(_bio_t, NULL, 0, NULL);

	if (!_x509_r)
		goto err;

	/* Create recipient STACK and add recipient cert to it */
	_sk_x509 = sk_X509_new_null();

	if (!_sk_x509 || !sk_X509_push(_sk_x509, _x509_r))
		goto err;

	/*
	 * OSSL_STACK_OF_X509_free() will free up recipient STACK and its contents
	 * so set rcert to NULL so it isn't freed up twice.
	 */
	_x509_r = NULL;

	/* Open content being encrypted */

	_bio_in = BIO_new_file("encr.txt", "r");

	if (!_bio_in)
		goto err;

	/* encrypt content */
	_pkcs7 = PKCS7_encrypt(_sk_x509, _bio_in, EVP_des_ede3_cbc(), flags_encrypt);

	if (!_pkcs7)
		goto err;

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

	/* Write out S/MIME message */
	if (!SMIME_write_PKCS7(_bio_out, _pkcs7, _bio_in, flags_encrypt))
		goto err;

	ret = EXIT_SUCCESS;

err:
	if (ret != EXIT_SUCCESS) {
		fprintf(stderr, "Error Encrypting Data\n");
		ERR_print_errors_fp(stderr);
	}
	PKCS7_free(_pkcs7);
	X509_free(_x509_r);
	OSSL_STACK_OF_X509_free(_sk_x509);
	BIO_free(_bio_in);
	BIO_free(_bio_out);
	BIO_free(_bio_t);
	return ret;

}

END

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