当前位置: 首页>>代码示例>>Python>>正文


Python GPG.decrypt_file方法代码示例

本文整理汇总了Python中gnupg.GPG.decrypt_file方法的典型用法代码示例。如果您正苦于以下问题:Python GPG.decrypt_file方法的具体用法?Python GPG.decrypt_file怎么用?Python GPG.decrypt_file使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在gnupg.GPG的用法示例。


在下文中一共展示了GPG.decrypt_file方法的6个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: decrypt

# 需要导入模块: from gnupg import GPG [as 别名]
# 或者: from gnupg.GPG import decrypt_file [as 别名]
def decrypt(file):
  gpg_home = find_gpg_keys()
  if ( gpg_home == ''):
    print 'GPG keys not found'
    sys.exit(1)
  gpg = GPG(gnupghome=gpg_home, use_agent=True)
  public_keys = gpg.list_keys()
  key_id = public_keys[0]['keyid']
  if ( os.path.isfile(file)):
      if ( file.endswith('.gpg')):
        stream = open(file, 'rb')
        status = gpg.decrypt_file(stream, output=file[:-4])
        if ( status.ok):
          os.remove(file)
          print file[:-4] + ' succesfully decrypted'
      else:
        print file + ' not encrypted'
  elif ( os.path.isdir(file) ):
    for root, dirs, files in os.walk(file, topdown=True):
      for name in files:
        current_file = (os.path.join(root, name))
        if ( current_file.endswith('.gpg')):
          stream = open(current_file, "rb")
          status = gpg.decrypt_file(stream, output=current_file[:-4])
          if ( status.ok ):
            os.remove(current_file)
            print current_file[:-4] + ' successfully decrypted'
        else:
          print current_file + ' not encrypted'
  else:
    print 'ERROR: file or directory not found'
开发者ID:niklasad1,项目名称:crypt,代码行数:33,代码来源:crypt.py

示例2: reqPGP

# 需要导入模块: from gnupg import GPG [as 别名]
# 或者: from gnupg.GPG import decrypt_file [as 别名]
class reqPGP(object):
    def __init__(self, path=None):
        self.gpg = GPG(gpgbinary=('../gpg.exe' if osName == 'nt' else 'gpg'))
        if not path:
            try:
                self.path = environ["HOME"] + '/'
            except KeyError:
                self.path = environ["HOMEPATH"] + '\\'
        else:
            if path[-1] != '\\' and osName == 'nt':
                path += '\\'
            elif path[-1] != '/' and osName == 'posix':
                path += '/'
            self.path = path
            

    def genKey(self, account, passphrase):
        input_data = self.gpg.gen_key_input(
            name_email=account,
            passphrase=passphrase)
        self.gpg.gen_key(input_data)

    def encryptFile(self, account, data):
        encryptedData = str(self.gpg.encrypt(data, account))
        with open(self.path + '.' + account + '.req', 'w') as f:
            f.write(encryptedData)

    def decryptFile(self, account, passphrase):
        with open(self.path + '.' + account + '.req', 'rb') as f:
            decryptedData = str(self.gpg.decrypt_file(f, passphrase=passphrase))
        return decryptedData
    
    def deleteKey(self, keyId):
        self.gpg.delete_keys(keyId, True)
        self.gpg.delete_keys(keyId)
开发者ID:simonvadee,项目名称:requireris,代码行数:37,代码来源:reqPGP.py

示例3: GpgExtractor

# 需要导入模块: from gnupg import GPG [as 别名]
# 或者: from gnupg.GPG import decrypt_file [as 别名]
class GpgExtractor(StoqExtractorPlugin):

    def __init__(self):
        super().__init__()

    def activate(self, stoq):
        self.stoq = stoq

        super().activate()

        if not os.path.exists(self.gpg_home):
            self.stoq.exception("GPG Home is not defined! Skipping...")

        self.gpg = GPG(gnupghome=self.gpg_home,
                       gpgbinary=self.gpg_bin,
                       keyring=self.public_keyring,
                       secret_keyring=self.secret_keyring)


    def extract(self, payload, **kwargs):
        """
        Decrypt content from provided payload

        :param bytes payload: Payload to be decrypted
        :param **kwargs kwargs: Additional attributes (unused)

        :returns: Decrypted payload
        :rtype: list of tuples

        """

        passphrase = None
        always_trust = False

        if self.passphrase:
            passphrase = self.passphrase

        if self.always_trust:
            always_trust = self.always_trust

        # Ensure the payload is a ByesIO object
        payload_object = BytesIO(payload)

        # Decrypt the payload and return a file object
        decrypted_payload = self.gpg.decrypt_file(payload_object,
                                                  passphrase=passphrase,
                                                  always_trust=always_trust)

        content = decrypted_payload.data

        if content:
            meta = {}
            meta['size'] = len(content)

            # Return the decrypted payload
            return [(meta, content)]

        else:
            self.stoq.log.error("Unable to decrypt payload: {}".format(kwargs))
            return None
开发者ID:mishley,项目名称:stoq-plugins-public,代码行数:62,代码来源:gpg.py

示例4: read_key

# 需要导入模块: from gnupg import GPG [as 别名]
# 或者: from gnupg.GPG import decrypt_file [as 别名]
def read_key(path, gpg_bin, gpg_opts):
    """Read and decrypt a single key file.

    :param str path: The path to the key to decrypt.

    :param str gpg_bin: The path to the gpg binary.

    :param list gpg_opts: The options for gpg.

    :rtype: str
    :returns: The unencrypted content of the file at `path`.

    """
    gpg = GPG(gpgbinary=gpg_bin, options=gpg_opts)
    with open(path, 'rb') as key_file:
        return str(gpg.decrypt_file(key_file))
开发者ID:bfrascher,项目名称:passpy,代码行数:18,代码来源:gpg.py

示例5: Vault

# 需要导入模块: from gnupg import GPG [as 别名]
# 或者: from gnupg.GPG import decrypt_file [as 别名]
class Vault(object):

    def __init__(self):
        self.vault = {}
        self._gpg = GPG()
        self._file_descriptor = None
        self.passphrase = None

    def reload(self):
        if None in (self._file_descriptor, self.passphrase):
            raise RuntimeError('Cannot reload before calling .load()')
        self.load(self._file_descriptor, self.passphrase)

    def load(self, file_descriptor, passphrase):
        self._file_descriptor = file_descriptor
        self.passphrase = passphrase
        self._file_descriptor.seek(0)
        json_ = self._gpg.decrypt_file(self._file_descriptor, passphrase=self.passphrase)
        self.vault = json.loads(str(json_))

    def save(self, file_descriptor=None, passphrase=None):
        if file_descriptor is not None:
            self._file_descriptor = file_descriptor
        if passphrase is not None:
            self.passphrase = passphrase
        self._file_descriptor.seek(0)
        json_ = json.dumps(self.vault)
        encrypted = self._gpg.encrypt(json_, False, passphrase=self.passphrase, symmetric=True)
        self._file_descriptor.write(str(encrypted))

    def __getitem__(self, key):
        return self.vault[key]

    def get(self, name, default=None):
        return self.vault.get(name, default)

    def __setitem__(self, key, value):
        self.vault[key] = value

    def __delitem__(self, key):
        del self._vault[key]

    def list(self):
        return sorted(self._vault.keys())
开发者ID:winny-,项目名称:secret-manager,代码行数:46,代码来源:secret_manager.py

示例6: __init__

# 需要导入模块: from gnupg import GPG [as 别名]
# 或者: from gnupg.GPG import decrypt_file [as 别名]

#.........这里部分代码省略.........
            if self.mode:
                NHKp = pbkdf2(RKp, b'\x04', 10, prf='hmac-sha256')
                CKp = pbkdf2(RKp, b'\x06', 10, prf='hmac-sha256')
            else:
                NHKp = pbkdf2(RKp, b'\x03', 10, prf='hmac-sha256')
                CKp = pbkdf2(RKp, b'\x05', 10, prf='hmac-sha256')
            CKp, mk = self.stageSkippedMK(HKp, 0, Np, CKp)
            body = self.dec(mk, msg[106:])
            if not body or body == '':
                raise (Axolotl_exception('Undecipherable message'))

            self.state['RK'] = RKp
            self.state['HKr'] = HKp
            self.state['NHKr'] = NHKp
            self.state['DHRr'] = DHRp
            self.state['DHRs_priv'] = None
            self.state['DHRs'] = None
            self.state['ratchet_flag'] = True
        self.commit_skipped_mk()
        self.state['Nr'] = Np + 1
        self.state['CKr'] = CKp
        return body

    def encrypt_file(self, filename):
        with open(filename, 'r') as f:
            plaintext = f.read()
        ciphertext = b2a_base64(self.encrypt(plaintext))
        with open(filename + '.asc', 'w') as f:
            lines = [ciphertext[i:i + 64] for i in
                     xrange(0, len(ciphertext), 64)]
            for line in lines:
                f.write(line + '\n')

    def decrypt_file(self, filename):
        with open(filename, 'r') as f:
            ciphertext = a2b_base64(f.read())
        plaintext = self.decrypt(ciphertext)
        print(plaintext)

    def encrypt_pipe(self):
        plaintext = sys.stdin.read()
        ciphertext = b2a_base64(self.encrypt(plaintext))
        sys.stdout.write(ciphertext)
        sys.stdout.flush()

    def decrypt_pipe(self):
        ciphertext = a2b_base64(sys.stdin.read())
        plaintext = self.decrypt(ciphertext)
        sys.stdout.write(plaintext)
        sys.stdout.flush()

    def printKeys(self):
        print('Your Identity key is:\n' + b2a_base64(
            self.state['DHIs']))
        fingerprint = sha224(self.state['DHIs']).hexdigest().upper()
        fprint = ''
        for i in range(0, len(fingerprint), 4):
            fprint += fingerprint[i:i + 2] + ':'
        print('Your identity key fingerprint is: ')
        print(fprint[:-1] + '\n')
        print('Your Ratchet key is:\n' + b2a_base64(
            self.state['DHRs']))
        if self.handshakeKey:
            print('Your Handshake key is:\n' + b2a_base64(
                self.handshakePKey))
        else:
开发者ID:ghtdak,项目名称:pyaxo,代码行数:70,代码来源:pyaxo.py


注:本文中的gnupg.GPG.decrypt_file方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。