#!/usr/bin/python # Copyright 2000 Enhanced Software Technologies Inc. # # Licensed as Open Source software under a BSD-style license. # Read file 'LICENSE.ocotillo' for more information. # This uses the 'twofish' module to encrypt and decrypt a file. # It operates in one of two ways: # # keyfile mode: -- if the '-k=' option is passed on cmd line, the next # option is the keyfile. It contains a 128 to 256 bit key in binary. Unless # -i or -o options are provided, all i/o is to stdin/stdout. Use 'randkey' # program to create a random key. # # immediate mode -- you must provide "-i=" argument. The output # file will be "inputfile.enc", unless you provide a "-o=" # argument. You will be prompted for a passphrase. This passphrase will then # be md5-hashed. The resulting 128-bit string is then passed to the # encryption algorithm as its key. # note that we're a wrapper around twofish.py. We should only be called # from the command line. ONLY_CALL_FROM_COMMAND_LINE="cryptfile.ONLY_CALL_FROM_COMMAND_LINE" import sys import twofish import md5 import getpass cipher=None inputfilename=None outputfilename=None keyfilename=None def set_key_from_file(cipher,keyfilename): fh=open(keyfilename,"r") key=fh.read(32) # read a max of 256 chars! if len(key) > 24 and len(key) < 32: key=key[0:24] elif len(key) > 16 and len(key) < 24: key=key[0:16] elif len(key) < 16: sys.stderr.write("Invalid Key Length in key file %s\n" % keyfilename) sys.exit(1) return cipher.setkey(key) return def prompt_for_key(cipher): m=md5.new() line = getpass.getpass("Passphrase:> ") m.update(line) key=m.digest() cipher.setkey(key) return def execute_encryption(): global inputfilename global outputfilename global keyfilename global cipher if len(sys.argv) < 2: sys.stderr.write("Error: Need arguments to tell me where my key is.\n") sys.exit(1) return shortlist=sys.argv[1:] for s in shortlist: cmd=s[0:2] if cmd =="-i": inputfilename=s[3:] elif cmd == "-o": outputfilename=s[3:] elif cmd=="-k": keyfilename=s[3:] pass continue # now to check to see if we got enough parameters: if (not keyfilename) and (not inputfilename): sys.stderr.write("Error: must specify either keyfile or input file.\n") sys.exit(1) return cipher=twofish.twofish() # okay, if we have a keyfilename, do that, else prompt for key: if keyfilename: set_key_from_file(cipher,keyfilename) else: prompt_for_key(cipher) pass if inputfilename: inputfile=open(inputfilename,"r") if not outputfilename: if inputfilename[-4:]==".tfe": outputfilename=inputfilename[:-4] #strip it off! else: outputfilename=inputfilename+".tfd" pass pass else: inputfile=sys.stdin pass if outputfilename: outputfile=open(outputfilename,"w") else: outputfile=sys.stdout pass cipher.decrypt_cfb_file(inputfile,outputfile) return if __name__ == '__main__': execute_encryption() else: raise ONLY_CALL_FROM_COMMAND_LINE,"Use twofish.py directly"