source: TI12-security/trunk/python/Tests/xmlsec/decrypt2.py @ 1415

Subversion URL: http://proj.badc.rl.ac.uk/svn/ndg/TI12-security/trunk/python/Tests/xmlsec/decrypt2.py@1415
Revision 1415, 5.1 KB checked in by pjkersha, 13 years ago (diff)

Include XML Security test programs.

  • Property svn:executable set to *
Line 
1#!/usr/bin/env python
2#
3# $Id: decrypt2.py,v 1.4 2004/01/25 00:31:12 valos Exp $
4#
5# PyXMLSec example: Decrypting an encrypted file using keys manager.
6#
7# Decrypts encrypted XML file using keys manager and a list of
8# DES key from a binary file
9#
10# Usage:
11#       decrypt2.py <xml-enc> <des-key-file1> [<des-key-file2> [...]]
12#
13# Example:
14#       ./decrypt2.py encrypt1-res.xml deskey.bin
15#       ./decrypt2.py encrypt2-res.xml deskey.bin
16#
17# This is free software; see COPYING file in the source
18# distribution for preciese wording.
19#
20# Copyright (C) 2003-2004 Valery Febvre <vfebvre@easter-eggs.com>
21#
22
23import os, sys
24sys.path.insert(0, '../')
25
26import libxml2
27import xmlsec
28
29def main():
30    assert(sys.argv)
31    if len(sys.argv) < 3:
32        print "Error: wrong number of arguments."
33        print "Usage: %s <xml-tmpl> <des-key-file>" % sys.argv[0]
34        return sys.exit(1)
35   
36    # Init libxml library
37    libxml2.initParser()
38    libxml2.substituteEntitiesDefault(1)
39
40    # Init xmlsec library
41    if xmlsec.init() < 0:
42        print "Error: xmlsec initialization failed."
43        return sys.exit(-1)
44   
45    # Check loaded library version
46    if xmlsec.checkVersion() != 1:
47        print "Error: loaded xmlsec library version is not compatible.\n"
48        sys.exit(-1)
49
50    # Init crypto library
51    if xmlsec.cryptoAppInit(None) < 0:
52        print "Error: crypto initialization failed."
53   
54    # Init xmlsec-crypto library
55    if xmlsec.cryptoInit() < 0:
56        print "Error: xmlsec-crypto initialization failed."
57
58    # Create keys manager and load keys
59    mngr = load_des_keys(sys.argv[2:], len(sys.argv) - 2)
60
61    if mngr is not None:
62        res = decrypt_file(mngr, sys.argv[1])
63        # Destroy keys manager
64        mngr.destroy()
65
66    # Shutdown xmlsec-crypto library
67    xmlsec.cryptoShutdown()
68
69    # Shutdown crypto library
70    xmlsec.cryptoAppShutdown()
71
72    # Shutdown xmlsec library
73    xmlsec.shutdown()
74
75    # Shutdown LibXML2
76    libxml2.cleanupParser()
77
78    sys.exit(res)
79
80
81# Creates simple keys manager and load DES keys from files in it.
82# The caller is responsible for destroying returned keys manager using
83# destroy.
84#
85# Returns the newly created keys manager or None if an error occurs.
86def load_des_keys(files, files_size):
87    assert(files)
88    assert(files_size > 0)
89
90    # Create and initialize keys manager, we use a simple list based
91    # keys manager, implement your own KeysStore klass if you need
92    # something more sophisticated
93    mngr = xmlsec.KeysMngr()
94    if mngr is None:
95        print "Error: failed to create keys manager."
96        return None
97    if xmlsec.cryptoAppDefaultKeysMngrInit(mngr) < 0:
98        print "Error: failed to initialize keys manager."
99        mngr.destroy()
100        return None
101    for file in files:
102        if not check_filename(file):
103            mngr.destroy()
104            return None
105        # Load DES key
106        key = xmlsec.keyReadBinaryFile(xmlsec.keyDataDesId(), file)
107        if key is None:
108            print "Error: failed to load des key from binary file \"%s\"" % file
109            mngr.destroy()
110            return None
111        # Add key to keys manager, from now on keys manager is responsible
112        # for destroying key
113        if xmlsec.cryptoAppDefaultKeysMngrAdoptKey(mngr, key) < 0:
114            print "Error: failed to add key from \"%s\" to keys manager" % file
115            key.destroy()
116            mngr.destroy()
117            return None
118    return mngr
119
120
121# Decrypts the XML file enc_file using DES key files in mngr and
122# prints results to stdout.
123#
124# Returns 0 on success or a negative value if an error occurs.
125def decrypt_file(mngr, enc_file):
126    assert(mngr)
127    assert(enc_file)
128
129    # Load template
130    if not check_filename(enc_file):
131        return -1
132    doc = libxml2.parseFile(enc_file)
133    if doc is None or doc.getRootElement() is None:
134        print "Error: unable to parse file \"%s\"" % enc_file
135        return cleanup(doc)
136   
137    # Find start node
138    node = xmlsec.findNode(doc.getRootElement(), xmlsec.NodeEncryptedData,
139                           xmlsec.EncNs)
140    if node is None:
141        print "Error: start node not found in \"%s\"" % tmpl_file
142        return cleanup(doc)
143
144    # Create encryption context
145    enc_ctx = xmlsec.EncCtx(mngr)
146    if enc_ctx is None:
147        print "Error: failed to create encryption context"
148        return cleanup(doc)
149
150    # Decrypt the data
151    if enc_ctx.decrypt(node) < 0 or enc_ctx.result is None:
152        print "Error: decryption failed"
153        return cleanup(doc, enc_ctx)
154
155    # Print decrypted data to stdout
156    if enc_ctx.resultReplaced != 0:
157        print "Decrypted XML data:"
158        doc.dump("-")
159    else:
160        print "Decrypted binary data (%d bytes):" % enc_ctx.result.getSize()
161        print enc_ctx.result.getData()
162
163    # Success
164    return cleanup(doc, enc_ctx, 1)
165
166
167def cleanup(doc=None, enc_ctx=None, res=-1):
168    if enc_ctx is not None:
169        enc_ctx.destroy()
170    if doc is not None:
171        doc.freeDoc()
172    return res
173
174
175def check_filename(filename):
176    if os.access(filename, os.R_OK):
177        return 1
178    else:
179        print "Error: XML file \"%s\" not found OR no read access" % filename
180        return 0
181
182
183if __name__ == "__main__":
184    main()
Note: See TracBrowser for help on using the repository browser.