aboutsummaryrefslogtreecommitdiffstats
path: root/crypto/pkcs7/sign.c
blob: 9400fe30ba235208fd56d50a23c89b7eedca9a8f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
#include <stdio.h>
#include "bio.h"
#include "x509.h"
#include "pem.h"

main(argc,argv)
int argc;
char *argv[];
	{
	X509 *x509;
	EVP_PKEY *pkey;
	PKCS7 *p7;
	PKCS7 *p7_data;
	PKCS7_SIGNER_INFO *si;
	BIO *in;
	BIO *data,*p7bio;
	char buf[1024*4];
	int i,j;
	int nodetach=0;

	EVP_add_digest(EVP_md2());
	EVP_add_digest(EVP_md5());
	EVP_add_digest(EVP_sha1());
	EVP_add_digest(EVP_mdc2());

	data=BIO_new(BIO_s_file());
again:
	if (argc > 1)
		{
		if (strcmp(argv[1],"-nd") == 0)
			{
			nodetach=1;
			argv++; argc--;
			goto again;
			}
		if (!BIO_read_filename(data,argv[1]))
			goto err;
		}
	else
		BIO_set_fp(data,stdin,BIO_NOCLOSE);

	if ((in=BIO_new_file("server.pem","r")) == NULL) goto err;
	if ((x509=PEM_read_bio_X509(in,NULL,NULL)) == NULL) goto err;
	BIO_reset(in);
	if ((pkey=PEM_read_bio_PrivateKey(in,NULL,NULL)) == NULL) goto err;
	BIO_free(in);

	p7=PKCS7_new();
	PKCS7_set_type(p7,NID_pkcs7_signed);
	 
	if (PKCS7_add_signature(p7,x509,pkey,EVP_sha1()) == NULL) goto err;

	/* we may want to add more */
	PKCS7_add_certificate(p7,x509);

	/* Set the content of the signed to 'data' */
	PKCS7_content_new(p7,NID_pkcs7_data);

	if (!nodetach)
		PKCS7_set_detached(p7,1);

	if ((p7bio=PKCS7_dataInit(p7,NULL)) == NULL) goto err;

	for (;;)
		{
		i=BIO_read(data,buf,sizeof(buf));
		if (i <= 0) break;
		BIO_write(p7bio,buf,i);
		}

	if (!PKCS7_dataSign(p7,p7bio)) goto err;
	BIO_free(p7bio);

	PEM_write_PKCS7(stdout,p7);
	PKCS7_free(p7);

	exit(0);
err:
	ERR_load_crypto_strings();
	ERR_print_errors_fp(stderr);
	exit(1);
	}