(self, data, recipients,
                 default_key=None,
                 passphrase=None,
                 armor=True,
                 encrypt=True,
                 symmetric=False,
                 always_trust=True,
                 output=None,
                 throw_keyids=False,
                 hidden_recipients=None,
                 cipher_algo='AES256',
                 digest_algo='SHA512',
                 compress_algo='ZLIB')
return result
Encrypt the message read from the file-like object **data**.

        :param str data: The file or bytestream to encrypt.

        :param str recipients: The recipients to encrypt to. Recipients must
                               be specified keyID/fingerprint.

        .. warning:: Care should be taken in Python2 to make sure that the
                     given fingerprints for **recipients** are in fact strings
                     and not unicode objects.

        :param str default_key: The keyID/fingerprint of the key to use for
                                signing. If given, **data** will be encrypted
                                *and* signed.

        :param str passphrase: If given, and **default_key** is also given,
                               use this passphrase to unlock the secret
                               portion of the **default_key** to sign the
                               encrypted **data**.  Otherwise, if
                               **default_key** is not given, but **symmetric**
                               is ``True``, then use this passphrase as the
                               passphrase for symmetric encryption. Signing
                               and symmetric encryption should *not* be
                               combined when sending the **data** to other
                               recipients, else the passphrase to the secret
                               key would be shared with them.

        :param bool armor: If True, ascii armor the output; otherwise, the
                           output will be in binary format. (Default: True)

        :param bool encrypt: If True, encrypt the **data** using the
                             **recipients** public keys. (Default: True)

        :param bool symmetric: If True, encrypt the **data** to **recipients**
                               using a symmetric key. See the **passphrase**
                               parameter. Symmetric encryption and public key
                               encryption can be used simultaneously, and will
                               result in a ciphertext which is decryptable
                               with either the symmetric **passphrase** or one
                               of the corresponding private keys.

        :param bool always_trust: If True, ignore trust warnings on
                                  **recipients** keys. If False, display trust
                                  warnings. (default: True)

        :type output: str or file-like object
        :param output: The output file to write to. If not specified, the
                       encrypted output is returned, and thus should be stored
                       as an object in Python. For example:

        >>> import shutil
        >>> import gnupg
        >>> if os.path.exists("doctests"):
        ...     shutil.rmtree("doctests")
        >>> gpg = gnupg.GPG(homedir="doctests")
        >>> key_settings = gpg.gen_key_input(key_type='RSA',
        ...                                  key_length=1024,
        ...                                  key_usage='ESCA',
        ...                                  passphrase='foo')
        >>> key = gpg.gen_key(key_settings)
        >>> message = "The crow flies at midnight."
        >>> encrypted = str(gpg.encrypt(message, key.fingerprint))
        >>> assert encrypted != message
        >>> assert not encrypted.isspace()
        >>> decrypted = str(gpg.decrypt(encrypted, passphrase='foo'))
        >>> assert not decrypted.isspace()
        >>> decrypted
        'The crow flies at midnight.'


        :param bool throw_keyids: If True, make all **recipients** keyids be
            zero'd out in packet information. This is the same as using
            **hidden_recipients** for all **recipients**. (Default: False).

        :param list hidden_recipients: A list of recipients that should have
            their keyids zero'd out in packet information.

        :param str cipher_algo: The cipher algorithm to use. To see available
                                algorithms with your version of GnuPG, do:
                                :command:`$ gpg --with-colons --list-config
                                ciphername`. The default **cipher_algo**, if
                                unspecified, is ``'AES256'``.

        :param str digest_algo: The hash digest to use. Again, to see which
                                hashes your GnuPG is capable of using, do:
                                :command:`$ gpg --with-colons --list-config
                                digestname`.  The default, if unspecified, is
                                ``'SHA512'``.

        :param str compress_algo: The compression algorithm to use. Can be one
                                  of ``'ZLIB'``, ``'BZIP2'``, ``'ZIP'``, or
                                  ``'Uncompressed'``.
