文章目录
openssl3.2 - 官方demo学习 - smime - smsign.c
概述
从证书中得到X509*和私钥指针
用证书和私钥对铭文进行签名, 得到签名后的pkcs7指针
将pkcs7指向的bio_in, 写为MIME格式的签名密文
BIO_reset() 可以将一个bio恢复到刚打开的状态(应该就是将文件指针重新指向文件头部), 一般用于只读打开的场景
经常用于多个对象要操作同一个bio的场景(一先一后的操作).
笔记
c
/*!
\file smsign.c
\note
openssl3.2 - 官方demo学习 - smime - smsign.c
从证书中得到X509*和私钥指针
用证书和私钥对铭文进行签名, 得到签名后的pkcs7指针
将pkcs7指向的bio_in, 写为MIME格式的签名密文
BIO_reset() 可以将一个bio恢复到刚打开的状态(应该就是将文件指针重新指向文件头部), 一般用于只读打开的场景
经常用于多个对象要操作同一个bio的场景(一先一后的操作).
*/
/*
* 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_in = NULL, *_bio_out = NULL, *_bio_t = NULL;
X509 *_x509 = NULL;
EVP_PKEY *_evp_pkey = NULL;
PKCS7 *_pkcs7 = NULL;
int ret = EXIT_FAILURE;
/*
* For simple S/MIME signing use PKCS7_DETACHED. On OpenSSL 0.9.9 only:
* for streaming detached set PKCS7_DETACHED|PKCS7_STREAM for streaming
* non-detached set PKCS7_STREAM
*/
int flags = PKCS7_DETACHED | PKCS7_STREAM;
OpenSSL_add_all_algorithms();
ERR_load_crypto_strings();
/* Read in signer certificate and private key */
_bio_t = BIO_new_file("signer.pem", "r");
if (!_bio_t)
goto err;
_x509 = PEM_read_bio_X509(_bio_t, NULL, 0, NULL);
BIO_reset(_bio_t);
_evp_pkey = PEM_read_bio_PrivateKey(_bio_t, NULL, 0, NULL);
if (!_x509 || !_evp_pkey)
goto err;
/* Open content being signed */
_bio_in = BIO_new_file("sign.txt", "r");
if (!_bio_in)
goto err;
/* Sign content */
_pkcs7 = PKCS7_sign(_x509, _evp_pkey, NULL, _bio_in, flags);
if (!_pkcs7)
goto err;
_bio_out = BIO_new_file("smout.txt", "w");
if (!_bio_out)
goto err;
if (!(flags & PKCS7_STREAM))
BIO_reset(_bio_in);
/* Write out S/MIME message */
if (!SMIME_write_PKCS7(_bio_out, _pkcs7, _bio_in, flags))
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);
EVP_PKEY_free(_evp_pkey);
BIO_free(_bio_in);
BIO_free(_bio_out);
BIO_free(_bio_t);
return ret;
}