source: TI12-security/trunk/NDGSecurity/python/Tests/xmlsec/encrypt2.py @ 7080

Subversion URL: http://proj.badc.rl.ac.uk/svn/ndg/TI12-security/trunk/NDGSecurity/python/Tests/xmlsec/encrypt2.py@7080
Revision 7080, 4.7 KB checked in by pjkersha, 9 years ago (diff)
  • Property svn:executable set to *
  • Property svn:keywords set to Id
Line 
1#!/usr/bin/env python
2#
3# $Id$
4#
5# PyXMLSec example: Encrypting XML file with a dynamicaly created template.
6#
7# Encrypts XML file using a dynamicaly created template file and a DES key
8# from a binary file
9#
10# Usage:
11#       ./encrypt2.py <xml-doc> <des-key-file>
12#
13# Example:
14#       ./encrypt2.py encrypt2-doc.xml deskey.bin > encrypt2-res.xml
15#
16# The result could be decrypted with decrypt1 example:
17#       ./decrypt1.py encrypt2-res.xml deskey.bin
18#
19# This is free software; see COPYING file in the source
20# distribution for preciese wording.
21#
22# Copyright (C) 2003-2004 Valery Febvre <vfebvre@easter-eggs.com>
23#
24
25import os, sys
26sys.path.insert(0, '../')
27
28import libxml2
29import xmlsec
30
31def main():
32    assert(sys.argv)
33    if len(sys.argv) < 3:
34        print "Error: wrong number of arguments."
35        print "Usage: %s <xml-tmpl> <key-file>" % sys.argv[0]
36        return sys.exit(1)
37   
38    # Init libxml library
39    libxml2.initParser()
40    libxml2.substituteEntitiesDefault(1)
41
42    # Init xmlsec library
43    if xmlsec.init() < 0:
44        print "Error: xmlsec initialization failed."
45        return sys.exit(-1)
46   
47    # Check loaded library version
48    if xmlsec.checkVersion() != 1:
49        print "Error: loaded xmlsec library version is not compatible.\n"
50        sys.exit(-1)
51
52    # Init crypto library
53    if xmlsec.cryptoAppInit(None) < 0:
54        print "Error: crypto initialization failed."
55   
56    # Init xmlsec-crypto library
57    if xmlsec.cryptoInit() < 0:
58        print "Error: xmlsec-crypto initialization failed."
59
60    res = encrypt_file(sys.argv[1], sys.argv[2])
61
62    # Shutdown xmlsec-crypto library
63    xmlsec.cryptoShutdown()
64
65    # Shutdown crypto library
66    xmlsec.cryptoAppShutdown()
67
68    # Shutdown xmlsec library
69    xmlsec.shutdown()
70
71    # Shutdown LibXML2
72    libxml2.cleanupParser()
73
74    sys.exit(res)
75
76
77# Encrypts xml_file using a dynamicaly created template and DES key from
78# key_file.
79# Returns 0 on success or a negative value if an error occurs.
80def encrypt_file(xml_file, key_file):
81    assert(xml_file)
82    assert(key_file)
83
84    # Load template
85    if not check_filename(xml_file):
86        return -1
87    doc = libxml2.parseFile(xml_file)
88    if doc is None or doc.getRootElement() is None:
89        print "Error: unable to parse file \"%s\"" % xml_file
90        return cleanup(doc)
91
92    # Create encryption template to encrypt XML file and replace
93    # its content with encryption result
94    enc_data_node = xmlsec.TmplEncData(doc, xmlsec.transformDes3CbcId(),
95                                       None, xmlsec.TypeEncElement, None, None)
96    if enc_data_node is None:
97        print "Error: failed to create encryption template"
98        cleanup(doc)
99
100    # We want to put encrypted data in the <enc:CipherValue/> node
101    if enc_data_node.ensureCipherValue() is None:
102        print "Error: failed to add CipherValue node"
103        cleanup(doc, enc_data_node)
104
105    # add <dsig:KeyInfo/> and <dsig:KeyName/> nodes to put key name in the
106    # signed document
107    key_info_node = enc_data_node.ensureKeyInfo(None)
108    if key_info_node is None:
109        print "Error: failed to add key info"
110        cleanup(doc, enc_data_node)
111
112    if key_info_node.addKeyName(None) is None:
113        print "Error: failed to add key name"
114        cleanup(doc, enc_data_node)
115
116    # Create encryption context, we don't need keys manager in this example
117    enc_ctx = xmlsec.EncCtx(None)
118    if enc_ctx is None:
119        print "Error: failed to create encryption context"
120        cleanup(doc, enc_data_node)
121
122    # Load DES key, assuming that there is not password
123    if not check_filename(key_file):
124        cleanup(doc, enc_data_node, enc_ctx)
125    key = xmlsec.keyReadBinaryFile(xmlsec.keyDataDesId(), key_file)
126    if key is None:
127        print "Error failed to load DES key from binary file \"%s\"" % key_file
128        return cleanup(doc, enc_data_node, enc_ctx)
129
130    # Set key name to the file name, this is just an example!
131    if key.setName(key_file) < 0:
132        print "Error: failed to set key name for key from \"%s\"" % key_file
133        return cleanup(doc, enc_data_node, enc_ctx)
134
135    enc_ctx.encKey = key
136
137    # Encrypt the data
138    if enc_ctx.xmlEncrypt(enc_data_node, doc.getRootElement()) < 0:
139        print "Error: encryption failed"
140        return cleanup(doc, enc_data_node, enc_ctx)
141
142    doc.dump("-")
143
144    # Success
145    return cleanup(doc, None, enc_ctx, 1)
146
147
148def cleanup(doc=None, enc_data_node=None, enc_ctx=None, res=-1):
149    if enc_ctx is not None:
150        enc_ctx.destroy()
151    if enc_data_node is not None:
152        enc_data_node.freeNode()
153    if doc is not None:
154        doc.freeDoc()
155    return res
156
157
158def check_filename(filename):
159    if os.access(filename, os.R_OK):
160        return 1
161    else:
162        print "Error: XML file \"%s\" not found OR no read access" % filename
163        return 0
164
165
166if __name__ == "__main__":
167    main()
168
Note: See TracBrowser for help on using the repository browser.