Created
July 21, 2018 11:09
-
-
Save ykon/5fd2922ab69b1ac7dc7bdd021ec88fca to your computer and use it in GitHub Desktop.
CMS Encrypt
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_enc.c | |
| // g++ test_enc.cpp -lcrypto -o test_enc | |
| #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_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(); | |
| X509 *rcert = PEM_read_bio_X509(cert_io, NULL, 0, NULL); | |
| if (!rcert) | |
| exit_openssl_error(); | |
| STACK_OF(X509) *recips = sk_X509_new_null(); | |
| if (!recips || !sk_X509_push(recips, rcert)) | |
| exit_openssl_error(); | |
| rcert = NULL; | |
| BIO *in = BIO_new_file(target_file_path, "r"); | |
| if (!in) | |
| exit_openssl_error(); | |
| CMS_ContentInfo *cms = CMS_encrypt(recips, in, EVP_des_ede3_cbc(), flags); | |
| if (!cms) | |
| exit_openssl_error(); | |
| BIO *out = BIO_new(BIO_s_mem()); | |
| if (!out) | |
| exit_openssl_error(); | |
| 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(rcert); | |
| sk_X509_pop_free(recips, X509_free); | |
| 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