Sunday, June 12, 2016

encrypt and decrypt file using HMAC-SHA256

python script
--------------------------
from aead import AEAD
import sys
import re
import os
def usages():
 print "usage"
 print "cryptor.py enc/dec passw file"
if len(sys.argv) == 1:
 if os.path.isfile("~/.key") == False:
  print "pls generate 32 bytes key first"
  print "cryptor.py genkey"
  print "after you have .key, usage below"
  usages()
  sys.exit()
elif sys.argv[1]=="genkey":
 k= AEAD.generate_key()
 print k
 sys.exit()

key32 = open("~/.key", "rb")
key32r = key32.read()
cryptor = AEAD(key32r.strip())
key32.close()
if len(sys.argv)  != 4:
 usages()
else:
 opt = sys.argv[1]
 passw = sys.argv[2]
 filew = sys.argv[3]
 if opt == "enc":
  f = open(filew, "r")
  fr = f.read()
  ct = cryptor.encrypt(fr, passw)
  fe = open(filew+".enc","w")
  fe.write(ct)
  f.close()
  fe.close()
 elif opt == "dec":
  f = open(filew, "r")
  fr = f.read().strip()
  dc = cryptor.decrypt(fr, passw)
  filen = re.sub(r"\.enc$", "", filew)
  fe = open(filen+".dec","w")
  fe.write(dc)
  f.close()
  fe.close()
 else:
  usages()



save it as cryptor.py

usage:
1- generate 32 byte keys and save it to ~/.key
$ python cryptor.py genkey > ~/.key

2- encrypt file
$ python cryptor.py enc mypassword filename
then it will generate filename.enc, so you might want to delete the original file.

3- decrypt file
$ python cryptor.py dec mypassword filename.enc
 then it will generate filename.dec that is the decrypted version of filename.enc

*** note ***
you have to safe guard/ remember both   ~/.key and mypassword (replace with whatever string you like)

No comments:

Post a Comment