Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import sys, getpass, os
- from hashlib import md5
- from Crypto.Cipher import AES
- from Crypto import Random
- if os.name == "nt":
- warning = """Usage:python pyaes.py <IN_file> <OUT_file> <mode>
- modes:
- encrypt
- decrypt
- *You will be prompted for a password."""
- try:
- inf = sys.argv[1]
- outf = sys.argv[2]
- mode = sys.argv[3]
- if mode not in ("encrypt","decrypt"):raise StandardError
- except:
- print "Something went wrong!\n\n",warning
- sys.exit(0)
- def derive_key_and_iv(password, salt, key_length, iv_length):
- d = d_i = ''
- while len(d) < key_length + iv_length:
- d_i = md5(d_i + password + salt).digest()
- d += d_i
- return d[:key_length], d[key_length:key_length+iv_length]
- def encrypt(in_file, out_file, password, key_length=32):
- bs = AES.block_size
- salt = Random.new().read(bs - len('Salted__'))
- key, iv = derive_key_and_iv(password, salt, key_length, bs)
- cipher = AES.new(key, AES.MODE_CBC, iv)
- out_file.write('Salted__' + salt)
- finished = False
- while not finished:
- chunk = in_file.read(1024 * bs)
- if len(chunk) == 0 or len(chunk) % bs != 0:
- padding_length = (bs - len(chunk) % bs) or bs
- chunk += padding_length * chr(padding_length)
- finished = True
- out_file.write(cipher.encrypt(chunk))
- def decrypt(in_file, out_file, password, key_length=32):
- bs = AES.block_size
- salt = in_file.read(bs)[len('Salted__'):]
- key, iv = derive_key_and_iv(password, salt, key_length, bs)
- cipher = AES.new(key, AES.MODE_CBC, iv)
- next_chunk = ''
- finished = False
- while not finished:
- chunk, next_chunk = next_chunk, cipher.decrypt(in_file.read(1024 * bs))
- if len(next_chunk) == 0:
- padding_length = ord(chunk[-1])
- chunk = chunk[:-padding_length]
- finished = True
- out_file.write(chunk)
- if mode == "encrypt":
- password = ""
- def verify():
- global password
- vpw1 = getpass.getpass("Type a Password:")
- vpw2 = getpass.getpass("Retype Password:")
- if vpw1 != vpw2:
- print "\nPasswords do not patch.\n"
- verify()
- else:
- password += vpw2
- verify()
- with open(inf, 'rb') as in_file, open(outf, 'wb') as out_file:
- encrypt(in_file, out_file, password)
- if mode == "decrypt":
- password = getpass.getpass()
- with open(inf, 'rb') as in_file, open(outf, 'wb') as out_file:
- decrypt(in_file, out_file, password)
- else:exec('7261697365204f534572726f722c20224e6f742057696e646f77732c206b696c6c20796f757273656c662e22'.decode('hex'))#cheeky
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement