Skip to content

Instantly share code, notes, and snippets.

@lad1337
Created March 26, 2015 17:19
Show Gist options
  • Save lad1337/55d3635dd7f79b84bc53 to your computer and use it in GitHub Desktop.
Save lad1337/55d3635dd7f79b84bc53 to your computer and use it in GitHub Desktop.
from Crypto.Cipher import AES
import base64
import re
from codecs import open
PADDING = '{'
BLOCK_SIZE = 32
pad = lambda s: s + (BLOCK_SIZE - len(s) % BLOCK_SIZE) * PADDING
encode_aes = lambda c, s: base64.b64encode(c.encrypt(pad(s)))
decode_aes = lambda c, e: c.decrypt(base64.b64decode(e)).rstrip(PADDING)
def encrypt(plain, password):
cipher = AES.new(pad(password))
return encode_aes(cipher, plain).encode("utf-8")
def decrypt(encoded, password):
cipher = AES.new(pad(password))
thing = decode_aes(cipher, encoded)
try:
return decode_aes(cipher, encoded).encode("utf-8")
except UnicodeDecodeError:
raise AssertionError("Looks like a wrong password")
def encrypt_lines(lines, password, plain=False):
pattern = re.compile(r"\{decrypted:(?P<value>.*?)\}")
new_lines = []
for line in lines:
match = pattern.search(line)
if match and match.group("value"):
if not plain:
print "encrypting"
encrypted = encrypt(match.group("value"), password)
line = pattern.sub(u"{encrypted:%s}" % encrypted, line)
else:
print "plaining and encrypted value"
line = pattern.sub(match.group("value"), line)
new_lines.append(line)
return new_lines
def decrypt_lines(lines, password, plain=False):
pattern = re.compile(r"\{encrypted:(?P<value>.*?)\}")
new_lines = []
for line in lines:
match = pattern.search(line)
if match and match.group("value"):
if not plain:
print "decrypting"
decrypted = decrypt(match.group("value"), password)
line = pattern.sub(u"{decrypted:%s}" % decrypted, line)
else:
print "plaining an decrypted value"
line = pattern.sub(match.group("value"), line)
new_lines.append(line)
return new_lines
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description='De/encript vars in a file')
parser.add_argument("function", choices=("decrypt", "encrypt", "plain"))
parser.add_argument("password")
parser.add_argument("file")
args = parser.parse_args()
plain = args.function == "plain"
print plain
with open(args.file, "r+", "utf-8") as f:
lines = f.readlines()
print "working on %s lines" % len(lines)
if args.function == "decrypt" or plain:
lines = decrypt_lines(lines, args.password, plain)
if args.function == "encrypt" or plain:
lines = encrypt_lines(lines, args.password, plain)
f.seek(0)
f.truncate()
f.writelines(lines)
@stvnwrgs
Copy link

line 57:

else:
            print "plaining an decrypted value"
            decrypted = decrypt(match.group("value"), password)
            line = pattern.sub(decrypted, line)
    new_lines.append(line)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment