c - openssl 解密签名和加密的消息

标签 c openssl

我正在尝试一个小示例程序来解密已签名然后使用 openSSL 加密的消息。它在命令行中运行良好。但是在修改OpenSSL的'demos'文件夹中的代码后试用代码,解密失败

解密代码如下:

   int decrypt_smime(){

        BIO *in = NULL, *out = NULL, *tbio = NULL;
        X509 *rcert = NULL;
        EVP_PKEY *rkey = NULL;
        //PKCS7 *cms = NULL;
        CMS_ContentInfo *cms = NULL;
        int ret = 1;
        int flags = CMS_STREAM;
        OpenSSL_add_all_algorithms();
        ERR_load_crypto_strings();
        printf("decrypt...\n");
        /* Read in recipient certificate and private key */
        tbio = BIO_new_file("signer.pem", "r");

        if (!tbio)
            goto err;

        rcert = PEM_read_bio_X509(tbio, NULL, 0, NULL);

        BIO_reset(tbio);

        rkey = PEM_read_bio_PrivateKey(tbio, NULL, 0, NULL);

        if (!rcert || !rkey)
            goto err;
        printf("decrypt...\n");
        /* Open S/MIME message to decrypt */

        in = BIO_new_file("smencsign.txt", "r");

        if (!in)
            goto err;
        printf("keys read...\n");
        /* Parse message */
        cms = SMIME_read_CMS(in, NULL); //here is the problem I think

        if (!cms)
            goto err;
        printf("keys read...\n");
        out = BIO_new_file("decout.txt", "w");
        if (!out)
            goto err;

        /* Decrypt S/MIME message */
        if (!CMS_decrypt(cms, rkey, rcert, NULL, out, flags))
            goto err;

        ret = 0;

        err:

        if (ret)
        {
            fprintf(stderr, "Error Decrypting Data\n");
            ERR_print_errors_fp(stderr);
        }

        if (cms)
            //PKCS7_free(cms);
            CMS_ContentInfo_free(cms);
        if (rcert)
            X509_free(rcert);
        if (rkey)
            EVP_PKEY_free(rkey);

        if (in)
            BIO_free(in);
        if (out)
            BIO_free(out);
        if (tbio)
            BIO_free(tbio);

        return ret;

    }

我得到的错误是: 错误验证数据 *3074258568:error:0D0D40D1:asn1 encoding routines:SMIME_read_ASN1:no content type:asn_mime.c:451:*

The commands on openssl that worked:

openssl cms -sign -in encr.txt -signer signer.pem -text | openssl cms -encrypt -out smencsign.txt signer.pem 

openssl smime -decrypt -in smencsign.txt -recip signer.pem -inkey signer.pem

很明显,openssl 使用“cms”实用程序进行签名和加密,但似乎使用“smime”实用程序进行解密。那么等效的代码是什么?

最佳答案

尝试添加以下行:

OpenSSL_add_all_ciphers();

关于c - openssl 解密签名和加密的消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18448182/

相关文章:

Java AES 128 加密方式与 openssl 不同

c - 这个宏到底在做什么?

c++ - PEM_read_X509 未读取整个证书

php - 用PHP加密的openssl需要用Ruby解密

c++ - 使用 iPad 上的所有可用内存

linux - 无法链接到特定的 OpenSSL 库 (Linux Mint 13)

ssl - 尝试使用客户端证书时解决 sslv3 警报握手失败

c - 告诉 C 内联函数但仍然可以调用调试器

c - 使用指向 pthread_create 的函数指针会导致段错误

c - 如何更改 tcsetattr() 的 Linux 中断定时器