import binascii
import base64
import re
import sys
import binascii

class PEcrypt:
    """
    PEcrypt - very, very simple word key encryption system
              uses cyclic XOR between the keyword character
              bytes and the string to be encrypted/decrypted.
              Therefore, the same function and keyword will
              encrypt the string the first time and decrypt
              it if called on the encrypted string.
    """

    def __init__(self, aKey):
        """
        Initialise the class with the key that
        is used to encrypt/decrypt strings
        """
        self.key = aKey

        # CRC can be used to validate a key (very roughly)
        # if you store the CRC from a previous keyword
        # and then compare with a newly generated one and
        # they are the same then chances are the keyword
        # is correct - only a single byte so not that reliable
        self.crc = 0    
        for x in self.key:
            intX = ord(x)
            self.crc = self.crc ^ intX


    def Crypt(self, aString):
        """
        Encrypt/Decrypt the passed string object and return
        the encrypted string
        """
        kIdx = 0
        cryptStr = ""   # empty 'crypted string to be returned

        # loop through the string and XOR each byte with the keyword
        # to get the 'crypted byte. Add the 'crypted byte to the
        # 'crypted string
        for x in range(len(aString)):
            cryptStr = cryptStr + \
                       chr( ord(aString[x]) ^ ord(self.key[kIdx]))
            # use the mod operator - % - to cyclically loop through
            # the keyword
            kIdx = (kIdx + 1) % len(self.key)

        return cryptStr

rhead =  re.compile(".*<head>(?P<head>[^<]+)</head>.*")
rtitle = re.compile(".*<title>(?P<title>[^<]+)</title>.*")
rbody = re.compile(".*<body>(?P<body>[^<]+)</body>.*")
f = open(sys.argv[1], "r")
data = f.read()
f.close()

xor = sys.argv[2]
xor = binascii.unhexlify(xor)

pe = PEcrypt(xor)

m = rhead.match(data)
if m:
	head =  m.group(1)
	head = base64.b64decode(head)
	head = pe.Crypt(head)
	print head

m = rtitle.match(data)
if m:
	title =  m.group(1)
	title = base64.b64decode(title)
	title = pe.Crypt(title)
	print title

m = rbody.match(data)
if m:
	body =  m.group(1)
	body = base64.b64decode(body)
	body = pe.Crypt(body)
	f = open("%s.exe" % sys.argv[1], "w")
	f.write(body)
	f.close()
	print "Binary file %s saved" % ("%s.exe" % sys.argv[1])
	

