Git init
[external/xmlsec1.git] / examples / sign3.c
1 /** 
2  * XML Security Library example: Signing a file with a dynamicaly created template and an X509 certificate.
3  * 
4  * Signs a file using a dynamicaly created template, key from PEM file and
5  * an X509 certificate. The signature has one reference with one enveloped 
6  * transform to sign the whole document except the <dsig:Signature/> node 
7  * itself. The key certificate is written in the <dsig:X509Data/> node.
8  * 
9  * This example was developed and tested with OpenSSL crypto library. The 
10  * certificates management policies for another crypto library may break it.
11  * 
12  * Usage: 
13  *      sign3 <xml-doc> <pem-key> 
14  *
15  * Example:
16  *      ./sign3 sign3-doc.xml rsakey.pem rsacert.pem > sign3-res.xml
17  *
18  * The result signature could be validated using verify3 example:
19  *      ./verify3 sign3-res.xml rootcert.pem
20  *
21  * This is free software; see Copyright file in the source
22  * distribution for preciese wording.
23  * 
24  * Copyright (C) 2002-2003 Aleksey Sanin <aleksey@aleksey.com>
25  */
26 #include <stdlib.h>
27 #include <string.h>
28 #include <assert.h>
29
30 #include <libxml/tree.h>
31 #include <libxml/xmlmemory.h>
32 #include <libxml/parser.h>
33
34 #ifndef XMLSEC_NO_XSLT
35 #include <libxslt/xslt.h>
36 #endif /* XMLSEC_NO_XSLT */
37
38 #include <xmlsec/xmlsec.h>
39 #include <xmlsec/xmltree.h>
40 #include <xmlsec/xmldsig.h>
41 #include <xmlsec/templates.h>
42 #include <xmlsec/crypto.h>
43
44 int sign_file(const char* xml_file, const char* key_file, const char* cert_file);
45
46 int 
47 main(int argc, char **argv) {
48     assert(argv);
49
50     if(argc != 4) {
51         fprintf(stderr, "Error: wrong number of arguments.\n");
52         fprintf(stderr, "Usage: %s <xml-file> <key-file> <cert-file>\n", argv[0]);
53         return(1);
54     }
55
56     /* Init libxml and libxslt libraries */
57     xmlInitParser();
58     LIBXML_TEST_VERSION
59     xmlLoadExtDtdDefaultValue = XML_DETECT_IDS | XML_COMPLETE_ATTRS;
60     xmlSubstituteEntitiesDefault(1);
61 #ifndef XMLSEC_NO_XSLT
62     xmlIndentTreeOutput = 1; 
63 #endif /* XMLSEC_NO_XSLT */
64                 
65     /* Init xmlsec library */
66     if(xmlSecInit() < 0) {
67         fprintf(stderr, "Error: xmlsec initialization failed.\n");
68         return(-1);
69     }
70
71     /* Check loaded library version */
72     if(xmlSecCheckVersion() != 1) {
73         fprintf(stderr, "Error: loaded xmlsec library version is not compatible.\n");
74         return(-1);
75     }
76
77     /* Load default crypto engine if we are supporting dynamic
78      * loading for xmlsec-crypto libraries. Use the crypto library
79      * name ("openssl", "nss", etc.) to load corresponding 
80      * xmlsec-crypto library.
81      */
82 #ifdef XMLSEC_CRYPTO_DYNAMIC_LOADING
83     if(xmlSecCryptoDLLoadLibrary(BAD_CAST XMLSEC_CRYPTO) < 0) {
84         fprintf(stderr, "Error: unable to load default xmlsec-crypto library. Make sure\n"
85                         "that you have it installed and check shared libraries path\n"
86                         "(LD_LIBRARY_PATH) envornment variable.\n");
87         return(-1);     
88     }
89 #endif /* XMLSEC_CRYPTO_DYNAMIC_LOADING */
90
91     /* Init crypto library */
92     if(xmlSecCryptoAppInit(NULL) < 0) {
93         fprintf(stderr, "Error: crypto initialization failed.\n");
94         return(-1);
95     }
96
97     /* Init xmlsec-crypto library */
98     if(xmlSecCryptoInit() < 0) {
99         fprintf(stderr, "Error: xmlsec-crypto initialization failed.\n");
100         return(-1);
101     }
102
103     if(sign_file(argv[1], argv[2], argv[3]) < 0) {
104         return(-1);
105     }    
106     
107     /* Shutdown xmlsec-crypto library */
108     xmlSecCryptoShutdown();
109     
110     /* Shutdown crypto library */
111     xmlSecCryptoAppShutdown();
112     
113     /* Shutdown xmlsec library */
114     xmlSecShutdown();
115
116     /* Shutdown libxslt/libxml */
117 #ifndef XMLSEC_NO_XSLT
118     xsltCleanupGlobals();            
119 #endif /* XMLSEC_NO_XSLT */
120     xmlCleanupParser();
121     
122     return(0);
123 }
124
125 /** 
126  * sign_file:
127  * @xml_file:           the XML file name.
128  * @key_file:           the PEM private key file name.
129  * @cert_file:          the x509 certificate PEM file.
130  *
131  * Signs the @xml_file using private key from @key_file and dynamicaly
132  * created enveloped signature template. The certificate from @cert_file
133  * is placed in the <dsig:X509Data/> node.
134  *
135  * Returns 0 on success or a negative value if an error occurs.
136  */
137 int 
138 sign_file(const char* xml_file, const char* key_file, const char* cert_file) {
139     xmlDocPtr doc = NULL;
140     xmlNodePtr signNode = NULL;
141     xmlNodePtr refNode = NULL;
142     xmlNodePtr keyInfoNode = NULL;
143     xmlSecDSigCtxPtr dsigCtx = NULL;
144     int res = -1;
145     
146     assert(xml_file);
147     assert(key_file);
148     assert(cert_file);
149
150     /* load doc file */
151     doc = xmlParseFile(xml_file);
152     if ((doc == NULL) || (xmlDocGetRootElement(doc) == NULL)){
153         fprintf(stderr, "Error: unable to parse file \"%s\"\n", xml_file);
154         goto done;      
155     }
156     
157     /* create signature template for RSA-SHA1 enveloped signature */
158     signNode = xmlSecTmplSignatureCreate(doc, xmlSecTransformExclC14NId,
159                                          xmlSecTransformRsaSha1Id, NULL);
160     if(signNode == NULL) {
161         fprintf(stderr, "Error: failed to create signature template\n");
162         goto done;              
163     }
164
165     /* add <dsig:Signature/> node to the doc */
166     xmlAddChild(xmlDocGetRootElement(doc), signNode);
167     
168     /* add reference */
169     refNode = xmlSecTmplSignatureAddReference(signNode, xmlSecTransformSha1Id,
170                                         NULL, NULL, NULL);
171     if(refNode == NULL) {
172         fprintf(stderr, "Error: failed to add reference to signature template\n");
173         goto done;              
174     }
175
176     /* add enveloped transform */
177     if(xmlSecTmplReferenceAddTransform(refNode, xmlSecTransformEnvelopedId) == NULL) {
178         fprintf(stderr, "Error: failed to add enveloped transform to reference\n");
179         goto done;              
180     }
181     
182     /* add <dsig:KeyInfo/> and <dsig:X509Data/> */
183     keyInfoNode = xmlSecTmplSignatureEnsureKeyInfo(signNode, NULL);
184     if(keyInfoNode == NULL) {
185         fprintf(stderr, "Error: failed to add key info\n");
186         goto done;              
187     }
188     
189     if(xmlSecTmplKeyInfoAddX509Data(keyInfoNode) == NULL) {
190         fprintf(stderr, "Error: failed to add X509Data node\n");
191         goto done;              
192     }
193
194     /* create signature context, we don't need keys manager in this example */
195     dsigCtx = xmlSecDSigCtxCreate(NULL);
196     if(dsigCtx == NULL) {
197         fprintf(stderr,"Error: failed to create signature context\n");
198         goto done;
199     }
200
201     /* load private key, assuming that there is not password */
202     dsigCtx->signKey = xmlSecCryptoAppKeyLoad(key_file, xmlSecKeyDataFormatPem, NULL, NULL, NULL);
203     if(dsigCtx->signKey == NULL) {
204         fprintf(stderr,"Error: failed to load private pem key from \"%s\"\n", key_file);
205         goto done;
206     }
207     
208     /* load certificate and add to the key */
209     if(xmlSecCryptoAppKeyCertLoad(dsigCtx->signKey, cert_file, xmlSecKeyDataFormatPem) < 0) {
210         fprintf(stderr,"Error: failed to load pem certificate \"%s\"\n", cert_file);
211         goto done;
212     }
213
214     /* set key name to the file name, this is just an example! */
215     if(xmlSecKeySetName(dsigCtx->signKey, key_file) < 0) {
216         fprintf(stderr,"Error: failed to set key name for key from \"%s\"\n", key_file);
217         goto done;
218     }
219
220     /* sign the template */
221     if(xmlSecDSigCtxSign(dsigCtx, signNode) < 0) {
222         fprintf(stderr,"Error: signature failed\n");
223         goto done;
224     }
225         
226     /* print signed document to stdout */
227     xmlDocDump(stdout, doc);
228     
229     /* success */
230     res = 0;
231
232 done:    
233     /* cleanup */
234     if(dsigCtx != NULL) {
235         xmlSecDSigCtxDestroy(dsigCtx);
236     }
237     
238     if(doc != NULL) {
239         xmlFreeDoc(doc); 
240     }
241     return(res);
242 }
243