Skip to content

Instantly share code, notes, and snippets.

@ochinchina
Last active October 17, 2016 09:07
Show Gist options
  • Save ochinchina/b725a45991baac1a176e5dae370ba69d to your computer and use it in GitHub Desktop.
Save ochinchina/b725a45991baac1a176e5dae370ba69d to your computer and use it in GitHub Desktop.
AES encrypt/decrypt with openssl
#!/usr/bin/python
import array
import optparse
import os
import sys
import base64
def gen_random_key( fileName ):
os.system("openssl rand -base64 -out %s 16" % fileName )
def encrypt(inputFileName, keyFile, outputFileName):
with open(keyFile) as f:
b = base64.standard_b64decode( f.read() )
os.system("openssl enc -aes-128-ecb -a -in %s -K %s -out %s" % ( inputFileName, to_hex(b), outputFileName))
def to_hex( s ):
return ''.join(format(ord(x),"02x") for x in list(s) )
def decrypt( inputFileName, keyFile, outputFileName):
with open(keyFile) as f:
b = base64.standard_b64decode( f.read() )
os.system("openssl enc -d -aes-128-ecb -a -in %s -K %s -out %s" % ( inputFileName, to_hex(b), outputFileName))
def main():
usage="Usage: %prog [options] enc|dec|key-gen"
parser = optparse.OptionParser(usage)
parser.add_option( "-i", "--input", dest="inputFile", help="the name of to-be encrypted/descrypted file" )
parser.add_option( "-o", "--output", dest="outputFile", help="the name of encrypted/descrypted output file" )
parser.add_option( "-k", "--key", dest="keyFile", help="the key file for the encryption/descryption")
(options, args) = parser.parse_args()
if len( args ) <= 0:
parser.print_help()
elif args[0] == "key-gen":
if not options.outputFile:
print "please provide option --output"
else:
gen_random_key( options.outputFile )
elif args[0] == "enc":
if options.inputFile and options.keyFile and options.outputFile:
encrypt( options.inputFile, options.keyFile, options.outputFile )
else:
print "please provide following options:--input, --output and --key"
elif args[0] == "dec":
if options.inputFile and options.keyFile and options.outputFile:
decrypt( options.inputFile, options.keyFile, options.outputFile )
else:
print "please provide following options:--input, --output and --key"
else:
print "invalid command %s" % args[1]
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment