How to encrypt individual notes from your vault

(crossposted on my blog jenglert.gitlab.io once I figure out a Hugo build error)

Based on the thread here:

I decided to write two small python functions that allow me to encrypt & decrypt individual files such as a personal journaling note.

Both functions are sitting in my Obsidian vault and I call them via the command line to encrypt a note by setting a key.

Code below; simply save the functions as .py in your vault and set path_folderto your vault.

Maybe someone can could even make it into a plugin that can directly encrypt/decrypt notes from the Obsidian interface.

encrypt

from Crypto.Cipher import AES

path_folder="C:\\Users\Admin\Google Drive\Obsidian\\"

def encrypt():
    '''
    AES key must be either 16, 24, or 32 bytes long 
    '''
    sep = b'---\n\n' # separate metadata from note

    file = input("Enter file name: ")
    
    with open(path_folder+file, 'rb') as f: 
        everything = f.read()

    metadata = everything[:everything.index(sep)+len(sep)]
    data = everything[everything.index(sep)+len(sep):]

    key = input("Enter key: ").encode('utf-8')
    cipher = AES.new(key, AES.MODE_CTR)
    ct = cipher.encrypt(data)
    nonce = cipher.nonce
    
    
    with open(path_folder+file, 'wb') as f: 
        f.write(metadata)

    with open(path_folder+file, 'ab') as f: 
        f.write(nonce+ct)

    print("File encrypted")

encrypt()

decrypt

from Crypto.Cipher import AES

path_folder="C:\\Users\Admin\Google Drive\Obsidian\\"


def decrypt():
    
    sep = b'---\n\n' # separate metadata from note

    file = input("Enter file name: ")

    with open(path_folder+file, 'rb') as f: 
        everything = f.read()

    metadata = everything[:everything.index(sep)+len(sep)]
    rest = everything[everything.index(sep)+len(sep):]
    
    nonce = rest[:8]
    ct = rest[8:]

    key = input("Enter key: ").encode('utf-8')
    cipher = AES.new(key, AES.MODE_CTR, nonce=nonce)
    pt = cipher.decrypt(ct)
    
    with open(path_folder+file, 'wb') as f: 
        f.write(metadata)

    with open(path_folder+file, 'ab') as f: 
        f.write(pt)
    
    print("File decrypted")

decrypt()

See here if you have trouble with No module named Crypto.Cipher.

5 Likes

I was thinking that a even simpler plugin idea would be to just put a public key in the root of the vault and encrypt everything in the vault/folder with that public key. Note, if you lost the private key then you’ve lost everything in that vault, but you could then share the private key it with collaborators and use public services like github or dropbox to share confidential information.

I guess Obsidian would need some sort of translation layer so you see the dencrypted text when viewing but it would encrypt before saving to disk.