Encrypt the message read from the file-like object **data**.
Encrypt the message read from the file - like object ** data ** .
def _encrypt(self, data, recipients,
                 default_key=None,
                 passphrase=None,
                 armor=True,
                 encrypt=True,
                 symmetric=False,
                 always_trust=True,
                 output=None,
                 throw_keyids=False,
                 hidden_recipients=None,
                 cipher_algo='AES256',
                 digest_algo='SHA512',
                 compress_algo='ZLIB'):
        """Encrypt the message read from the file-like object **data**.

        :param str data: The file or bytestream to encrypt.

        :param str recipients: The recipients to encrypt to. Recipients must
                               be specified keyID/fingerprint.

        .. warning:: Care should be taken in Python2 to make sure that the
                     given fingerprints for **recipients** are in fact strings
                     and not unicode objects.

        :param str default_key: The keyID/fingerprint of the key to use for
                                signing. If given, **data** will be encrypted
                                *and* signed.

        :param str passphrase: If given, and **default_key** is also given,
                               use this passphrase to unlock the secret
                               portion of the **default_key** to sign the
                               encrypted **data**.  Otherwise, if
                               **default_key** is not given, but **symmetric**
                               is ``True``, then use this passphrase as the
                               passphrase for symmetric encryption. Signing
                               and symmetric encryption should *not* be
                               combined when sending the **data** to other
                               recipients, else the passphrase to the secret
                               key would be shared with them.

        :param bool armor: If True, ascii armor the output; otherwise, the
                           output will be in binary format. (Default: True)

        :param bool encrypt: If True, encrypt the **data** using the
                             **recipients** public keys. (Default: True)

        :param bool symmetric: If True, encrypt the **data** to **recipients**
                               using a symmetric key. See the **passphrase**
                               parameter. Symmetric encryption and public key
                               encryption can be used simultaneously, and will
                               result in a ciphertext which is decryptable
                               with either the symmetric **passphrase** or one
                               of the corresponding private keys.

        :param bool always_trust: If True, ignore trust warnings on
                                  **recipients** keys. If False, display trust
                                  warnings. (default: True)

        :type output: str or file-like object
        :param output: The output file to write to. If not specified, the
                       encrypted output is returned, and thus should be stored
                       as an object in Python. For example:

        >>> import shutil
        >>> import gnupg
        >>> if os.path.exists("doctests"):
        ...     shutil.rmtree("doctests")
        >>> gpg = gnupg.GPG(homedir="doctests")
        >>> key_settings = gpg.gen_key_input(key_type='RSA',
        ...                                  key_length=1024,
        ...                                  key_usage='ESCA',
        ...                                  passphrase='foo')
        >>> key = gpg.gen_key(key_settings)
        >>> message = "The crow flies at midnight."
        >>> encrypted = str(gpg.encrypt(message, key.fingerprint))
        >>> assert encrypted != message
        >>> assert not encrypted.isspace()
        >>> decrypted = str(gpg.decrypt(encrypted, passphrase='foo'))
        >>> assert not decrypted.isspace()
        >>> decrypted
        'The crow flies at midnight.'


        :param bool throw_keyids: If True, make all **recipients** keyids be
            zero'd out in packet information. This is the same as using
            **hidden_recipients** for all **recipients**. (Default: False).

        :param list hidden_recipients: A list of recipients that should have
            their keyids zero'd out in packet information.

        :param str cipher_algo: The cipher algorithm to use. To see available
                                algorithms with your version of GnuPG, do:
                                :command:`$ gpg --with-colons --list-config
                                ciphername`. The default **cipher_algo**, if
                                unspecified, is ``'AES256'``.

        :param str digest_algo: The hash digest to use. Again, to see which
                                hashes your GnuPG is capable of using, do:
                                :command:`$ gpg --with-colons --list-config
                                digestname`.  The default, if unspecified, is
                                ``'SHA512'``.

        :param str compress_algo: The compression algorithm to use. Can be one
                                  of ``'ZLIB'``, ``'BZIP2'``, ``'ZIP'``, or
                                  ``'Uncompressed'``.
        """
        args = []

        ## FIXME: GnuPG appears to ignore the --output directive when being
        ## programmatically driven. We'll handle the IO ourselves to fix this
        ## for now.
        output_filename = None
        if output:
            if getattr(output, 'fileno', None) is not None:
                ## avoid overwrite confirmation message
                if getattr(output, 'name', None) is not None:
                    output_filename = output.name
                    if os.path.exists(output.name):
                        os.remove(output.name)
                    #args.append('--output %s' % output.name)
            else:
                output_filename = output
                if os.path.exists(output):
                    os.remove(output)
                #args.append('--output %s' % output)

        if armor: args.append('--armor')
        if always_trust: args.append('--always-trust')
        if cipher_algo: args.append('--cipher-algo %s' % cipher_algo)
        if compress_algo: args.append('--compress-algo %s' % compress_algo)

        if default_key:
            args.append('--sign')
            args.append('--default-key %s' % default_key)
            if digest_algo:
                args.append('--digest-algo %s' % digest_algo)

        ## both can be used at the same time for an encrypted file which
        ## is decryptable with a passphrase or secretkey.
        if symmetric: args.append('--symmetric')
        if encrypt: args.append('--encrypt')
        if throw_keyids: args.append('--throw-keyids')

        if len(recipients) >= 1:
            log.debug("GPG.encrypt() called for recipients '%s' with type '%s'"
                      % (recipients, type(recipients)))

            if isinstance(recipients, (list, tuple)):
                for recp in recipients:
                    if not _util._py3k:
                        if isinstance(recp, unicode):
                            try:
                                assert _parsers._is_hex(str(recp))
                            except AssertionError:
                                log.info("Can't accept recipient string: %s"
                                         % recp)
                            else:
                                self._add_recipient_string(args, hidden_recipients, str(recp))
                                continue
                            ## will give unicode in 2.x as '\uXXXX\uXXXX'
                            if isinstance(hidden_recipients, (list, tuple)):
                                if [s for s in hidden_recipients if recp in str(s)]:
                                    args.append('--hidden-recipient %r' % recp)
                                else:
                                    args.append('--recipient %r' % recp)
                            else:
                                args.append('--recipient %r' % recp)
                            continue
                    if isinstance(recp, str):
                        self._add_recipient_string(args, hidden_recipients, recp)

            elif (not _util._py3k) and isinstance(recp, basestring):
                for recp in recipients.split('\x20'):
                    self._add_recipient_string(args, hidden_recipients, recp)

            elif _util._py3k and isinstance(recp, str):
                for recp in recipients.split(' '):
                    self._add_recipient_string(args, hidden_recipients, recp)
                    ## ...and now that we've proven py3k is better...
            else:
                log.debug("Don't know what to do with recipients: %r"
                          % recipients)

        result = self._result_map['crypt'](self)
        log.debug("Got data '%s' with type '%s'." % (data, type(data)))
        self._handle_io(args, data, result, passphrase=passphrase, binary=True)
        # Avoid writing raw encrypted bytes to terminal loggers and breaking
        # them in that adorable way where they spew hieroglyphics until reset:
        if armor:
            log.debug("\n%s" % result.data)

        if output_filename:
            log.info("Writing encrypted output to file: %s" % output_filename)
            with open(output_filename, 'wb') as fh:
                fh.write(result.data)
                fh.flush()
                log.info("Encrypted output written successfully.")

        return result
def _encrypt ( self , data , recipients , default_key = None , passphrase = None , armor = True , encrypt = True , symmetric = False , always_trust = True , output = None , throw_keyids = False , hidden_recipients = None , cipher_algo = 'AES256' , digest_algo = 'SHA512' , compress_algo = 'ZLIB' ) : args = [ ] ## FIXME: GnuPG appears to ignore the --output directive when being ## programmatically driven. We'll handle the IO ourselves to fix this ## for now. output_filename = None if output : if getattr ( output , 'fileno' , None ) is not None : ## avoid overwrite confirmation message if getattr ( output , 'name' , None ) is not None : output_filename = output . name if os . path . exists ( output . name ) : os . remove ( output . name ) #args.append('--output %s' % output.name) else : output_filename = output if os . path . exists ( output ) : os . remove ( output ) #args.append('--output %s' % output) if armor : args . append ( '--armor' ) if always_trust : args . append ( '--always-trust' ) if cipher_algo : args . append ( '--cipher-algo %s' % cipher_algo ) if compress_algo : args . append ( '--compress-algo %s' % compress_algo ) if default_key : args . append ( '--sign' ) args . append ( '--default-key %s' % default_key ) if digest_algo : args . append ( '--digest-algo %s' % digest_algo ) ## both can be used at the same time for an encrypted file which ## is decryptable with a passphrase or secretkey. if symmetric : args . append ( '--symmetric' ) if encrypt : args . append ( '--encrypt' ) if throw_keyids : args . append ( '--throw-keyids' ) if len ( recipients ) >= 1 : log . debug ( "GPG.encrypt() called for recipients '%s' with type '%s'" % ( recipients , type ( recipients ) ) ) if isinstance ( recipients , ( list , tuple ) ) : for recp in recipients : if not _util . _py3k : if isinstance ( recp , unicode ) : try : assert _parsers . _is_hex ( str ( recp ) ) except AssertionError : log . info ( "Can't accept recipient string: %s" % recp ) else : self . _add_recipient_string ( args , hidden_recipients , str ( recp ) ) continue ## will give unicode in 2.x as '\uXXXX\uXXXX' if isinstance ( hidden_recipients , ( list , tuple ) ) : if [ s for s in hidden_recipients if recp in str ( s ) ] : args . append ( '--hidden-recipient %r' % recp ) else : args . append ( '--recipient %r' % recp ) else : args . append ( '--recipient %r' % recp ) continue if isinstance ( recp , str ) : self . _add_recipient_string ( args , hidden_recipients , recp ) elif ( not _util . _py3k ) and isinstance ( recp , basestring ) : for recp in recipients . split ( '\x20' ) : self . _add_recipient_string ( args , hidden_recipients , recp ) elif _util . _py3k and isinstance ( recp , str ) : for recp in recipients . split ( ' ' ) : self . _add_recipient_string ( args , hidden_recipients , recp ) ## ...and now that we've proven py3k is better... else : log . debug ( "Don't know what to do with recipients: %r" % recipients ) result = self . _result_map [ 'crypt' ] ( self ) log . debug ( "Got data '%s' with type '%s'." % ( data , type ( data ) ) ) self . _handle_io ( args , data , result , passphrase = passphrase , binary = True ) # Avoid writing raw encrypted bytes to terminal loggers and breaking # them in that adorable way where they spew hieroglyphics until reset: if armor : log . debug ( "\n%s" % result . data ) if output_filename : log . info ( "Writing encrypted output to file: %s" % output_filename ) with open ( output_filename , 'wb' ) as fh : fh . write ( result . data ) fh . flush ( ) log . info ( "Encrypted output written successfully." ) return result