3-DES Encryption of XML Fields Using Python

Posted: September 3, 2012 in Uncategorized

Data, data, XML, data its everywhere easy to manipultate and transfer; difficult to secure and protect. This Python script will loop through an xml structure and encrypt the named fields. It uses the freely available pyDes and minidom libraries and if your needing to send sensitive data anywhere or simply store it. Its very easy to use. This script assumes an XML file with the sensitive fields in nodes called ‘Classified’.

#! /usr/bin/env python

#import modules
from pyDes import *
import xml.dom.minidom as dom1
from binascii import unhexlify as unhex
import os

#Define 24 Byte Encryption Key – I’ve put this in the code for simplicity you should never store it plainly in the code. Apply it each time and remove
EK = unhex(“150DDCB0AE7904FD764551DC433D26195D5B04793854FEFD”)

#Create dom and load with batch xml
doc = dom1.parse(‘yourfile.xml’)

#get document element
node = doc.documentElement

#get array of classified elements
clEls = doc.getElementsByTagName(“Classified”)

#loop through classified elements
for clEl in clEls:
#get array of the child text nodes containing the data
nodes = clEl.childNodes
#loop through child nodes encrypting and replacing
for node in nodes:
#Define 8 Byte IV
IV = os.urandom(8)

k = triple_des(EK, CBC, IV, pad=None, padmode=PAD_PKCS5)
encCl = k.encrypt(str(node.data))
encNode = doc.createTextNode(IV.encode(‘hex’)+encCl.encode(‘hex’))


#replace values
f = open(‘enc.xml’,’wb’)
xmlStr = doc.toxml(“utf-8”)
print xmlStr


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s