Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Private note generation
#!/usr/bin/python
import os, random, struct
from Crypto.Cipher import AES
from Crypto import Random
import md5, sys, getpass, filecmp, json, shutil
from datetime import datetime
import time
class PrivateNote:
def __init__(self, fileName):
self.fileName = fileName
# Prompt user for password and convert to md5 hash
passwd = getpass.getpass()
m = md5.new()
m.update(passwd);
self.passwdHash = m.hexdigest()
def clearFile(self):
passwd = getpass.getpass()
m = md5.new()
m.update(passwd);
if self.passwdHash == m.hexdigest():
return self.encrypt({})
print "ERROR: Password confirmation failed."
# Encrypt note and append to file
def encrypt(self, notes, chunksize=64*1024):
notesStr = json.dumps(notes, sort_keys=True)
iv = Random.new().read(AES.block_size)
encryptor = AES.new(self.passwdHash, AES.MODE_CBC, iv)
filesize = sys.getsizeof(notesStr)
with open(self.fileName, 'wb') as outfile:
outfile.write(struct.pack('<Q', filesize))
outfile.write(iv)
if len(notesStr) % 16 != 0:
notesStr += ' ' * (16 - len(notesStr) % 16)
outfile.write(encryptor.encrypt(notesStr))
outfile.close()
print "SUCCESS: notes encrypted."
# Decrypt file
def decrypt(self, chunksize=24*1024):
with open(self.fileName, 'rb') as infile:
origsize = struct.unpack('<Q', infile.read(struct.calcsize('Q')))[0]
iv = infile.read(16)
decryptor = AES.new(self.passwdHash, AES.MODE_CBC, iv)
return json.loads(str(decryptor.decrypt(infile.read())).strip())
def listNotes(self):
try:
notes = self.decrypt()
for note in notes:
print notes[note]
print "--------------------"
except ValueError:
print "ERROR: Invalid key."
def new(self):
notes = self.decrypt()
# Create new note in temp directory as blank file
notePath = "/tmp/new_note"
if os.path.isfile(notePath):
clashCount = 0
today = datetime.now().strftime("%Y%m%d")
while os.path.isfile(notePath+"."+today+"."+str(clashCount)):
clashCount += 1
notePath = notePath+"."+today+"."+str(clashCount)
noteFile = open(notePath, "w")
noteFile.close()
# Open new note in LibreOffice Writer
os.system("libreoffice --writer "+notePath)
# File should now have note in it
note = open(notePath, "r").read()
# Push new note onto notes
notes.update({time.time(): note})
# Clean up temp note file
os.remove(notePath)
self.encrypt(notes)
privateNote = PrivateNote('collection.encrypted')
#privateNote.new()
#privateNote.listNotes()
#privateNote.clearFile()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.