summaryrefslogtreecommitdiff
path: root/Assignment 3/des-demo.py
blob: 0a4954f81f385f5104d1a4767e6a9801783fa6ca (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
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:])