r'''
    Generate a key pair. No keys are stored on the master. A key pair is
    returned as a dict containing pub and priv keys. Returns a dictionary
    containing the the ``pub`` and ``priv`` keys with their generated values.

    id\_
        Set a name to generate a key pair for use with salt. If not specified,
        a random name will be specified.

    keysize
        The size of the key pair to generate. The size must be ``2048``, which
        is the default, or greater. If set to a value less than ``2048``, the
        key size will be rounded up to ``2048``.

    .. code-block:: python

        >>> wheel.cmd('key.gen')
        {'pub': '-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBC
        ...
        BBPfamX9gGPQTpN9e8HwcZjXQnmg8OrcUl10WHw09SDWLOlnW+ueTWugEQpPt\niQIDAQAB\n
        -----END PUBLIC KEY-----',
        'priv': '-----BEGIN RSA PRIVATE KEY-----\nMIIEpAIBAAKCAQEA42Kf+w9XeZWgguzv
        ...
        QH3/W74X1+WTBlx4R2KGLYBiH+bCCFEQ/Zvcu4Xp4bIOPtRKozEQ==\n
        -----END RSA PRIVATE KEY-----'}

def gen(id_=None, keysize=2048):
    r'''
    Generate a key pair. No keys are stored on the master. A key pair is
    returned as a dict containing pub and priv keys. Returns a dictionary
    containing the the ``pub`` and ``priv`` keys with their generated values.

    id\_
        Set a name to generate a key pair for use with salt. If not specified,
        a random name will be specified.

    keysize
        The size of the key pair to generate. The size must be ``2048``, which
        is the default, or greater. If set to a value less than ``2048``, the
        key size will be rounded up to ``2048``.

    .. code-block:: python

        >>> wheel.cmd('key.gen')
        {'pub': '-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBC
        ...
        BBPfamX9gGPQTpN9e8HwcZjXQnmg8OrcUl10WHw09SDWLOlnW+ueTWugEQpPt\niQIDAQAB\n
        -----END PUBLIC KEY-----',
        'priv': '-----BEGIN RSA PRIVATE KEY-----\nMIIEpAIBAAKCAQEA42Kf+w9XeZWgguzv
        ...
        QH3/W74X1+WTBlx4R2KGLYBiH+bCCFEQ/Zvcu4Xp4bIOPtRKozEQ==\n
        -----END RSA PRIVATE KEY-----'}

    '''
    if id_ is None:
        id_ = hashlib.sha512(os.urandom(32)).hexdigest()
    else:
        id_ = clean.filename(id_)
    ret = {'priv': '',
           'pub': ''}
    priv = salt.crypt.gen_keys(__opts__['pki_dir'], id_, keysize)
    pub = '{0}.pub'.format(priv[:priv.rindex('.')])
    with salt.utils.files.fopen(priv) as fp_:
        ret['priv'] = salt.utils.stringutils.to_unicode(fp_.read())
    with salt.utils.files.fopen(pub) as fp_:
        ret['pub'] = salt.utils.stringutils.to_unicode(fp_.read())

    # The priv key is given the Read-Only attribute. The causes `os.remove` to
    # fail in Windows.
    if salt.utils.platform.is_windows():
        os.chmod(priv, 128)

    os.remove(priv)
    os.remove(pub)
    return ret