(self, separate_keyring=False, save_batchfile=False,
                      testing=False, **kwargs)
return out
Generate a batch file for input to :meth:`~gnupg.GPG.gen_key`.

        The GnuPG batch file key generation feature allows unattended key
        generation by creating a file with special syntax and then providing it
        to: :command:`gpg --gen-key --batch`. Batch files look like this:

        |  Name-Real: Alice
        |  Name-Email: alice@inter.net
        |  Expire-Date: 2014-04-01
        |  Key-Type: RSA
        |  Key-Length: 4096
        |  Key-Usage: cert
        |  Subkey-Type: RSA
        |  Subkey-Length: 4096
        |  Subkey-Usage: encrypt,sign,auth
        |  Passphrase: sekrit
        |  %pubring foo.gpg
        |  %secring sec.gpg
        |  %commit

        which is what this function creates for you. All of the available,
        non-control parameters are detailed below (control parameters are the
        ones which begin with a '%'). For example, to generate the batch file
        example above, use like this:

        >>> import gnupg
        GnuPG logging disabled...
        >>> from __future__ import print_function
        >>> gpg = gnupg.GPG(homedir='doctests')
        >>> alice = { 'name_real': 'Alice',
        ...     'name_email': 'alice@inter.net',
        ...     'expire_date': '2014-04-01',
        ...     'key_type': 'RSA',
        ...     'key_length': 4096,
        ...     'key_usage': '',
        ...     'subkey_type': 'RSA',
        ...     'subkey_length': 4096,
        ...     'subkey_usage': 'encrypt,sign,auth',
        ...     'passphrase': 'sekrit'}
        >>> alice_input = gpg.gen_key_input(**alice)
        >>> print(alice_input)
        Key-Type: RSA
        Subkey-Type: RSA
        Subkey-Usage: encrypt,sign,auth
        Expire-Date: 2014-04-01
        Passphrase: sekrit
        Name-Real: Alice
        Name-Email: alice@inter.net
        Key-Length: 4096
        Subkey-Length: 4096
        %pubring ./doctests/alice.pubring.gpg
        %secring ./doctests/alice.secring.gpg
        %commit
        <BLANKLINE>
        >>> alice_key = gpg.gen_key(alice_input)
        >>> assert alice_key is not None
        >>> assert alice_key.fingerprint is not None
        >>> message = "no one else can read my sekrit message"
        >>> encrypted = gpg.encrypt(message, alice_key.fingerprint)
        >>> assert isinstance(encrypted.data, str)

        :param bool separate_keyring: Specify for the new key to be written to
            a separate pubring.gpg and secring.gpg. If True,
            :meth:`~gnupg.GPG.gen_key` will automatically rename the separate
            keyring and secring to whatever the fingerprint of the generated
            key ends up being, suffixed with '.pubring' and '.secring'
            respectively.

        :param bool save_batchfile: Save a copy of the generated batch file to
            disk in a file named <name_real>.batch, where <name_real> is the
            ``name_real`` parameter stripped of punctuation, spaces, and
            non-ascii characters.

        :param bool testing: Uses a faster, albeit insecure random number
            generator to create keys. This should only be used for testing
            purposes, for keys which are going to be created and then soon
            after destroyed, and never for the generation of actual use keys.

        :param str name_real: The name field of the UID in the generated key.
        :param str name_comment: The comment in the UID of the generated key.

        :param str name_email: The email in the UID of the generated key.
            (default: ``$USER`` @ :command:`hostname` ) Remember to use UTF-8
            encoding for the entirety of the UID. At least one of
            ``name_real``, ``name_comment``, or ``name_email`` must be
            provided, or else no user ID is created.

        :param str key_type: One of 'RSA', 'DSA', 'ELG-E', or 'default'.
            (default: 'RSA', if using GnuPG v1.x, otherwise 'default') Starts
            a new parameter block by giving the type of the primary key. The
            algorithm must be capable of signing. This is a required
            parameter. The algorithm may either be an OpenPGP algorithm number
            or a string with the algorithm name. The special value ‘default’
            may be used for algo to create the default key type; in this case
            a ``key_usage`` should not be given and 'default' must also be
            used for ``subkey_type``.

        :param int key_length: The requested length of the generated key in
            bits. (Default: 4096)

        :param str key_grip: hexstring This is an optional hexidecimal string
            which is used to generate a CSR or certificate for an already
            existing key. ``key_length`` will be ignored if this parameter
            is given.

        :param str key_usage: Space or comma delimited string of key
            usages. Allowed values are ‘encrypt’, ‘sign’, and ‘auth’. This is
            used to generate the key flags. Please make sure that the
            algorithm is capable of this usage. Note that OpenPGP requires
            that all primary keys are capable of certification, so no matter
            what usage is given here, the ‘cert’ flag will be on. If no
            ‘Key-Usage’ is specified and the ‘Key-Type’ is not ‘default’, all
            allowed usages for that particular algorithm are used; if it is
            not given but ‘default’ is used the usage will be ‘sign’.

        :param str subkey_type: This generates a secondary key
            (subkey). Currently only one subkey can be handled. See also
            ``key_type`` above.

        :param int subkey_length: The length of the secondary subkey in bits.

        :param str subkey_usage: Key usage for a subkey; similar to
            ``key_usage``.

        :type expire_date: :obj:`int` or :obj:`str`
        :param expire_date: Can be specified as an iso-date or as
            <int>[d|w|m|y] Set the expiration date for the key (and the
            subkey). It may either be entered in ISO date format (2000-08-15)
            or as number of days, weeks, month or years. The special notation
            "seconds=N" is also allowed to directly give an Epoch
            value. Without a letter days are assumed. Note that there is no
            check done on the overflow of the type used by OpenPGP for
            timestamps. Thus you better make sure that the given value make
            sense. Although OpenPGP works with time intervals, GnuPG uses an
            absolute value internally and thus the last year we can represent
            is 2105.

        :param str creation_date: Set the creation date of the key as stored
            in the key information and which is also part of the fingerprint
            calculation. Either a date like "1986-04-26" or a full timestamp
            like "19860426T042640" may be used. The time is considered to be
            UTC. If it is not given the current time is used.

        :param str passphrase: The passphrase for the new key. The default is
            to not use any passphrase. Note that GnuPG>=2.1.x will not allow
            you to specify a passphrase for batch key generation -- GnuPG will
            ignore the **passphrase** parameter, stop, and ask the user for
            the new passphrase.  However, we can put the command
            ``%no-protection`` into the batch key generation file to allow a
            passwordless key to be created, which can then have its passphrase
            set later with ``--edit-key``.

        :param str preferences: Set the cipher, hash, and compression
            preference values for this key. This expects the same type of
            string as the sub-command ‘setpref’ in the --edit-key menu.

        :param str revoker: Should be given as 'algo:fpr' (case sensitive).
            Add a designated revoker to the generated key. Algo is the public
            key algorithm of the designated revoker (i.e. RSA=1, DSA=17, etc.)
            fpr is the fingerprint of the designated revoker. The optional
            ‘sensitive’ flag marks the designated revoker as sensitive
            information. Only v4 keys may be designated revokers.

        :param str keyserver: This is an optional parameter that specifies the
            preferred keyserver URL for the key.

        :param str handle: This is an optional parameter only used with the
            status lines ``KEY_CREATED`` and ``KEY_NOT_CREATED``. string may
            be up to 100 characters and should not contain spaces. It is
            useful for batch key generation to associate a key parameter block
            with a status line.

        :rtype: str
        :returns: A suitable input string for the :meth:`GPG.gen_key` method,
            the latter of which will create the new keypair.

        See `this GnuPG Manual section`__ for more details.

        __ http://www.gnupg.org/documentation/manuals/gnupg-devel/Unattended-GPG-key-generation.html
Generate a batch file for input to :meth:`~gnupg.GPG.gen_key`.
Generate a batch file for input to : meth : ~gnupg . GPG . gen_key .
def gen_key_input(self, separate_keyring=False, save_batchfile=False,
                      testing=False, **kwargs):
        """Generate a batch file for input to :meth:`~gnupg.GPG.gen_key`.

        The GnuPG batch file key generation feature allows unattended key
        generation by creating a file with special syntax and then providing it
        to: :command:`gpg --gen-key --batch`. Batch files look like this:

        |  Name-Real: Alice
        |  Name-Email: alice@inter.net
        |  Expire-Date: 2014-04-01
        |  Key-Type: RSA
        |  Key-Length: 4096
        |  Key-Usage: cert
        |  Subkey-Type: RSA
        |  Subkey-Length: 4096
        |  Subkey-Usage: encrypt,sign,auth
        |  Passphrase: sekrit
        |  %pubring foo.gpg
        |  %secring sec.gpg
        |  %commit

        which is what this function creates for you. All of the available,
        non-control parameters are detailed below (control parameters are the
        ones which begin with a '%'). For example, to generate the batch file
        example above, use like this:

        >>> import gnupg
        GnuPG logging disabled...
        >>> from __future__ import print_function
        >>> gpg = gnupg.GPG(homedir='doctests')
        >>> alice = { 'name_real': 'Alice',
        ...     'name_email': 'alice@inter.net',
        ...     'expire_date': '2014-04-01',
        ...     'key_type': 'RSA',
        ...     'key_length': 4096,
        ...     'key_usage': '',
        ...     'subkey_type': 'RSA',
        ...     'subkey_length': 4096,
        ...     'subkey_usage': 'encrypt,sign,auth',
        ...     'passphrase': 'sekrit'}
        >>> alice_input = gpg.gen_key_input(**alice)
        >>> print(alice_input)
        Key-Type: RSA
        Subkey-Type: RSA
        Subkey-Usage: encrypt,sign,auth
        Expire-Date: 2014-04-01
        Passphrase: sekrit
        Name-Real: Alice
        Name-Email: alice@inter.net
        Key-Length: 4096
        Subkey-Length: 4096
        %pubring ./doctests/alice.pubring.gpg
        %secring ./doctests/alice.secring.gpg
        %commit
        <BLANKLINE>
        >>> alice_key = gpg.gen_key(alice_input)
        >>> assert alice_key is not None
        >>> assert alice_key.fingerprint is not None
        >>> message = "no one else can read my sekrit message"
        >>> encrypted = gpg.encrypt(message, alice_key.fingerprint)
        >>> assert isinstance(encrypted.data, str)

        :param bool separate_keyring: Specify for the new key to be written to
            a separate pubring.gpg and secring.gpg. If True,
            :meth:`~gnupg.GPG.gen_key` will automatically rename the separate
            keyring and secring to whatever the fingerprint of the generated
            key ends up being, suffixed with '.pubring' and '.secring'
            respectively.

        :param bool save_batchfile: Save a copy of the generated batch file to
            disk in a file named <name_real>.batch, where <name_real> is the
            ``name_real`` parameter stripped of punctuation, spaces, and
            non-ascii characters.

        :param bool testing: Uses a faster, albeit insecure random number
            generator to create keys. This should only be used for testing
            purposes, for keys which are going to be created and then soon
            after destroyed, and never for the generation of actual use keys.

        :param str name_real: The name field of the UID in the generated key.
        :param str name_comment: The comment in the UID of the generated key.

        :param str name_email: The email in the UID of the generated key.
            (default: ``$USER`` @ :command:`hostname` ) Remember to use UTF-8
            encoding for the entirety of the UID. At least one of
            ``name_real``, ``name_comment``, or ``name_email`` must be
            provided, or else no user ID is created.

        :param str key_type: One of 'RSA', 'DSA', 'ELG-E', or 'default'.
            (default: 'RSA', if using GnuPG v1.x, otherwise 'default') Starts
            a new parameter block by giving the type of the primary key. The
            algorithm must be capable of signing. This is a required
            parameter. The algorithm may either be an OpenPGP algorithm number
            or a string with the algorithm name. The special value ‘default’
            may be used for algo to create the default key type; in this case
            a ``key_usage`` should not be given and 'default' must also be
            used for ``subkey_type``.

        :param int key_length: The requested length of the generated key in
            bits. (Default: 4096)

        :param str key_grip: hexstring This is an optional hexidecimal string
            which is used to generate a CSR or certificate for an already
            existing key. ``key_length`` will be ignored if this parameter
            is given.

        :param str key_usage: Space or comma delimited string of key
            usages. Allowed values are ‘encrypt’, ‘sign’, and ‘auth’. This is
            used to generate the key flags. Please make sure that the
            algorithm is capable of this usage. Note that OpenPGP requires
            that all primary keys are capable of certification, so no matter
            what usage is given here, the ‘cert’ flag will be on. If no
            ‘Key-Usage’ is specified and the ‘Key-Type’ is not ‘default’, all
            allowed usages for that particular algorithm are used; if it is
            not given but ‘default’ is used the usage will be ‘sign’.

        :param str subkey_type: This generates a secondary key
            (subkey). Currently only one subkey can be handled. See also
            ``key_type`` above.

        :param int subkey_length: The length of the secondary subkey in bits.

        :param str subkey_usage: Key usage for a subkey; similar to
            ``key_usage``.

        :type expire_date: :obj:`int` or :obj:`str`
        :param expire_date: Can be specified as an iso-date or as
            <int>[d|w|m|y] Set the expiration date for the key (and the
            subkey). It may either be entered in ISO date format (2000-08-15)
            or as number of days, weeks, month or years. The special notation
            "seconds=N" is also allowed to directly give an Epoch
            value. Without a letter days are assumed. Note that there is no
            check done on the overflow of the type used by OpenPGP for
            timestamps. Thus you better make sure that the given value make
            sense. Although OpenPGP works with time intervals, GnuPG uses an
            absolute value internally and thus the last year we can represent
            is 2105.

        :param str creation_date: Set the creation date of the key as stored
            in the key information and which is also part of the fingerprint
            calculation. Either a date like "1986-04-26" or a full timestamp
            like "19860426T042640" may be used. The time is considered to be
            UTC. If it is not given the current time is used.

        :param str passphrase: The passphrase for the new key. The default is
            to not use any passphrase. Note that GnuPG>=2.1.x will not allow
            you to specify a passphrase for batch key generation -- GnuPG will
            ignore the **passphrase** parameter, stop, and ask the user for
            the new passphrase.  However, we can put the command
            ``%no-protection`` into the batch key generation file to allow a
            passwordless key to be created, which can then have its passphrase
            set later with ``--edit-key``.

        :param str preferences: Set the cipher, hash, and compression
            preference values for this key. This expects the same type of
            string as the sub-command ‘setpref’ in the --edit-key menu.

        :param str revoker: Should be given as 'algo:fpr' (case sensitive).
            Add a designated revoker to the generated key. Algo is the public
            key algorithm of the designated revoker (i.e. RSA=1, DSA=17, etc.)
            fpr is the fingerprint of the designated revoker. The optional
            ‘sensitive’ flag marks the designated revoker as sensitive
            information. Only v4 keys may be designated revokers.

        :param str keyserver: This is an optional parameter that specifies the
            preferred keyserver URL for the key.

        :param str handle: This is an optional parameter only used with the
            status lines ``KEY_CREATED`` and ``KEY_NOT_CREATED``. string may
            be up to 100 characters and should not contain spaces. It is
            useful for batch key generation to associate a key parameter block
            with a status line.

        :rtype: str
        :returns: A suitable input string for the :meth:`GPG.gen_key` method,
            the latter of which will create the new keypair.

        See `this GnuPG Manual section`__ for more details.

        __ http://www.gnupg.org/documentation/manuals/gnupg-devel/Unattended-GPG-key-generation.html
        """
        #: A boolean for determining whether to set subkey_type to 'default'
        default_type = False

        parms = {}

        ## if using GnuPG version 1.x, then set the default 'Key-Type' to
        ## 'RSA' because it doesn't understand 'default'
        parms.setdefault('Key-Type', 'default')
        if _util._is_gpg1(self.binary_version):
            parms.setdefault('Key-Type', 'RSA')
        log.debug("GnuPG v%s detected: setting default key type to %s."
                  % (self.binary_version, parms['Key-Type']))
        parms.setdefault('Key-Length', 4096)
        parms.setdefault('Name-Real', "Autogenerated Key")
        parms.setdefault('Expire-Date', _util._next_year())

        name_email = kwargs.get('name_email')
        uidemail = _util.create_uid_email(name_email)
        parms.setdefault('Name-Email', uidemail)

        if testing:
            ## This specific comment string is required by (some? all?)
            ## versions of GnuPG to use the insecure PRNG:
            parms.setdefault('Name-Comment', 'insecure!')

        for key, val in list(kwargs.items()):
            key = key.replace('_','-').title()
            ## to set 'cert', 'Key-Usage' must be blank string
            if not key in ('Key-Usage', 'Subkey-Usage'):
                if type('')(val).strip():
                    parms[key] = val

        ## if Key-Type is 'default', make Subkey-Type also be 'default'
        if parms['Key-Type'] == 'default':
            default_type = True
            for field in ('Key-Usage', 'Subkey-Usage',):
                try: parms.pop(field)  ## toss these out, handle manually
                except KeyError: pass

        ## Key-Type must come first, followed by length
        out  = "Key-Type: %s\n" % parms.pop('Key-Type')
        out += "Key-Length: %d\n" % parms.pop('Key-Length')
        if 'Subkey-Type' in parms.keys():
            out += "Subkey-Type: %s\n" % parms.pop('Subkey-Type')
        else:
            if default_type:
                out += "Subkey-Type: default\n"
        if 'Subkey-Length' in parms.keys():
            out += "Subkey-Length: %s\n" % parms.pop('Subkey-Length')

        for key, val in list(parms.items()):
            out += "%s: %s\n" % (key, val)

        ## There is a problem where, in the batch files, if the '%%pubring'
        ## and '%%secring' are given as any static string, i.e. 'pubring.gpg',
        ## that file will always get rewritten without confirmation, killing
        ## off any keys we had before. So in the case where we wish to
        ## generate a bunch of keys and then do stuff with them, we should not
        ## give 'pubring.gpg' as our keyring file, otherwise we will lose any
        ## keys we had previously.

        if separate_keyring:
            ring = str(uidemail + '_' + str(_util._utc_epoch()))
            self.temp_keyring = os.path.join(self.homedir, ring+'.pubring')
            self.temp_secring = os.path.join(self.homedir, ring+'.secring')
            out += "%%pubring %s\n" % self.temp_keyring
            out += "%%secring %s\n" % self.temp_secring

        if testing:
            ## see TODO file, tag :compatibility:gen_key_input:
            ##
            ## Add version detection before the '%no-protection' flag.
            out += "%no-protection\n"
            out += "%transient-key\n"

        out += "%commit\n"

        ## if we've been asked to save a copy of the batch file:
        if save_batchfile and parms['Name-Email'] != uidemail:
            asc_uid  = encodings.normalize_encoding(parms['Name-Email'])
            filename = _fix_unsafe(asc_uid) + _util._now() + '.batch'
            save_as  = os.path.join(self._batch_dir, filename)
            readme = os.path.join(self._batch_dir, 'README')

            if not os.path.exists(self._batch_dir):
                os.makedirs(self._batch_dir)

                ## the following pulls the link to GnuPG's online batchfile
                ## documentation from this function's docstring and sticks it
                ## in a README file in the batch directory:

                if getattr(self.gen_key_input, '__doc__', None) is not None:
                    docs = self.gen_key_input.__doc__
                else:
                    docs = str() ## docstring=None if run with "python -OO"
                links = '\n'.join(x.strip() for x in docs.splitlines()[-2:])
                explain = """
This directory was created by python-gnupg, on {}, and
it contains saved batch files, which can be given to GnuPG to automatically
generate keys. Please see
{}""".format(_util.now(), links) ## sometimes python is awesome.

                with open(readme, 'a+') as fh:
                    [fh.write(line) for line in explain]

            with open(save_as, 'a+') as batch_file:
                [batch_file.write(line) for line in out]

        return out
def gen_key_input ( self , separate_keyring = False , save_batchfile = False , testing = False , * * kwargs ) : #: A boolean for determining whether to set subkey_type to 'default' default_type = False parms = { } ## if using GnuPG version 1.x, then set the default 'Key-Type' to ## 'RSA' because it doesn't understand 'default' parms . setdefault ( 'Key-Type' , 'default' ) if _util . _is_gpg1 ( self . binary_version ) : parms . setdefault ( 'Key-Type' , 'RSA' ) log . debug ( "GnuPG v%s detected: setting default key type to %s." % ( self . binary_version , parms [ 'Key-Type' ] ) ) parms . setdefault ( 'Key-Length' , 4096 ) parms . setdefault ( 'Name-Real' , "Autogenerated Key" ) parms . setdefault ( 'Expire-Date' , _util . _next_year ( ) ) name_email = kwargs . get ( 'name_email' ) uidemail = _util . create_uid_email ( name_email ) parms . setdefault ( 'Name-Email' , uidemail ) if testing : ## This specific comment string is required by (some? all?) ## versions of GnuPG to use the insecure PRNG: parms . setdefault ( 'Name-Comment' , 'insecure!' ) for key , val in list ( kwargs . items ( ) ) : key = key . replace ( '_' , '-' ) . title ( ) ## to set 'cert', 'Key-Usage' must be blank string if not key in ( 'Key-Usage' , 'Subkey-Usage' ) : if type ( '' ) ( val ) . strip ( ) : parms [ key ] = val ## if Key-Type is 'default', make Subkey-Type also be 'default' if parms [ 'Key-Type' ] == 'default' : default_type = True for field in ( 'Key-Usage' , 'Subkey-Usage' , ) : try : parms . pop ( field ) ## toss these out, handle manually except KeyError : pass ## Key-Type must come first, followed by length out = "Key-Type: %s\n" % parms . pop ( 'Key-Type' ) out += "Key-Length: %d\n" % parms . pop ( 'Key-Length' ) if 'Subkey-Type' in parms . keys ( ) : out += "Subkey-Type: %s\n" % parms . pop ( 'Subkey-Type' ) else : if default_type : out += "Subkey-Type: default\n" if 'Subkey-Length' in parms . keys ( ) : out += "Subkey-Length: %s\n" % parms . pop ( 'Subkey-Length' ) for key , val in list ( parms . items ( ) ) : out += "%s: %s\n" % ( key , val ) ## There is a problem where, in the batch files, if the '%%pubring' ## and '%%secring' are given as any static string, i.e. 'pubring.gpg', ## that file will always get rewritten without confirmation, killing ## off any keys we had before. So in the case where we wish to ## generate a bunch of keys and then do stuff with them, we should not ## give 'pubring.gpg' as our keyring file, otherwise we will lose any ## keys we had previously. if separate_keyring : ring = str ( uidemail + '_' + str ( _util . _utc_epoch ( ) ) ) self . temp_keyring = os . path . join ( self . homedir , ring + '.pubring' ) self . temp_secring = os . path . join ( self . homedir , ring + '.secring' ) out += "%%pubring %s\n" % self . temp_keyring out += "%%secring %s\n" % self . temp_secring if testing : ## see TODO file, tag :compatibility:gen_key_input: ## ## Add version detection before the '%no-protection' flag. out += "%no-protection\n" out += "%transient-key\n" out += "%commit\n" ## if we've been asked to save a copy of the batch file: if save_batchfile and parms [ 'Name-Email' ] != uidemail : asc_uid = encodings . normalize_encoding ( parms [ 'Name-Email' ] ) filename = _fix_unsafe ( asc_uid ) + _util . _now ( ) + '.batch' save_as = os . path . join ( self . _batch_dir , filename ) readme = os . path . join ( self . _batch_dir , 'README' ) if not os . path . exists ( self . _batch_dir ) : os . makedirs ( self . _batch_dir ) ## the following pulls the link to GnuPG's online batchfile ## documentation from this function's docstring and sticks it ## in a README file in the batch directory: if getattr ( self . gen_key_input , '__doc__' , None ) is not None : docs = self . gen_key_input . __doc__ else : docs = str ( ) ## docstring=None if run with "python -OO" links = '\n' . join ( x . strip ( ) for x in docs . splitlines ( ) [ - 2 : ] ) explain = """
This directory was created by python-gnupg, on {}, and
it contains saved batch files, which can be given to GnuPG to automatically
generate keys. Please see
{}""" . format ( _util . now ( ) , links ) ## sometimes python is awesome. with open ( readme , 'a+' ) as fh : [ fh . write ( line ) for line in explain ] with open ( save_as , 'a+' ) as batch_file : [ batch_file . write ( line ) for line in out ] return out