Skip to content

Instantly share code, notes, and snippets.

@huhushow
Created December 9, 2015 08:25
Show Gist options
  • Save huhushow/03c3267a9ccaa394736c to your computer and use it in GitHub Desktop.
Save huhushow/03c3267a9ccaa394736c to your computer and use it in GitHub Desktop.
this is simple json validate and encrypted file generating python script
__author__ = 'huhushow'
import json, sys, getopt, base64, hashlib
from Crypto import Random
from Crypto.Cipher import AES
BS = 16
pad = lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS).encode()
unpad = lambda s: s[:-ord(s[len(s)-1:])]
def iv():
"""
The initialization vector to use for encryption or decryption.
It is ignored for MODE_ECB and MODE_CTR.
"""
return chr(0) * 16
class AESCipher(object):
"""
https://github.com/dlitz/pycrypto
"""
def __init__(self):
self.key = 'abcdefghijklmnopqrstuvwxyz1234567890'
#self.key = hashlib.sha256(key.encode()).digest()
def encrypt(self, message):
"""
It is assumed that you use Python 3.0+
, so plaintext's type must be str type(== unicode).
"""
message = message.encode()
raw = pad(message)
cipher = AES.new(self.key, AES.MODE_CBC, iv())
enc = cipher.encrypt(raw)
return base64.b64encode(enc).decode('utf-8')
def decrypt(self, enc):
enc = base64.b64decode(enc)
cipher = AES.new(self.key, AES.MODE_CBC, iv())
dec = cipher.decrypt(enc)
return unpad(dec).decode('utf-8')
def main():
try:
argv_short = "hi:o:"
argv_long = ["help","input_file=","output_file="]
opts, args = getopt.getopt(sys.argv[1:], argv_short, argv_long)
except getopt.GetoptError as err:
print(err)
usage()
sys.exit(2)
infile = None
indata = None
outfile_name = None
outfile = None
verbose = False
for o, a in opts:
if o == "-v":
verbose = True
elif o in ("-h", "--help"):
usage()
sys.exit()
elif o in ("-i", "--input_file"):
infile = open(a, 'r')
elif o in ("-o", "--output_file"):
outfile_name = a
else:
assert False, "unhandled option"
indata = infile.read()
infile.close()
try:
json.loads(indata)
except ValueError as err:
print(err)
sys.exit(2)
encypted = AESCipher().encrypt(indata)
outfile = open(outfile_name, 'w')
outfile.write(encypted)
outfile.close()
def usage():
usage = """
check input files json validate
and output encrypted file
-h --help Print this
-i --input_file input plain file name
-o --output_file output encrypted file name
"""
print(usage)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment