Skip to content

Instantly share code, notes, and snippets.

@hdante
Created January 1, 2015 15:49
Show Gist options
  • Save hdante/919e2d3ae73238d801b8 to your computer and use it in GitHub Desktop.
Save hdante/919e2d3ae73238d801b8 to your computer and use it in GitHub Desktop.
cryptedit: transparently edit GPG encrypted text file
#!/usr/bin/env python
# cryptedit: transparently edit GPG encrypted text file
#
# usage:
# - create an encrypted text file:
# gpg -o text.gpg --symmetric text
# - edit it with cryptedit
# cryptedit text.gpg
# Replace by your preferred editor
edit = 'gedit --standalone \'%s\''
import getpass
import os
import shutil
import sys
import tempfile
def check(result):
if result != 0:
print('aborting')
raise SystemExit
encrypt = 'gpg --batch --yes --passphrase \'%s\' --output \'%s\' --symmetric \'%s\''
decrypt = 'gpg --batch --yes --passphrase \'%s\' --output \'%s\' --decrypt \'%s\''
try:
encrypted = sys.argv[1]
except:
print('Usage: %s <file>' % sys.argv[0])
raise SystemExit
old = encrypted + '.old'
tmp = tempfile.mkstemp(prefix=encrypted+'.')
decrypted = tmp[1]
password = getpass.getpass()
check(os.system(decrypt % (password, decrypted, encrypted)))
time1 = os.stat(decrypted).st_mtime
check(os.system(edit % decrypted))
time2 = os.stat(decrypted).st_mtime
if time1 == time2:
print('unchanged')
raise SystemExit
shutil.copy2(encrypted, old)
check(os.system(encrypt % (password, encrypted, decrypted)))
os.close(tmp[0])
os.unlink(decrypted)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment