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