diff options
author | Camil Staps | 2016-02-12 15:01:00 +0100 |
---|---|---|
committer | Camil Staps | 2016-02-12 15:01:00 +0100 |
commit | efd533331d6a7f0c51ef857af448a6c84c3084ed (patch) | |
tree | 7f28f4e20a215784f27643ad49029332204528b2 /Assignment3/des-demo.py | |
parent | Makefile (diff) |
Removed spaces in path
Diffstat (limited to 'Assignment3/des-demo.py')
-rwxr-xr-x | Assignment3/des-demo.py | 62 |
1 files changed, 62 insertions, 0 deletions
diff --git a/Assignment3/des-demo.py b/Assignment3/des-demo.py new file mode 100755 index 0000000..0a4954f --- /dev/null +++ b/Assignment3/des-demo.py @@ -0,0 +1,62 @@ +#!/usr/bin/python + +# Copyright (c) 2015 Camil Staps <info@camilstaps.nl> + +import sys, getopt, binascii +from Crypto.Cipher import DES + +def main(argv): + key = '' + plaintext = '' + ciphertext = '' + + # Parse arguments. Use -h for help. + try: + opts, args = getopt.getopt(argv, "hk:p:c:", ["key=","plaintext=","ciphertext="]) + except getopt.GetoptError: + usage() + sys.exit(2) + + for opt, arg in opts: + if opt == '-h': + usage() + sys.exit() + elif opt in ("-k", "--key"): + key = binascii.a2b_hex(arg) + elif opt in ("-p", "--plaintext"): + plaintext = binascii.a2b_hex(arg) + elif opt in ("-c", "--ciphertext"): + ciphertext = binascii.a2b_hex(arg) + + if key == '' or plaintext == '' and ciphertext == '': + usage() + sys.exit(2) + + # PyCrypto does the hard work + cipher = DES.new(key, DES.MODE_ECB) + + encryption = '' + decryption = '' + + if plaintext != '': + encryption = cipher.encrypt(plaintext) + if ciphertext != '': + decryption = cipher.decrypt(ciphertext) + + # When plaintext and ciphertext are provided, output if DES[k](p) = c. Otherwise, output the encryption / decryption. + if encryption != '' and decryption != '': + print encryption == ciphertext + elif encryption != '': + print binascii.b2a_hex(encryption) + elif decryption != '': + print binascii.b2a_hex(decryption) + +def usage(): + print 'Usage: des-demo.py -k <key> [-p <plaintext>] [-c <ciphertext>]' + print ' key : an 8-byte value entered as hexadecimal numbers' + print ' plaintext : an 8-byte value entered as hexadecimal numbers' + print ' ciphertext : an 8-byte value entered as hexadecimal numbers' + print 'At least one of plaintext and ciphertext should be provided. When both are provided, we check if DES[k](p) = c.' + +if __name__ == "__main__": + main(sys.argv[1:]) |