Created
July 21, 2018 11:11
-
-
Save ykon/059ea3c9fc4cb949475e0099d018a7e7 to your computer and use it in GitHub Desktop.
CMS Decrypt
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_dec.c | |
// g++ test_dec.cpp -lcrypto -o test_dec | |
#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]; | |
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(); | |
BIO_reset(cert_io); | |
EVP_PKEY *rkey = PEM_read_bio_PrivateKey(cert_io, NULL, 0, NULL); | |
if (!rkey) | |
exit_openssl_error(); | |
BIO *in = BIO_new_file(target_file_path, "r"); | |
if (!in) | |
exit_openssl_error(); | |
CMS_ContentInfo *cms = SMIME_read_CMS(in, NULL); | |
if (!cms) | |
exit_openssl_error(); | |
BIO *out = BIO_new(BIO_s_mem()); | |
if (!out) | |
exit_openssl_error(); | |
if (!CMS_decrypt(cms, rkey, rcert, NULL, out, 0)) | |
exit_openssl_error(); | |
std::cout << get_bio_str(out) << std::endl; | |
CMS_ContentInfo_free(cms); | |
X509_free(rcert); | |
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