Advertisement
Guest User

Untitled

a guest
Jan 16th, 2017
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.15 KB | None | 0 0
  1. #!/usr/bin/env python
  2.  
  3. # This script will encrypt/decrypt the AES ciphertext file.
  4.  
  5. import argparse
  6. from Crypto import Random
  7. from Crypto.Cipher import AES
  8. import base64
  9. import os.path
  10. import sys
  11.  
  12. parser = argparse.ArgumentParser(description='Encrypt/decrypt using ciphertext/plaintext and an encryption key with AES256.')
  13. parser.add_argument("-m", "--mode", help="Operation mode.", choices=["encrypt","decrypt"])
  14. parser.add_argument("-i", "--input", help="Specify the input ciphertext/plaintext filepath.")
  15. parser.add_argument("-k", "--key", help="Specify the encryption key filepath.")
  16. parser.add_argument("-o", "--output", help="Specify the output ciphertext/plaintext filepath.")
  17. parser.add_argument("-v", "--verbose", action="store_true", dest="verbose", help="Output the ciphertext/plaintext to stdout.")
  18. args = parser.parse_args()
  19.  
  20.  
  21. if args.input and os.path.isfile(args.input):
  22.   with open(args.input, 'r') as input_file:
  23.     input_rawtext = input_file.read()
  24. else:
  25.   print "--input option required and must be valid file."
  26.   sys.exit(1)
  27.  
  28. if args.key and os.path.isfile(args.key):
  29.   with open(args.key, 'r') as key_file:
  30.     key_rawtext = key_file.read()
  31. else:
  32.   print "--key option required and must be valid file."
  33.   sys.exit(1)
  34.  
  35. if args.mode == 'encrypt':
  36.   key_text = base64.b64decode(key_rawtext)
  37.   plain_text = input_rawtext
  38.   cipher = AES.new(key_text, AES.MODE_ECB)
  39.   # Insert padding if necessary to ciphertext (must be a multiple of 16 bytes)
  40.   length = 16 - (len(plain_text) % 16)
  41.   plain_text += chr(length)*length
  42.   cipher_text = base64.b64encode(cipher.encrypt(plain_text))
  43.   if args.output:
  44.     with open(args.output, 'w') as output_file:
  45.       output_file.truncate
  46.       output_file.write(cipher_text)
  47.   if args.verbose:
  48.     print cipher_text
  49.  
  50. if args.mode == 'decrypt':
  51.   key_text = base64.b64decode(key_rawtext)
  52.   cipher_text = base64.b64decode(input_rawtext)
  53.   cipher = AES.new(key_text, AES.MODE_ECB)
  54.   plain_text = cipher.decrypt(cipher_text)
  55.   if args.output:
  56.     with open(args.output, 'w') as output_file:
  57.       output_file.truncate
  58.       output_file.write(plain_text)
  59.   if args.verbose:
  60.     print plain_text
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement