Your IP : 216.73.216.213


Current Path : /opt/alt/python37/lib64/python3.7/site-packages/twisted/conch/ssh/__pycache__/
Upload File :
Current File : //opt/alt/python37/lib64/python3.7/site-packages/twisted/conch/ssh/__pycache__/keys.cpython-37.pyc

B

��q^>��@s$dZddlmZmZddlZddlZddlmZmZddl	Z	ddl
Z
ddlZddlZddl
mZddlmZddlmZmZddlmZmZmZmZdd	lmZmZdd
lmZyddlmZm Z Wn$e!k
r�ddlm"Zm#Z YnXdd
l$m%Z%m&Z&m'Z'ddl(m)Z)ddl*m+Z+ddl,m-Z.ddl,m/Z0ddl1m2Z2m3Z3ddl4m5Z5m6Z6ddl7m8Z8ddl9m:Z:m;Z;m<Z<m=Z=m>Z>m?Z?m@ZAmBZCmDZEddlFmGZGmHZHddlImJZJe�K�e�L�e�M�d�ZNdddd�ZOGdd�deP�ZQGdd �d eP�ZRGd!d"�d"eP�ZSGd#d$�d$eH�ZTGd%d&�d&eU�ZVd*d(d)�ZWdS)+z$
Handling of RSA, DSA, and EC keys.
�)�absolute_import�divisionN)�md5�sha256)�InvalidSignature)�default_backend)�hashes�
serialization)�dsa�rsa�padding�ec)�load_pem_private_key�load_ssh_public_key)�utils)�encode_dss_signature�decode_dss_signature)�encode_rfc6979_signature�decode_rfc6979_signature)�Cipher�
algorithms�modes)�PyAsn1Error)�univ)�decoder)�encoder)�common�sexpy)�int_from_bytes�int_to_bytes)�	randbytes)	�	iterbytes�long�izip�nativeString�unicode�_PY3�_b64decodebytes�_b64encodebytes�	_bytesChr)�
NamedConstant�Names)�_mutuallyExclusiveArguments)secdsa-sha2-nistp256secdsa-sha2-nistp384secdsa-sha2-nistp521snistp256snistp384snistp521)s	secp256r1s	secp384r1s	secp521r1c@seZdZdZdS)�BadKeyErrorzj
    Raised when a key isn't what we expected from it.

    XXX: we really need to check for bad keys
    N)�__name__�
__module__�__qualname__�__doc__�r2r2�I/opt/alt/python37/lib64/python3.7/site-packages/twisted/conch/ssh/keys.pyr-Fsr-c@seZdZdZdS)�EncryptedKeyErrorzb
    Raised when an encrypted key is presented to fromString/fromFile without
    a password.
    N)r.r/r0r1r2r2r2r3r4Osr4c@seZdZdZdS)�BadFingerPrintFormatzS
    Raises when unsupported fingerprint formats are presented to fingerprint.
    N)r.r/r0r1r2r2r2r3r5Wsr5c@seZdZdZe�Ze�ZdS)�FingerprintFormatsa�
    Constants representing the supported formats of key fingerprints.

    @cvar MD5_HEX: Named constant representing fingerprint format generated
        using md5[RFC1321] algorithm in hexadecimal encoding.
    @type MD5_HEX: L{twisted.python.constants.NamedConstant}

    @cvar SHA256_BASE64: Named constant representing fingerprint format
        generated using sha256[RFC4634] algorithm in base64 encoding
    @type SHA256_BASE64: L{twisted.python.constants.NamedConstant}
    N)r.r/r0r1r*�MD5_HEX�
SHA256_BASE64r2r2r2r3r6^sr6c@s�eZdZdZedRdd��ZedSdd��Zedd��Zed	d
��Zedd��Z	ed
d��Z
edd��Zedd��Zedd��Z
edd��Zedd��Zedd��ZedTdd��ZedUdd��ZedVdd ��ZedWd!d"��Zd#d$�Zd%d&�Zd'd(�Zd)d*�Zd+d,�Zd-d.�Zejfd/d0�Zd1d2�Zd3d4�Zd5d6�Z d7d8�Z!d9d:�Z"d;d<�Z#e$d=d>gd=d?gg�dXd@dA��Z%dYdBdC�Z&dZdDdE�Z'd[dFdG�Z(d\dHdI�Z)dJdK�Z*dLdM�Z+dNdO�Z,dPdQ�Z-dS)]�Keyau
    An object representing a key.  A key can be either a public or
    private key.  A public key can verify a signature; a private key can
    create or verify a signature.  To generate a string that can be stored
    on disk, use the toString method.  If you have a private key, but want
    the string representation of the public key, use Key.public().toString().
    Nc	Cs(t|d��}|�|��||�SQRXdS)a�
        Load a key from a file.

        @param filename: The path to load key data from.

        @type type: L{str} or L{None}
        @param type: A string describing the format the key data is in, or
        L{None} to attempt detection of the type.

        @type passphrase: L{bytes} or L{None}
        @param passphrase: The passphrase the key is encrypted with, or L{None}
        if there is no encryption.

        @rtype: L{Key}
        @return: The loaded key.
        �rbN)�open�
fromString�read)�cls�filename�type�
passphrase�fr2r2r3�fromFilexszKey.fromFilecCs�t|t�r|�d�}t|t�r(|�d�}|dkr:|�|�}|dkrPtd|f��t|d|��fd�}|dkr|td|f��|jjdkr�|r�td��||�S|||�SdS)a
        Return a Key object corresponding to the string data.
        type is optionally the type of string, matching a _fromString_*
        method.  Otherwise, the _guessStringType() classmethod will be used
        to guess a type.  If the key is encrypted, passphrase is used as
        the decryption key.

        @type data: L{bytes}
        @param data: The key data.

        @type type: L{str} or L{None}
        @param type: A string describing the format the key data is in, or
        L{None} to attempt detection of the type.

        @type passphrase: L{bytes} or L{None}
        @param passphrase: The passphrase the key is encrypted with, or L{None}
        if there is no encryption.

        @rtype: L{Key}
        @return: The loaded key.
        zutf-8Nzcannot guess the type of %rz_fromString_%szno _fromString method for %s�zkey not encrypted)	�
isinstancer%�encode�_guessStringTyper-�getattr�upper�__code__�co_argcount)r>�datar@rA�methodr2r2r3r<�s 




zKey.fromStringc
Cs�t�|�\}}|dkr@t�|d�\}}}|t�||��t���S|dkr�t�|d�\}}}}	}|tj|	tj	|||d�d��t���S|t
kr�|tj�
t
|t�|d�d��Std|f��d	S)
a
        Return a public key object corresponding to this public key blob.
        The format of a RSA public key blob is::
            string 'ssh-rsa'
            integer e
            integer n

        The format of a DSA public key blob is::
            string 'ssh-dss'
            integer p
            integer q
            integer g
            integer y

        The format of ECDSA-SHA2-* public key blob is::
            string 'ecdsa-sha2-[identifier]'
            integer x
            integer y

            identifier is the standard NIST curve name.

        @type blob: L{bytes}
        @param blob: The key data.

        @return: A new key.
        @rtype: L{twisted.conch.ssh.keys.Key}
        @raises BadKeyError: if the key type (the first string) is unknown.
        sssh-rsarDsssh-dss�)�p�q�g)�y�parameter_numbers�zunknown blob type: %sN)r�getNS�getMPr�RSAPublicNumbers�
public_keyrr
�DSAPublicNumbers�DSAParameterNumbers�_curveTabler
�EllipticCurvePublicKey�from_encoded_pointr-)
r>�blob�keyType�rest�e�nrOrPrQrRr2r2r3�_fromString_BLOB�s(
zKey._fromString_BLOBcCs�t�|�\}}|dkrDt�|d�\}}}}}}	}|j|||||	d�S|dkrxt�|d�\}}	}
}}}|j||
||	|d�S|tkr�t|}
t�|d�\}}	}|t|
j�d�kr�t	d	||f��t�|�\}}|j
|	||d
�St	d|f��dS)
a�
        Return a private key object corresponding to this private key blob.
        The blob formats are as follows:

        RSA keys::
            string 'ssh-rsa'
            integer n
            integer e
            integer d
            integer u
            integer p
            integer q

        DSA keys::
            string 'ssh-dss'
            integer p
            integer q
            integer g
            integer y
            integer x

        EC keys::
            string 'ecdsa-sha2-[identifier]'
            string identifier
            string q
            integer privateValue

            identifier is the standard NIST curve name.


        @type blob: L{bytes}
        @param blob: The key data.

        @return: A new key.
        @rtype: L{twisted.conch.ssh.keys.Key}
        @raises BadKeyError: if
            * the key type (the first string) is unknown
            * the curve name of an ECDSA key does not match the key type
        sssh-rsa�)rbra�drOrPsssh-dss�)rRrQrOrP�xrD�asciiz.ECDSA curve name %r does not match key type %r)�encodedPoint�curve�privateValuezunknown blob type: %sN)rrUrV�_fromRSAComponents�_fromDSAComponentsr[�
_secToNist�namerFr-�_fromECEncodedPoint)r>r^r_r`rbrare�urOrPrQrRrgrjZ	curveNamerkr2r2r3�_fromString_PRIVATE_BLOB�s")zKey._fromString_PRIVATE_BLOBcCs4|�d�r|t|t���St|��d�}|�|�S)a�
        Return a public key object corresponding to this OpenSSH public key
        string.  The format of an OpenSSH public key string is::
            <key type> <base64-encoded public key blob>

        @type data: L{bytes}
        @param data: The key data.

        @return: A new key.
        @rtype: L{twisted.conch.ssh.keys.Key}
        @raises BadKeyError: if the blob type is unknown.
        s
ecdsa-sha2rT)�
startswithrr�decodebytes�splitrc)r>rLr^r2r2r3�_fromString_PUBLIC_OPENSSH/s
zKey._fromString_PUBLIC_OPENSSHcCs|����}td�|dd���}|�d�s4td��|td�d�}t�|d�\}}}}t	�
d|dd	��d
}	|	dkr�td��t�|d	d�d�\}
}}
|d
k�r�|s�td��|dkr�tj
}d}
t|dd��d}|
}ntd|f��|dk�r4t�|�\}}t	�
d|dd	��d
}tj|||||dd�}ntd|f��t|�|
d
k�r\td��t||d|��t�||||��t�d���}|�|�|��}n|d
k�r�td|f��|}t	�
d|dd	��d
}t	�
d|d	d��d
}||k�rtd||f��|�|dd��S)a*
        Return a private key object corresponding to this OpenSSH private key
        string, in the "openssh-key-v1" format introduced in OpenSSH 6.5.

        The format of an openssh-key-v1 private key string is::
            -----BEGIN OPENSSH PRIVATE KEY-----
            <base64-encoded SSH protocol string>
            -----END OPENSSH PRIVATE KEY-----

        The SSH protocol string is as described in
        U{PROTOCOL.key<https://cvsweb.openbsd.org/cgi-bin/cvsweb/src/usr.bin/ssh/PROTOCOL.key>}.

        @type data: L{bytes}
        @param data: The key data.

        @type passphrase: L{bytes} or L{None}
        @param passphrase: The passphrase the key is encrypted with, or L{None}
        if it is not encrypted.

        @return: A new key.
        @rtype: L{twisted.conch.ssh.keys.Key}
        @raises BadKeyError: if
            * a passphrase is provided for an unencrypted key
            * the SSH protocol encoding is incorrect
        @raises EncryptedKeyError: if
            * a passphrase is not provided for an encrypted key
        �rT���sopenssh-key-v1z"unknown OpenSSH private key formatN�z!LrNrzDonly OpenSSH private key files containing a single key are supportedrDsnonez0Passphrase must be provided for an encrypted key)s
aes128-ctrs
aes192-ctrs
aes256-ctr�rd�zunknown encryption type %rsbcryptT)Zignore_few_roundszunknown KDF type %rzbad padding)�backendz*private key specifies KDF %r but no cipherz#check values do not match: %d != %d)�strip�
splitlinesrt�joinrsr-�lenrrU�struct�unpackr4r�AES�int�bcrypt�kdfrr�CTRr�	decryptor�update�finalizerr)r>rLrA�linesZkeyList�cipherr��
kdfOptionsr`rb�_�encPrivKeyList�algorithmClass�	blockSize�keySize�ivSize�salt�rounds�decKeyr��privKeyListZcheck1Zcheck2r2r2r3�_fromPrivateOpenSSH_v1EsV






zKey._fromPrivateOpenSSH_v1csV|����}|ddd�}|d�d��r�|s8td��y,|d�dd�\}}|���d	d�\}�Wn&tk
r�td
|df��YnX|dkr�tj	}t
|�d�d�d
}	t��dkr�td��n6|dkr�tj}d}	t��dkr�td��ntd|f��t
t�fdd�tdt��d�D���}
t||
dd
����}t|||
dd
����}||d|	�}
td�|dd���}t||
�t�|
�t�d���}|�|�|��}t|dd��}|d|�}nd�|dd��}t|�}yt�|�d}Wn2tk
�r*}ztd|f��Wdd}~XYnX|dk�rH|t||t���S|dk�r�t|�dk�rh|d}t|�dk�r~td ��d!d�|dd"�D�\}}}}}}}}|t j!||||||t j"||d#�d$��#t���S|d%k�rDd&d�|dd�D�\}}}}}t|�dk�rtd'��|t$j%|t$j&|t$j'|||d(�d)�d*�j#t�d��Std+|f��dS),a�
        Return a private key object corresponding to this OpenSSH private key
        string, in the old PEM-based format.

        The format of a PEM-based OpenSSH private key string is::
            -----BEGIN <key type> PRIVATE KEY-----
            [Proc-Type: 4,ENCRYPTED
            DEK-Info: DES-EDE3-CBC,<initialization value>]
            <base64-encoded ASN.1 structure>
            ------END <key type> PRIVATE KEY------

        The ASN.1 structure of a RSA key is::
            (0, n, e, d, p, q)

        The ASN.1 structure of a DSA key is::
            (0, p, q, g, y, x)

        The ASN.1 structure of a ECDSA key is::
            (ECParameters, OID, NULL)

        @type data: L{bytes}
        @param data: The key data.

        @type passphrase: L{bytes} or L{None}
        @param passphrase: The passphrase the key is encrypted with, or L{None}
        if it is not encrypted.

        @return: A new key.
        @rtype: L{twisted.conch.ssh.keys.Key}
        @raises BadKeyError: if
            * a passphrase is provided for an unencrypted key
            * the ASN.1 encoding is incorrect
        @raises EncryptedKeyError: if
            * a passphrase is not provided for an encrypted key
        r�i��rTsProc-Type: 4,ENCRYPTEDz0Passphrase must be provided for an encrypted keyrD� �,zinvalid DEK-info %r)sAES-128-CBCsAES-256-CBC�-r{� zAES encrypted key with a bad IVsDES-EDE3-CBC�rzzDES encrypted key with a bad IVzunknown encryption type %rcs"g|]}t�||d�d��qS)rDrz)r�)�.0�i)�ivdatar2r3�
<listcomp>�sz/Key._fromPrivateOpenSSH_PEM.<locals>.<listcomp>Nrwryrx)r|z*Failed to decode key (Bad Passphrase?): %ssECsRSArdz!RSA key failed to decode properlycSsg|]}t|��qSr2)r")r��valuer2r2r3r��s�	)rarb)rOrPre�dmp1�dmq1�iqmp�public_numberssDSAcSsg|]}t|��qSr2)r")r�r�r2r2r3r�
sz!DSA key failed to decode properly)rOrPrQ)rRrS)rgr�zunknown key type %s)(r}r~rsr4ru�rstrip�
ValueErrorr-rr�r�r��	TripleDES�bytes�	bytearray�ranger�digestrtrrr�CBCrr�r�r��ord�
berDecoder�decoderrr�RSAPrivateNumbersrW�private_keyr
�DSAPrivateNumbersrYrZ)r>rLrAr��kindr�ZcipherIVInfor�r�r��iv�ba�bbr��b64Datar��keyDataZ	removeLenZ
decodedKeyrarbrerOrPr�r�r�rQrRrgr2)r�r3�_fromPrivateOpenSSH_PEM�s�%



&

 zKey._fromPrivateOpenSSH_PEMcCs8|����ddd�dkr(|�||�S|�||�SdS)a�
        Return a private key object corresponding to this OpenSSH private key
        string.  If the key is encrypted, passphrase MUST be provided.
        Providing a passphrase for an unencrypted key is an error.

        @type data: L{bytes}
        @param data: The key data.

        @type passphrase: L{bytes} or L{None}
        @param passphrase: The passphrase the key is encrypted with, or L{None}
        if it is not encrypted.

        @return: A new key.
        @rtype: L{twisted.conch.ssh.keys.Key}
        @raises BadKeyError: if
            * a passphrase is provided for an unencrypted key
            * the encoding is incorrect
        @raises EncryptedKeyError: if
            * a passphrase is not provided for an encrypted key
        rr�i��sOPENSSHN)r}r~r�r�)r>rLrAr2r2r3�_fromString_PRIVATE_OPENSSH!szKey._fromString_PRIVATE_OPENSSHcCs�t�t|dd���}|ddks&t�i}x4|ddd�D] \}}t�t�|��d||<q<W|dddkr�|j|d|d|d	|d
d�S|dddkr�|j|d
|dd�St	d|ddf��dS)a
        Return a public key corresponding to this LSH public key string.
        The LSH public key string format is::
            <s-expression: ('public-key', (<key type>, (<name, <value>)+))>

        The names for a RSA (key type 'rsa-pkcs1-sha1') key are: n, e.
        The names for a DSA (key type 'dsa') key are: y, g, p, q.

        @type data: L{bytes}
        @param data: The key data.

        @return: A new key.
        @rtype: L{twisted.conch.ssh.keys.Key}
        @raises BadKeyError: if the key type is unknown
        rTrxrs
public-keyNsdsa�y�g�p�q)rRrQrOrPsrsa-pkcs1-sha1�n�e)rbrazunknown lsh key type %s)
r�parsert�AssertionErrorrrV�NSrmrlr-)r>rL�sexp�kdror2r2r3�_fromString_PUBLIC_LSH>szKey._fromString_PUBLIC_LSHcCs:t�|�}|ddkst�i}x4|ddd�D] \}}t�t�|��d||<q0W|dddkr�t|�dks|tt|���|j|d|d|d	|d
|dd�S|ddd
k�r t|�dks�tt|���|d	|d
kr�|d
|d	|d	<|d
<|j|d|d|d|d	|d
d�St	d|ddf��dS)a+
        Return a private key corresponding to this LSH private key string.
        The LSH private key string format is::
            <s-expression: ('private-key', (<key type>, (<name>, <value>)+))>

        The names for a RSA (key type 'rsa-pkcs1-sha1') key are: n, e, d, p, q.
        The names for a DSA (key type 'dsa') key are: y, g, p, q, x.

        @type data: L{bytes}
        @param data: The key data.

        @return: A new key.
        @rtype: L{twisted.conch.ssh.keys.Key}
        @raises BadKeyError: if the key type is unknown
        rsprivate-keyrTNsdsarfr�r�r�r��x)rRrQrOrPrgs	rsa-pkcs1r{r�r��d)rbrarerOrPzunknown lsh key type %s)
rr�r�rrVr�r�rmrlr-)r>rLr�r�ror2r2r3�_fromString_PRIVATE_LSH]s 
$$zKey._fromString_PRIVATE_LSHcCs�t�|�\}}|dkrpt�|�\}}t�|�\}}t�|�\}}t�|�\}}t�|�\}}|j|||||d�S|dkr�t�|�\}}t�|�\}	}t�|�\}
}t�|�\}}t�|�\}}t�|�\}}|j|
||	|||d�Std|f��dS)a�
        Return a private key object corresponsing to the Secure Shell Key
        Agent v3 format.

        The SSH Key Agent v3 format for a RSA key is::
            string 'ssh-rsa'
            integer e
            integer d
            integer n
            integer u
            integer p
            integer q

        The SSH Key Agent v3 format for a DSA key is::
            string 'ssh-dss'
            integer p
            integer q
            integer g
            integer y
            integer x

        @type data: L{bytes}
        @param data: The key data.

        @return: A new key.
        @rtype: L{twisted.conch.ssh.keys.Key}
        @raises BadKeyError: if the key type (the first string) is unknown
        sssh-dss)rRrQrOrPrgsssh-rsa)rbrarerOrPrqzunknown key type %sN)rrUrVrmrlr-)r>rLr_rOrPrQrRrgrarerbrqr2r2r3�_fromString_AGENTV3�s"zKey._fromString_AGENTV3cCs�|�d�s|�d�rdS|�d�r&dS|�d�r4dS|�d�rBd	S|�d
�sV|�d�r�t�|�\}}d}x|r�|d
7}t�|�\}}qjW|dkr�dSdSdS)z�
        Guess the type of key in data.  The types map to _fromString_*
        methods.

        @type data: L{bytes}
        @param data: The key data.
        sssh-secdsa-sha2-Zpublic_opensshs
-----BEGINZprivate_openssh�{Z
public_lsh�(Zprivate_lshsssh-s
ecdsa-rrTrNZagentv3r^N)rsrrUrV)r>rLZignoredr`�countr2r2r3rG�s"	


zKey._guessStringTypec

Cshtj||d�}|dkr$|�t��}n<tj|||t�||�t�||�t�||�|d�}	|	�t��}||�S)a�
        Build a key from RSA numerical components.

        @type n: L{int}
        @param n: The 'n' RSA variable.

        @type e: L{int}
        @param e: The 'e' RSA variable.

        @type d: L{int} or L{None}
        @param d: The 'd' RSA variable (optional for a public key).

        @type p: L{int} or L{None}
        @param p: The 'p' RSA variable (optional for a public key).

        @type q: L{int} or L{None}
        @param q: The 'q' RSA variable (optional for a public key).

        @type u: L{int} or L{None}
        @param u: The 'u' RSA variable. Ignored, as its value is determined by
        p and q.

        @rtype: L{Key}
        @return: An RSA key constructed from the values as given.
        )rarbN)rOrPrer�r�r�r�)	rrWrXrr�Zrsa_crt_dmp1Zrsa_crt_dmq1�rsa_crt_iqmpr�)
r>rbrarerOrPrq�
publicNumbers�	keyObject�privateNumbersr2r2r3rl�s


zKey._fromRSAComponentsc	CsRtj|tj|||d�d�}|dkr0|�t��}ntj||d�}|�t��}||�S)a
        Build a key from DSA numerical components.

        @type y: L{int}
        @param y: The 'y' DSA variable.

        @type p: L{int}
        @param p: The 'p' DSA variable.

        @type q: L{int}
        @param q: The 'q' DSA variable.

        @type g: L{int}
        @param g: The 'g' DSA variable.

        @type x: L{int} or L{None}
        @param x: The 'x' DSA variable (optional for a public key)

        @rtype: L{Key}
        @return: A DSA key constructed from the values as given.
        )rOrPrQ)rRrSN)rgr�)r
rYrZrXrr�r�)	r>rRrOrPrQrgr�r�r�r2r2r3rm�s
zKey._fromDSAComponentscCsLtj||t|d�}|dkr*|�t��}ntj||d�}|�t��}||�S)a�
        Build a key from EC components.

        @param x: The affine x component of the public point used for verifying.
        @type x: L{int}

        @param y: The affine y component of the public point used for verifying.
        @type y: L{int}

        @param curve: NIST name of elliptic curve.
        @type curve: L{bytes}

        @param privateValue: The private value.
        @type privateValue: L{int}
        )rgrRrjN)�
private_valuer�)r
ZEllipticCurvePublicNumbersr[rXrZEllipticCurvePrivateNumbersr�)r>rgrRrjrkr�r�r�r2r2r3�_fromECComponentss
zKey._fromECComponentscCs8|dkrtj�t||�}nt�|t|t��}||�S)aa
        Build a key from an EC encoded point.

        @param encodedPoint: The public point encoded as in SEC 1 v2.0
        section 2.3.3.
        @type encodedPoint: L{bytes}

        @param curve: NIST name of elliptic curve.
        @type curve: L{bytes}

        @param privateValue: The private value.
        @type privateValue: L{int}
        N)r
r\r]r[Zderive_private_keyr)r>rirjrkr�r2r2r3rp<szKey._fromECEncodedPointcCs
||_dS)z�
        Initialize with a private or public
        C{cryptography.hazmat.primitives.asymmetric} key.

        @param keyObject: Low level key.
        @type keyObject: C{cryptography.hazmat.primitives.asymmetric} key.
        N)�
_keyObject)�selfr�r2r2r3�__init__XszKey.__init__cCs8t|�t|�kr0|��|��ko.|��|��kStSdS)zN
        Return True if other represents an object with the same key.
        N)r@rL�NotImplemented)r��otherr2r2r3�__eq__bs z
Key.__eq__cCs|�|�}|tkr|S|S)zO
        Return True if other represents anything other than this key.
        )r�r�)r�r��resultr2r2r3�__ne__ks
z
Key.__ne__cCs�|��dkr�|��}|d�d�}|��r>d|dd�f}nd|dd�f}xDt|���D]4\}}tr�|dkr�|d|f7}q^|d	||f7}q^W|d
Sdt|���|��r�dp�d
|jj	fg}x�t|�����D]�\}}|�
d|f�t�|�dd�}xv|�rx|dd�}|dd�}d}	x$t
|�D]}
|	dt|
�f}	�q0Wt|�dk�rf|	dd�}	|�
d|	��qWq�W|dd|d<d�|�SdS)z@
        Return a pretty representation of this object.
        �ECrjzutf-8z$<Elliptic Curve Public Key (%s bits)���Nz%<Elliptic Curve Private Key (%s bits)z
curve:
	%sz
%s:
	%sz>
z<%s %s (%s bits)z
Public KeyzPrivate Keyzattr %s:rN��z%02x:rx�	�>�
)r@rLr��isPublic�sorted�itemsr&r$r��key_size�appendr�MPr!r�r�r)r�rLro�out�k�vr�Zby�m�o�cr2r2r3�__repr__ts:
zKey.__repr__cCst|jtjtjtjf�S)zl
        Check if this instance is a public key.

        @return: C{True} if this is a public key.
        )rEr�r�RSAPublicKeyr
�DSAPublicKeyr
r\)r�r2r2r3r��szKey.isPubliccCs|��r|St|j���SdS)z�
        Returns a version of this key containing only the public key data.
        If this is a public key, this may or may not be the same object
        as self.

        @rtype: L{Key}
        @return: A public key.
        N)r�r9r�rX)r�r2r2r3�public�s	z
Key.publiccCsh|tjkr$tt�t|�������S|tjkrVtd�	dd�t
t|������D���Std|f��dS)aO
        The fingerprint of a public key consists of the output of the
        message-digest algorithm in the specified format.
        Supported formats include L{FingerprintFormats.MD5_HEX} and
        L{FingerprintFormats.SHA256_BASE64}

        The input to the algorithm is the public key data as specified by [RFC4253].

        The output of sha256[RFC4634] algorithm is presented to the
        user in the form of base64 encoded sha256 hashes.
        Example: C{US5jTUa0kgX5ZxdqaGF0yGRu8EgKXHNmoT8jHKo1StM=}

        The output of the MD5[RFC1321](default) algorithm is presented to the user as
        a sequence of 16 octets printed as hexadecimal with lowercase letters
        and separated by colons.
        Example: C{c1:b1:30:29:d7:b8:de:6c:97:77:10:d7:46:41:63:87}

        @param format: Format for fingerprint generation. Consists
            hash function and representation format.
            Default is L{FingerprintFormats.MD5_HEX}

        @since: 8.2

        @return: the user presentation of this L{Key}'s fingerprint, as a
        string.

        @rtype: L{str}
        �:cSsg|]}t�|��qSr2)�binascii�hexlify)r�rgr2r2r3r��sz#Key.fingerprint.<locals>.<listcomp>z"Unsupported fingerprint format: %sN)
r6r8r$�base64�	b64encoderr^r�r7rr!rr5)r��formatr2r2r3�fingerprint�s


zKey.fingerprintcCs\t|jtjtjf�rdSt|jtjtjf�r0dSt|jtj	tj
f�rHdStd|jf��dS)z�
        Return the type of the object we wrap.  Currently this can only be
        'RSA', 'DSA', or 'EC'.

        @rtype: L{str}
        @raises RuntimeError: If the object type is unknown.
        �RSA�DSAr�zunknown type of object: %rN)rEr�rr��
RSAPrivateKeyr
r��
DSAPrivateKeyr
r\�EllipticCurvePrivateKey�RuntimeError)r�r2r2r3r@�szKey.typecCs:|��dkr$dt|jjj�d�Sddd�|��SdS)aK
        Get the type of the object we wrap as defined in the SSH protocol,
        defined in RFC 4253, Section 6.6. Currently this can only be b'ssh-rsa',
        b'ssh-dss' or b'ecdsa-sha2-[identifier]'.

        identifier is the standard NIST curve name

        @return: The key type format.
        @rtype: L{bytes}
        r�secdsa-sha2-rhsssh-rsasssh-dss)r�r�N)r@rnr�rjrorF)r�r2r2r3�sshType�szKey.sshTypecCs,|jdkrdS|��dkr$|jjjS|jjS)zv
        Return the size of the object we wrap.

        @return: The size of the key.
        @rtype: L{int}
        Nrr�)r�r@rjr�)r�r2r2r3�sizes


zKey.sizec	CsVt|jtj�r&|j��}|j|jd�St|jtj�rj|j��}|jj|jj|j	|j
|jt�|j|j
�d�St|jt
j�r�|j��}|j|jj|jj
|jjd�St|jt
j�r�|j��}|j|jj|jjj|jjj
|jjjd�St|jtj��r|j��}|j|j|��d�St|jtj��rB|j��}|jj|jj|j|��d�Std|jf��dS)	z_
        Return the values of the public key as a dictionary.

        @rtype: L{dict}
        )rbra)rbrarerOrPrq)rRrQrOrP)rgrRrQrOrP)rgrRrj)rgrRrkrjzUnexpected key type: %sN)rEr�rr�r�rbrarZprivate_numbersrerOrPr�r
r�rRrSrQrrgr
r\rrr�r)r��numbersr2r2r3rLsJ






zKey.datacCs�|��}|��}|dkr>t�d�t�|d�t�|d�S|dkr�t�d�t�|d�t�|d�t�|d	�t�|d
�S|jjjdd}t�|d
�t�|d
dd��t�dt�	|d|�t�	|d
|��SdS)aG
        Return the public key blob for this key. The blob is the
        over-the-wire format for public keys.

        SECSH-TRANS RFC 4253 Section 6.6.

        RSA keys::
            string 'ssh-rsa'
            integer e
            integer n

        DSA keys::
            string 'ssh-dss'
            integer p
            integer q
            integer g
            integer y

        EC keys::
            string 'ecdsa-sha2-[identifier]'
            integer x
            integer y

            identifier is the standard NIST curve name

        @rtype: L{bytes}
        r�sssh-rsararbr�sssh-dssrOrPrQrR�r{rji����N�rg)
r@rLrr�r�r�rjr�rr)r�r@rLZ
byteLengthr2r2r3r^Js2"zKey.blobcCs8|��}|��}|dkr�t�|d|d�}t�d�t�|d�t�|d�t�|d�t�|�t�|d�t�|d�S|dkr�t�d	�t�|d�t�|d�t�|d
�t�|d�t�|d�S|j���	t
jjt
j
j�}t�|d
�t�|d
dd��t�|�t�|d�SdS)a�
        Return the private key blob for this key. The blob is the
        over-the-wire format for private keys:

        Specification in OpenSSH PROTOCOL.agent

        RSA keys::
            string 'ssh-rsa'
            integer n
            integer e
            integer d
            integer u
            integer p
            integer q

        DSA keys::
            string 'ssh-dss'
            integer p
            integer q
            integer g
            integer y
            integer x

        EC keys::
            string 'ecdsa-sha2-[identifier]'
            integer x
            integer y
            integer privateValue

            identifier is the NIST standard curve name.
        r�rOrPsssh-rsarbrarer�sssh-dssrQrRrgrji����Nrk)r@rLrr�rr�r�r�rX�public_bytesr	�EncodingZX962�PublicFormatZUncompressedPoint)r�r@rLr�ZencPubr2r2r3�privateBlobvs JP

zKey.privateBlob�extra�commentrAcCs�|dk	r*tjdtdd�|��r&|}n|}t|t�r>|�d�}t|t�rR|�d�}t|d|��fd�}|dkr~t	d|f��||||d�S)	a
        Create a string representation of this key.  If the key is a private
        key and you want the representation of its public key, use
        C{key.public().toString()}.  type maps to a _toString_* method.

        @param type: The type of string to emit.  Currently supported values
            are C{'OPENSSH'}, C{'LSH'}, and C{'AGENTV3'}.
        @type type: L{str}

        @param extra: Any extra data supported by the selected format which
            is not part of the key itself.  For public OpenSSH keys, this is
            a comment.  For private OpenSSH keys, this is a passphrase to
            encrypt with.  (Deprecated since Twisted 20.3.0; use C{comment}
            or C{passphrase} as appropriate instead.)
        @type extra: L{bytes} or L{unicode} or L{None}

        @param subtype: A subtype of the requested C{type} to emit.  Only
            supported for private OpenSSH keys, for which the currently
            supported subtypes are C{'PEM'} and C{'v1'}.  If not given, an
            appropriate default is used.
        @type subtype: L{str} or L{None}

        @param comment: A comment to include with the key.  Only supported
            for OpenSSH keys.

            Present since Twisted 20.3.0.

        @type comment: L{bytes} or L{unicode} or L{None}

        @param passphrase: A passphrase to encrypt the key with.  Only
            supported for private OpenSSH keys.

            Present since Twisted 20.3.0.

        @type passphrase: L{bytes} or L{unicode} or L{None}

        @rtype: L{bytes}
        Nz�The 'extra' argument to twisted.conch.ssh.keys.Key.toString was deprecated in Twisted 20.3.0; use 'comment' or 'passphrase' instead.ry)�
stacklevelzutf-8z_toString_%szunknown key type: %s)�subtyperrA)
�warnings�warn�DeprecationWarningr�rEr%rFrHrIr-)r�r@r
rrrArMr2r2r3�toString�s,




zKey.toStringcCsn|��dkr6|sd}|j�tjjtjj�d|��St|�	���
dd�}|sRd}|��d|d|��S)a
        Return a public OpenSSH key string.

        See _fromString_PUBLIC_OPENSSH for the string format.

        @type comment: L{bytes} or L{None}
        @param comment: A comment to include with the key, or L{None} to
        omit the comment.
        r�rwr��
)r@r�r	r	r
ZOpenSSHrr}�encodebytesr^�replacer)r�rr�r2r2r3�_toPublicOpenSSH�s
"zKey._toPublicOpenSSHcs�|rJtj}d}d}|jd}d}|}t�|�}	d}
t�|	�t�d|
�}nd}d}d}d}t�d	�}|||�	�t�|p|d�}
d
}x(t
|
�|r�|d7}|
t|d@�7}
q�W|�rt�
||	||d�}t||d
|��t�||||��t�d���}|�|
�|��}n|
}dt�|�t�|�t�|�t�dd�t�|���t�|�}t|��dd��dg�fdd�td
t
��d�D�dg}d�|�dS)aP
        Return a private OpenSSH key string, in the "openssh-key-v1" format
        introduced in OpenSSH 6.5.

        See _fromPrivateOpenSSH_v1 for the string format.

        @type passphrase: L{bytes} or L{None}
        @param passphrase: The passphrase to encrypt the key with, or L{None}
        if it is not encrypted.
        s
aes256-ctrsbcryptr{r��dz!LsnonerwrNrrT�N)r|sopenssh-key-v1rs#-----BEGIN OPENSSH PRIVATE KEY-----csg|]}�||d��qS)�@r2)r�r�)r�r2r3r�:sz,Key._toPrivateOpenSSH_v1.<locals>.<listcomp>rs!-----END OPENSSH PRIVATE KEY-----)rr��
block_sizer �secureRandomrr�r��packrr��chrr�r�rrr�r�	encryptorr�r�r^rrr�r)r�rrAr�Z
cipherNameZkdfNamer�r�r�r�r�r��checkr�ZpadByte�encKeyr r�r^r�r2)r�r3�_toPrivateOpenSSH_v1sD


:"zKey._toPrivateOpenSSH_v1c
s\|��dkr<|st��}n
t�|�}|j�tjjtjj	|�S|�
�}d�d|���d�df�g}|��dkr�|d|d}}t
�||�}d	|d
|d|d|||d|d
|d|d
|f	}n$d	|d|d|d|d|df}t��}	x.tt��|�D]\}
}|	�|
t�|���qWt�|	�}|�rt�d�}
d�dd�t|
�D��}|�d�}|�d�|�d|d�t||
���}t|||
���}||dd�}dt|�d}|t|�|7}tt �!|�t"�#|
�t$�d��%�}|�&|�|�'�}t(|��)dd��|�fdd�t*d	t��d�D�7}|�d�d|���d�df��d�|�S)a,
        Return a private OpenSSH key string, in the old PEM-based format.

        See _fromPrivateOpenSSH_PEM for the string format.

        @type passphrase: L{bytes} or L{None}
        @param passphrase: The passphrase to encrypt the key with, or L{None}
        if it is not encrypted.
        r�rws-----BEGIN rhs PRIVATE KEY-----r�rOrPrrbrarerTrQrRrgr{r�cSsg|]}dt|�f�qS)z%02X)r�)r�rgr2r2r3r�gsz-Key._toPrivateOpenSSH_PEM.<locals>.<listcomp>sProc-Type: 4,ENCRYPTEDsDEK-Info: DES-EDE3-CBC,rNr�)r|csg|]}�||d��qS)rr2)r�r�)r�r2r3r�zsrs	-----END )+r@r	�NoEncryptionZBestAvailableEncryptionr��
private_bytesr
�PEM�
PrivateFormat�TraditionalOpenSSLrLrrFrr�r�Sequencer#�	itertoolsr�ZsetComponentByPositionZInteger�
berEncoderr rr!r�rr�r�rrrr�rr�rr r�r�rrr�)r�rAr rLr�rOrPr�ZobjDataZasn1Sequence�indexr�Zasn1Datar�Zhexivr�r�r"ZpadLenr2)r�r3�_toPrivateOpenSSH_PEM>sX








"
zKey._toPrivateOpenSSH_PEMcCsX|��r|j|d�S|dks$|dkr0|j|d�S|dkrF|j||d�Std|f��dS)a�
        Return a public or private OpenSSH string.  See
        _fromString_PUBLIC_OPENSSH and _fromPrivateOpenSSH_PEM for the
        string formats.  If extra is present, it represents a comment for a
        public key, or a passphrase for a private key.

        @param extra: Comment for a public key or passphrase for a
            private key
        @type extra: L{bytes}

        @rtype: L{bytes}
        )rNr&)rAZv1)rrAzunknown subtype %s)r�rr-r#r�)r�rrrAr2r2r3�_toString_OPENSSHs

zKey._toString_OPENSSHcKs�|��}|��}|���r|dkrft�dddt�|d�dd�gdt�|d	�dd�gggg�}n�|d
kr�t�dddt�|d
�dd�gdt�|d�dd�gdt�|d�dd�gdt�|d�dd�gggg�}ntd|f��dt|��	dd�dS|dk�r|d
|d}}t
�||�}t�dddt�|d�dd�gdt�|d	�dd�gdt�|d�dd�gdt�|�dd�gdt�|�dd�gdt�|d|d�dd�gdt�|d|d�dd�gd t�|�dd�gg	gg�S|d
k�r�t�dddt�|d
�dd�gdt�|d�dd�gdt�|d�dd�gdt�|d�dd�gd!t�|d"�dd�gggg�Std#|f��dS)$z�
        Return a public or private LSH key.  See _fromString_PUBLIC_LSH and
        _fromString_PRIVATE_LSH for the key formats.

        @rtype: L{bytes}
        r�s
public-keysrsa-pkcs1-sha1r�rbrNNr�rar�sdsar�rOr�rPr�rQr�rRzunknown key type %sr�rrw�}sprivate-keys	rsa-pkcs1r�re�arT�b�cr�rgzunknown key type %s')rLr@r�rrrr�r-rrrr�)r��kwargsrLr@r�rOrPr�r2r2r3�
_toString_LSH�sT
$$

"zKey._toString_LSHcKs�|��}|��s�|��dkrF|d|d|d|d|d|df}n.|��dkrt|d|d|d	|d
|df}t�|���d�ttj|��Sd
S)z�
        Return a private Secure Shell Agent v3 key.  See
        _fromString_AGENTV3 for the key format.

        @rtype: L{bytes}
        r�rarerbrqrOrPr�rQrRrgrwN)	rLr�r@rr�rr�mapr�)r�r3rL�valuesr2r2r3�_toString_AGENTV3�s
zKey._toString_AGENTV3cCs�|��}|dkr6|j�|t��t���}t�|�}�n>|dkrx|j�|t���}t	|�\}}t�t
|d�t
|d��}n�|dk�rt|��}|dkr�t��}n|dkr�t�
�}nt��}|j�|t�|��}	t	|	�\}}t
|�}
t
|�}t|
d�tk�rt|
d�}n|
d}|d@�r d	|
}
t|d�tk�r@t|d�}
n|d}
|
d@�rZd	|}t�t�|
�t�|��}t�|���|S)
z�
        Sign some data with this key.

        SECSH-TRANS RFC 4253 Section 6.6.

        @type data: L{bytes}
        @param data: The data to sign.

        @rtype: L{bytes}
        @return: A signature for the given data.
        r�r��r��i�r��)r@r��signr�PKCS1v15r�SHA1rr�rrr�SHA256�SHA384�SHA512r
�ECDSA�strr�r)r�rLr_�sig�ret�r�sr��hashSize�	signaturer:ZsbZrcompZscompr2r2r3r<�s>




zKey.signcCs�t|�dkrdt�|�}}nt�|�\}}||��kr<dS|��}|dkr�|j}|��sb|��}t�|�d|t	�
�t��f}�n|dkr�t�|�d}t
|dd�d	�}t
|dd�d	�}	t||	�}|j}|��s�|��}||t��f}n�|d
k�r�t�|�d}t�|d�\}
}}t
|
d	�}t
|d	�}	t||	�}|j}|���sN|��}|��}
|
dk�rjt��}n|
d
k�r~t��}nt��}||t�|�f}y|j|�Wntk
�r�dSXdSdS)a
        Verify a signature using this key.

        @type signature: L{bytes}
        @param signature: The signature to verify.

        @type data: L{bytes}
        @param data: The signed data.

        @rtype: L{bool}
        @return: C{True} if the signature is valid.
        �(sssh-dssFr�rr�Nr8�bigr�rDr9i�T)r�rr�rUrr@r�r�rXrr=rr>rrrr?r@rAr
rB�verifyr)r�rIrLZ
signatureTyper_r��argsZconcatenatedSignaturerFrGZrstrZsstrr`r�rHr2r2r3rLsX










z
Key.verify)NN)NN)NNNN)N)N)N)NNNN)N)NN)N)NNN).r.r/r0r1�classmethodrCr<rcrrrvr�r�r�r�r�r�rGrlrmr�rpr�r�r�r�r�r�r6r7r�r@rrrLr^rr,rrr#r-r.r4r7r<rLr2r2r2r3r9osd)9>T	$1,"
		)
(
;,4
;

=
A
5?r9�c	Cs�|��jdd�|��sPtjd|t�d�}|jtjj	tj
jt��d�}|�
|�|�d�� }tj|��dt�d�}t|�SQRXdS)	a�
    This function returns a persistent L{Key}.

    The key is loaded from a PEM file in C{location}. If it does not exist, a
    key with the key size of C{keySize} is generated and saved.

    @param location: Where the key is stored.
    @type location: L{twisted.python.filepath.FilePath}

    @param keySize: The size of the key, if it needs to be generated.
    @type keySize: L{int}

    @returns: A persistent key.
    @rtype: L{Key}
    T)ZignoreExistingDirectoryi)Zpublic_exponentr�r|)�encodingr�Zencryption_algorithmr:N)�passwordr|)�parent�makedirs�existsrZgenerate_private_keyrr%r	r
r&r'r(r$Z
setContentr;rr=r9)�locationr�Z
privateKeyZpemZkeyFiler2r2r3�_getPersistentRSAKeybs"


rV)rO)Xr1�
__future__rrr�r*�hashlibrrr�r�rr�Zcryptography.exceptionsrZcryptography.hazmat.backendsrZcryptography.hazmat.primitivesrr	Z)cryptography.hazmat.primitives.asymmetricr
rrr
Z,cryptography.hazmat.primitives.serializationrrZcryptographyrZ/cryptography.hazmat.primitives.asymmetric.utilsrr�ImportErrorrrZ&cryptography.hazmat.primitives.ciphersrrrZpyasn1.errorrZpyasn1.typerZpyasn1.codec.berrr�rr+Ztwisted.conch.sshrrZtwisted.conch.ssh.commonrrZtwisted.pythonr Ztwisted.python.compatr!r"r#r$r%r&r'rtr(rr)rZtwisted.python.constantsr*r+Ztwisted.python.deprecater,Z	SECP256R1Z	SECP384R1Z	SECP521R1r[rn�	Exceptionr-r4r5r6�objectr9rVr2r2r2r3�<module>sh,	~