#!/usr/bin/python

import sys, getopt, base64
From struct import pack, unpack

fixedkey = [int("0x50",0), int("0xF7",0), int("0x82",0), int("0x69",0), int("0xEA",0), int("0x2D",0), int("0xDD",0), int("0x2D",0), int("0x6A",0), int("0xB4",0), int("0x33",0), int("0x8F",0), int("0xD5",0), int("0xC7",0), int("0x90",0), int("0x9C",0), int("0x22",0), int("0x95",0), int("0x61",0), int("0xE5",0), int("0x65",0), int("0xF6",0), int("0xB0",0), int("0x4B",0), int("0x94",0), int("0x47",0), int("0xB0",0), int("0xBD",0), int("0x73",0), int("0x58",0), int("0x56",0), int("0x87",0), int("0x79",0), int("0x7B",0), int("0xE6",0), int("0xB0",0), int("0xD2",0), int("0x20",0), int("0x28",0), int("0xE1",0)]

def wpkg_crypt (passwd):
    buf = []
    length = len(passwd)
    idx = 0

    for i in range (length):
        buf.append(ord(passwd[i])^fixedkey[idx])
        idx = idx+1
        if (idx > len(fixedkey) -1):
            idx = 0

    return base64.b64encode(''.join([pack("B", c) for c in buf]))

def wpkg_decrypt (crypt):
    buf = []
    length = len(fixedkey)
    idx = 0

    unpacked = [unpack("B", c) for c in base64.b64decode(crypt)]

    for i in range (len(unpacked)):
        buf.append( chr( unpacked[i][0]^fixedkey[i] ) )
        idx = idx+1
        if (idx > length-1):
            idx = 0
    return ''.join(buf)

def usage ():
    print sys.argv[0] + " [option]"
    print "\t-h|--help\tThis help message"
    print "\t-p|--password\tPassword to encrypt"
    print "\t-c|--crypted\tText to decrypt"

try:
    opts, args = getopt.getopt(sys.argv[1:], "hp:c:", ["help", "password=", "crypted="])
except getopt.GetoptError, err:
    # print help information and exit:
    print str(err)
    usage()
    sys.exit(2)

for o, a in opts:
    if o in ("-h", "--help"):
        usage()
        sys.exit()
    elif o in ("-p", "--password"):
        print "Crypted: " + wpkg_crypt(a)
        sys.exit()
    elif o in ("-c", "--crypted"):
        print "Clear: " + wpkg_decrypt(a)
        sys.exit()
    else:
        assert False, "unhandled option"

usage()
