Created
July 21, 2018 11:06
-
-
Save ykon/9ec12b63ec3b06172ac4a62afba027e3 to your computer and use it in GitHub Desktop.
CMS Sign
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // original: openssl/demos/cms/cms_sign.c | |
| // g++ test_sign.cpp -lcrypto -o test_sign | |
| #include <iostream> | |
| #include <string> | |
| #include <openssl/bio.h> | |
| #include <openssl/err.h> | |
| #include <openssl/ssl.h> | |
| #include <openssl/pkcs7.h> | |
| #include <openssl/safestack.h> | |
| #include <openssl/x509.h> | |
| #include <openssl/x509v3.h> /* X509_PURPOSE_ANY */ | |
| #include <openssl/x509_vfy.h> | |
| #include <openssl/cms.h> | |
| #include <openssl/pem.h> | |
| std::string get_bio_str(BIO* bio) { | |
| char* data; | |
| BIO_get_mem_data(bio, &data); | |
| return data; | |
| } | |
| void print_openssl_errors() { | |
| ERR_print_errors_fp(stderr); | |
| } | |
| void exit_openssl_error() { | |
| print_openssl_errors(); | |
| exit(1); | |
| } | |
| int main(int argc, char* argv[]) { | |
| if (argc < 3) { | |
| std::cerr << argv[0] << " cert-file target-file" << std::endl; | |
| return 1; | |
| } | |
| const char *cert_file_path = argv[1]; | |
| const char *target_file_path = argv[2]; | |
| int flags = CMS_DETACHED | CMS_STREAM; | |
| OpenSSL_add_all_algorithms(); | |
| ERR_load_crypto_strings(); | |
| BIO *cert_io = BIO_new_file(cert_file_path, "r"); | |
| if (!cert_io) | |
| exit_openssl_error(); | |
| EVP_PKEY *skey = PEM_read_bio_PrivateKey(cert_io, NULL, 0, NULL); | |
| if (!skey) | |
| exit_openssl_error(); | |
| BIO_reset(cert_io); | |
| X509 *scert = PEM_read_bio_X509(cert_io, NULL, 0, NULL); | |
| if (!scert) | |
| exit_openssl_error(); | |
| BIO *in = BIO_new_file(target_file_path, "r"); | |
| if (!in) | |
| exit_openssl_error(); | |
| CMS_ContentInfo *cms = CMS_sign(scert, skey, NULL, in, flags); | |
| if (!cms) | |
| exit_openssl_error(); | |
| BIO *out = BIO_new(BIO_s_mem()); | |
| if (!out) | |
| exit_openssl_error(); | |
| if (!(flags & CMS_STREAM)) | |
| BIO_reset(in); | |
| if (!SMIME_write_CMS(out, cms, in, flags)) | |
| exit_openssl_error(); | |
| std::cout << get_bio_str(out) << std::endl; | |
| CMS_ContentInfo_free(cms); | |
| X509_free(scert); | |
| EVP_PKEY_free(skey); | |
| BIO_free(cert_io); | |
| BIO_free(in); | |
| BIO_free(out); | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment