Advertisement
Peaser

minicryptlib

Aug 20th, 2015
433
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.51 KB | None | 0 0
  1. import random, os, re
  2.  
  3. class Pad(object):
  4.   def __init__(self):
  5.     super(Pad, self).__init__()
  6.  
  7.   def getRandomCypher(self, data):
  8.     """Generates random key and returns dict with key and cyphered data."""
  9.     key = os.urandom(len(data))
  10.     pairs = [[ord(a) for a in i] for i in zip(data, key)]
  11.     retval = [chr(i[0]^i[1]) for i in pairs]
  12.     return {"KEY":key, "CRYPT":str().join(retval)}
  13.  
  14.   def decypher(self, dict):
  15.     """Decyphers with a dict. Takes dict with keys 'KEY' and 'CRYPT'."""
  16.     if list(sorted(dict.keys())) != ["CRYPT","KEY"]:
  17.       raise SyntaxError, "Invalid argument dict"
  18.     pairs = [[ord(a) for a in i] for i in zip(dict["KEY"], dict["CRYPT"])]
  19.     retval = [chr(i[0]^i[1]) for i in pairs]
  20.     return str().join(retval)
  21.  
  22.   def cypherFile(self, path):
  23.     kp = self.getRandomCypher(open(path, "rb").read())
  24.     with open("outfile.bin", "wb") as of:
  25.       of.write(kp["CRYPT"])
  26.     with open("cryptkey.KEY", "wb") as ck:
  27.       ckdat = """START?{d}?END\nFILE_NAME:'{fn}'"""\
  28.       .format(d=kp["KEY"].encode("base64"), fn=os.path.split(path)[1])
  29.       ck.write(ckdat)
  30.  
  31.   def decypherFile(self, keyFile, cypherFile):
  32.     keyDat = open(keyFile, "rb").read()
  33.     cypherDat = open(cypherFile, "rb").read()
  34.     keyRead = re.findall("START\?(.+)\?END", keyDat, re.DOTALL)[0]
  35.     FName   = re.findall("FILE_NAME:'(.+)'", keyDat, re.DOTALL)[0]
  36.     Decyphered = self.decypher({"KEY":keyRead.decode("base64"), "CRYPT":cypherDat})
  37.     with open(FName, "wb") as file:
  38.       file.write(Decyphered)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement