confini

Parse and merge multiple ini files in python3
git clone git://git.defalsify.org/python-confini.git
Info | Log | Files | Refs | README | LICENSE

pgp.py (1134B)


      1 # standard imports
      2 import logging
      3 import re
      4 import os
      5 
      6 # external imports
      7 import gnupg
      8 
      9 # local imports
     10 from confini.error import DecryptError
     11 
     12 
     13 logg = logging.getLogger(__name__)
     14 
     15 gpg = gnupg.GPG(
     16     verbose=False,
     17     use_agent=True,
     18         )
     19 gpg.encoding = 'utf-8'
     20 
     21 
     22 
     23 class PGPDecrypter:
     24 
     25     def __init__(self, base_dir='.'):
     26         self.base_dir = base_dir
     27 
     28 
     29     def decrypt(self, k, v, src_dir=None):
     30         if src_dir == None:
     31             src_dir = self.base_dir
     32 
     33         if type(v).__name__ != 'str':
     34             logg.debug('entry {} is not type str'.format(k))
     35             return (v, False)
     36 
     37         m = re.match(r'^\!gpg\((.*)\)', v)
     38         if m != None:
     39             filename = m.group(1)
     40             if filename[0] != '/':
     41                 filename = os.path.join(src_dir, filename)
     42             f = open(filename, 'rb')
     43             logg.debug('decrypting entry {} in file {}'.format(k, f))
     44             d = gpg.decrypt_file(f)
     45             if not d.ok:
     46                 raise DecryptError()
     47             v = str(d)
     48             f.close()
     49 
     50         return (v, m != None)
     51 
     52     def __str__(self):
     53         return 'gpg decrypter'