from Crypto.Cipher import DES
import binascii
import sys
import subprocess

def process_userid(s):
    while len(s) % 8:
        s.append(0x40)
 
def process_key(s):
    # replace missing characters in key by EBCDIC spaces (0x40) 
    while len(s) % 8 or len(s) == 0:
        s.append(0x40)
    for i in range(0, 8):
        s[i] = ((s[i] ^ 0x55) << 1) & 0xff
 
if __name__ == "__main__":
    if len(sys.argv) < 2:
        print >> sys.stderr, "Usage: %s <dictionary file>" % sys.argv[0]
        sys.exit(-1)

    with open(sys.argv[1]) as f:
        for line in f.readlines():
            line = line.rstrip()
            if line.startswith('#'):
                continue
            userid_ascii = "AAAAAAAA"
            pass_ascii = line
            # truncate and padding stuff
            userid_ascii = userid_ascii[0:8]
            pass_ascii = pass_ascii[0:8]
            userid_ebcdic = userid_ascii.decode('ascii').encode('EBCDIC-CP-BE')
            pass_ebcdic = pass_ascii.decode('ascii').encode('EBCDIC-CP-BE')
            ues = bytearray(userid_ebcdic)
            process_userid(ues)
            pes = bytearray(pass_ebcdic)
            process_key(pes)
            pesj = str(pes)
            uesj = str(ues)
            des = DES.new(pesj, DES.MODE_CBC)
            cipher = des.encrypt(uesj)
            out = binascii.hexlify(cipher)
            print "user-%s:$racf$*%s*%s" % (line, userid_ascii, out)


