簡體   English   中英

如何使用openssl API解密ASN.1 DER編碼的CMS文件?

[英]how to decrypt ASN.1 DER encoded CMS file using the openssl API?

我有一個DER編碼的CMS文件,我想使用openssl API解密。

我發現了用於解密的API

CMS_decrypt(cms_content, pkey, cert, NULL, out, NULL);

我已經找到了讀取pkey和cert PEM文件以及設置輸出BIO的示例,但是我找不到如何讀取cms文件的示例。

:我怎樣才能讀取ASN.1 DER編碼文件到cms_content具有類型變量CMS_ContentInfo


編輯:感謝Camille的回答 ,我設法使其與以下產品一起使用:

#include <stdio.h>

#include <openssl/ssl.h>
#include <openssl/err.h>
#include <openssl/cms.h>

int main (int argc, char **argv)
{
    char pkeypath[] = "recipient_prvkey.pem";
    char certpath[] = "sender_cert.pem";
    char cmspath[] = "encrypted.der";
    char decpath[] = "decrypted.zip";

    BIO *in = NULL, *out = NULL, *tbio = NULL;
    CMS_ContentInfo *cms = NULL;

    EVP_PKEY *pkey;
    X509 *cert;

    OpenSSL_add_all_algorithms();
    ERR_load_crypto_strings();

    tbio = BIO_new_file(pkeypath, "r");
    pkey = PEM_read_bio_PrivateKey(tbio, NULL, 0, NULL);
    if (pkey == NULL) {
        printf("error reading private key");
        return EXIT_FAILURE;
    }
    BIO_free(tbio);

    tbio = BIO_new_file(certpath, "r");
    cert = PEM_read_bio_X509(tbio, NULL, 0, NULL);
    if (cert == NULL) {
        printf("error reading private key");
        return EXIT_FAILURE;
    }

    in = BIO_new_file(cmspath, "r");
    cms = d2i_CMS_bio(in, NULL);
    BIO_free(in);

    out = BIO_new_file(decpath, "w");

    if (!CMS_decrypt_set1_pkey(cms, pkey, cert))
    {
        fprintf(stderr, "set1_pkey error\n");
        return EXIT_FAILURE;
    }

    if (!CMS_decrypt(cms, NULL, NULL, NULL, out, CMS_BINARY))
    {
        int error = ERR_get_error();

        fprintf(stderr, "error: %s :: %s :: %s\n",
                ERR_reason_error_string(error),
                ERR_func_error_string(error),
                ERR_lib_error_string(error)
                );
    }
    BIO_free(out);

    return 0;
}

我只是復制了可與PEM一起使用的OpenSSL cms_dec示例,並將其改編為DER編碼的CMS文件

BIO *in = NULL, *out = NULL, *tbio = NULL;
X509 *cert= NULL;
EVP_PKEY *rkey = NULL;
CMS_ContentInfo *cms = NULL;
int ret = 1;

OpenSSL_add_all_algorithms();
ERR_load_crypto_strings();

/* Read in recipient certificate and private key */
tbio = BIO_new_file("yourCMS.der", "r");
rcert = i2d_x509_bio(tbio, NULL);
BIO_reset(tbio);
i2d_PrivateKey_bio(tbio, rkey);

/* Open S/MIME message to decrypt */
in = BIO_new_file("smencr.txt", "r");

/* Parse message */
cms = SMIME_read_CMS(in, NULL);

out = BIO_new_file("decout.txt", "w");

/* Decrypt S/MIME message */
CMS_decrypt(cms, rkey, rcert, out, NULL, CMS_BINARY) //Edit : Added Flags for DER.
...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM