smsign2.c 1.8 KB
Newer Older
1 2 3 4 5 6
/* S/MIME signing example: 2 signers. OpenSSL 0.9.9 only */
#include <openssl/pem.h>
#include <openssl/pkcs7.h>
#include <openssl/err.h>

int main(int argc, char **argv)
7 8 9 10 11 12
{
    BIO *in = NULL, *out = NULL, *tbio = NULL;
    X509 *scert = NULL, *scert2 = NULL;
    EVP_PKEY *skey = NULL, *skey2 = NULL;
    PKCS7 *p7 = NULL;
    int ret = 1;
13

14 15
    OpenSSL_add_all_algorithms();
    ERR_load_crypto_strings();
16

17
    tbio = BIO_new_file("signer.pem", "r");
18

19 20
    if (!tbio)
        goto err;
21

22
    scert = PEM_read_bio_X509(tbio, NULL, 0, NULL);
23

24
    BIO_reset(tbio);
25

26
    skey = PEM_read_bio_PrivateKey(tbio, NULL, 0, NULL);
27

28
    BIO_free(tbio);
29

30
    tbio = BIO_new_file("signer2.pem", "r");
31

32 33
    if (!tbio)
        goto err;
34

35
    scert2 = PEM_read_bio_X509(tbio, NULL, 0, NULL);
36

37
    BIO_reset(tbio);
38

39
    skey2 = PEM_read_bio_PrivateKey(tbio, NULL, 0, NULL);
40

41 42
    if (!scert2 || !skey2)
        goto err;
43

44
    in = BIO_new_file("sign.txt", "r");
45

46 47
    if (!in)
        goto err;
48

49
    p7 = PKCS7_sign(NULL, NULL, NULL, in, PKCS7_STREAM | PKCS7_PARTIAL);
50

51 52
    if (!p7)
        goto err;
53

54
    /* Add each signer in turn */
55

56 57
    if (!PKCS7_sign_add_signer(p7, scert, skey, NULL, 0))
        goto err;
58

59 60
    if (!PKCS7_sign_add_signer(p7, scert2, skey2, NULL, 0))
        goto err;
61

62 63 64
    out = BIO_new_file("smout.txt", "w");
    if (!out)
        goto err;
65

66
    /* NB: content included and finalized by SMIME_write_PKCS7 */
67

68 69
    if (!SMIME_write_PKCS7(out, p7, in, PKCS7_STREAM))
        goto err;
70

71
    ret = 0;
72

73 74 75 76 77
 err:
    if (ret) {
        fprintf(stderr, "Error Signing Data\n");
        ERR_print_errors_fp(stderr);
    }
R
Rich Salz 已提交
78
    PKCS7_free(p7);
79 80
    if (scert)
        X509_free(scert);
R
Rich Salz 已提交
81
    EVP_PKEY_free(skey);
82 83
    if (scert2)
        X509_free(scert2);
R
Rich Salz 已提交
84
    EVP_PKEY_free(skey2);
R
Rich Salz 已提交
85 86 87
    BIO_free(in);
    BIO_free(out);
    BIO_free(tbio);
88 89
    return ret;
}