
    \d                       U d Z ddlZddlZddlZddlZddlZddlmZmZm	Z	 ddl
mZmZ ddlmZmZ ddlZddlmZ ddlmZ ddlmZ dd	lmZmZ dd
lmZmZmZmZmZ ddl m!Z!m"Z"m#Z# ddl$m%Z%m&Z& ddl'm(Z)m*Z+ ddl,m-Z- ddl.m/Z/ ddl0m1Z1m2Z2 ddl3m4Z4 ddl5m6Z6 ddl7m8Z8m9Z9 ddl:m;Z;m<Z< ddl=m>Z> 	 ddl?m@Z@mAZA n# eB$ r ddl?mCZ@mDZA Y nw xY w ejE                     ejF                     ejG                    dZHddddZIeeejJ                          eKd<   eeejL                          eKd<    e            M                                rejJ        ZJejL        ZLn	 ddlNmLZLmJZJ n# eB$ r dZJdZLY nw xY w G d  d!eO          ZP G d" d#eO          ZQ G d$ d%eO          ZR G d& d'eO          ZS G d( d)e<          ZT G d* d+eO          ZUd, ZV G d- d.          ZWd1d0ZXdS )2z0
Handling of RSA, DSA, ECDSA, and Ed25519 keys.
    N)	b64encodedecodebytesencodebytes)md5sha256)OptionalType)utils)InvalidSignature)default_backend)hashesserialization)dsaeced25519paddingrsa)Cipher
algorithmsmodes)load_pem_private_keyload_ssh_public_key)decoderencoder)PyAsn1Error)univ)commonsexpy)int_to_bytes)	randbytes)	iterbytesnativeString)NamedConstantNames)_mutuallyExclusiveArguments)decode_dss_signatureencode_dss_signature)decode_rfc6979_signatureencode_rfc6979_signature)s   ecdsa-sha2-nistp256s   ecdsa-sha2-nistp384s   ecdsa-sha2-nistp521s   nistp256s   nistp384s   nistp521)s	   secp256r1s	   secp384r1s	   secp521r1Ed25519PublicKeyEd25519PrivateKey)r+   r*   c                       e Zd ZdZdS )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__     6lib/python3.11/site-packages/twisted/conch/ssh/keys.pyr-   r-   U   s           r4   r-   c                       e Zd ZdZdS )BadSignatureAlgorithmErrorzi
    Raised when a public key signature algorithm name isn't defined for this
    public key format.
    Nr.   r3   r4   r5   r7   r7   ]              r4   r7   c                       e Zd ZdZdS )EncryptedKeyErrorzb
    Raised when an encrypted key is presented to fromString/fromFile without
    a password.
    Nr.   r3   r4   r5   r:   r:   d   r8   r4   r:   c                       e Zd ZdZdS )BadFingerPrintFormatzS
    Raises when unsupported fingerprint formats are presented to fingerprint.
    Nr.   r3   r4   r5   r<   r<   k   s           r4   r<   c                   :    e Zd ZdZ e            Z e            ZdS )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/   r0   r1   r2   r#   MD5_HEXSHA256_BASE64r3   r4   r5   r>   r>   q   s0        
 
 mooG!MOOMMMr4   r>   c                       e Zd ZdZdS )PassphraseNormalizationErrorz
    Raised when a passphrase contains Unicode characters that cannot be
    normalized using the available Unicode character database.
    Nr.   r3   r4   r5   rB   rB      r8   r4   rB   c                     t          | t                    rOt          d | D                       rt                      t	          j        d|                               d          S | S )a  
    Normalize a passphrase, which may be Unicode.

    If the passphrase is Unicode, this follows the requirements of U{NIST
    800-63B, section
    5.1.1.2<https://pages.nist.gov/800-63-3/sp800-63b.html#memsecretver>}
    for Unicode characters in memorized secrets: it applies the
    Normalization Process for Stabilized Strings using NFKC normalization.
    The passphrase is then encoded using UTF-8.

    @type passphrase: L{bytes} or L{unicode} or L{None}
    @param passphrase: The passphrase to normalize.

    @return: The normalized passphrase, if any.
    @rtype: L{bytes} or L{None}
    @raises PassphraseNormalizationError: if the passphrase is Unicode and
    cannot be normalized using the available Unicode character database.
    c              3   F   K   | ]}t          j        |          d k    V  dS )CnN)unicodedatacategory).0cs     r5   	<genexpr>z'_normalizePassphrase.<locals>.<genexpr>   s2      CC1{#A&&$.CCCCCCr4   NFKCzUTF-8)
isinstancestranyrB   rF   	normalizeencode
passphrases    r5   _normalizePassphraserS      sl    & *c"" 	 CC
CCCCC 	1 /000$VZ88??HHHr4   c                   x   e Zd ZdZed0d            Zed0d            Zed             Zed             Zed             Z	ed             Z
ed	             Zed
             Zed             Zed             Zed             Zed             Zed1d            Zed2d            Zed2d            Zed2d            Zed2d            Zd ZdedefdZdefdZd Zd Zej        fdZ d Z!d Z"d Z#d Z$d  Z%d! Z&d" Z'd# Z( e)d$d%gd$d&gg          d1d'            Z*d2d(Z+d0d)Z,d2d*Z-d3d+Z.d, Z/d- Z0d2d.Z1d/ Z2dS )4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                     t          |d          5 }|                     |                                ||          cddd           S # 1 swxY w Y   dS )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typerR   fs        r5   fromFilezKey.fromFile   s    $ (D!! 	>Q>>!&&((D*==	> 	> 	> 	> 	> 	> 	> 	> 	> 	> 	> 	> 	> 	> 	> 	> 	> 	>s   )AAAc                    t          |t                    r|                    d          }t          |          }||                     |          }|t          d|          t          | d|                                 d          }|t          d|           |j        j	        dk    r|rt          d           ||          S  |||          S )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.
        utf-8Nzcannot guess the type of _fromString_zno _fromString method for    zkey not encrypted)
rL   rM   rP   rS   _guessStringTyper-   getattrupper__code__co_argcount)r[   datar]   rR   methods        r5   rY   zKey.fromString   s    . dC   	(;;w''D)*55
<''--D<B$BBCCC;TZZ\\;;TBB>A4AABBB?&!++ 7!"56666$<<6$
+++r4   c           
         t          j        |          \  }}|dk    rVt          j        |d          \  }}} | t          j        ||                              t                                          S |dk    rnt          j        |d          \  }}}}	} | t          j        |	t          j	        |||                                        t                                          S |t          v rM | t          j                            t          |         t          j        |d          d                             S |dk    r,t          j        |          \  }
}|                     |
          S t          d	|           )
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.

        The format of an Ed25519 public key blob is::
            string 'ssh-ed25519'
            string a

        @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.
           ssh-rsarc      ssh-dss   pqgyparameter_numbers      ssh-ed25519unknown blob type: )r   getNSgetMPr   RSAPublicNumbers
public_keyr   r   DSAPublicNumbersDSAParameterNumbers_curveTabler   EllipticCurvePublicKeyfrom_encoded_point_fromEd25519Componentsr-   )r[   blobkeyTyperestenrp   rq   rr   rt   as              r5   _fromString_BLOBzKey._fromString_BLOB   s   D T**j  dA..JAq$3s+Aq11<<_=N=NOOPPP
""%|D!44Aq!Q3$3+BQ!q+Q+Q+Q  *_..//  
 ##3)<<(&,tQ*?*?*B   
 &&l4((GAt--a000=G==>>>r4   c                    t          j        |          \  }}|dk    r7t          j        |d          \  }}}}}}	}|                     |||||	          S |dk    r6t          j        |d          \  }}	}
}}}|                     ||
||	|          S |t
          v rt
          |         }t          j        |d          \  }}	}|t          |j                            d                   k    rt          d	|d
|          t          j        |          \  }}| 
                    |	||          S |dk    r:t          j        |d          \  }}}|dd         }|                     ||          S t          d|           )a6  
        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.

        Ed25519 keys::
            string 'ssh-ed25519'
            string a
            string k || a


        @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
        rl      r   r   drp   rq   rm      rt   rr   rp   rq   xrc   asciizECDSA curve name z does not match key type )encodedPointcurveprivateValuerw   N    )krx   )r   ry   rz   _fromRSAComponents_fromDSAComponentsr   
_secToNistnamerP   r-   _fromECEncodedPointr   )r[   r   r   r   r   r   r   urp   rq   rr   rt   r   r   	curveNamer   r   combinedr   s                      r5   _fromString_PRIVATE_BLOBzKey._fromString_PRIVATE_BLOB'  s   \ T**j  %+\$%:%:"Aq!Q1d))Aa1)BBB
"""(,tQ"7"7Aq!Q4))Aa1)BBB##(E!'dA!6!6Iq$Juz'8'8'A'ABBB!k!*GG5   "(d!3!3L$**gL +    && !'T1 5 5Ax"A--a1-555=G==>>>r4   c                     |                     d          r% | t          |t                                          S t          |                                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-sha2rv   )
startswithr   r   r   splitr   )r[   ri   r   s      r5   _fromString_PUBLIC_OPENSSHzKey._fromString_PUBLIC_OPENSSHr  sg      ??=)) 	E3*41B1BCCDDD4::<<?++##D)))r4   c           	         |                                                                 }t          d                    |dd                             }|                    d          st          d          |t          d          d         }t          j        |d          \  }}}}t          j
        d|dd	                   d
         }	|	dk    rt          d          t          j        |d	d         d          \  }
}}
|dk    ro|st          d          |dv r+t          j        }d}t          |dd                   dz  }|}nt          d|          |dk    rWt          j        |          \  }}t          j
        d|dd	                   d
         }t          j        ||||z   |d          }nt          d|          t          |          |z  d
k    rt          d          t#           ||d|                   t%          j        ||||z                      t)                                                                }|                    |          |                                z   }n|dk    rt          d|d          |}t          j
        d|dd	                   d
         }t          j
        d|d	d                   d
         }||k    rt          d||fz            |                     |dd                   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
        r4   rv      openssh-key-v1 z"unknown OpenSSH private key formatN   !Lrn   r   zDonly OpenSSH private key files containing a single key are supportedrc      none0Passphrase must be provided for an encrypted key)s
   aes128-ctrs
   aes192-ctr
   aes256-ctr   r      unknown encryption type    bcryptT)ignore_few_roundszunknown KDF type zbad paddingbackendzprivate key specifies KDF z but no cipherz#check values do not match: %d != %d)strip
splitlinesr   joinr   r-   lenr   ry   structunpackr:   r   AESintbcryptkdfr   r   CTRr   	decryptorupdatefinalizer   )r[   ri   rR   lineskeyListcipherr   
kdfOptionsr   r   _encPrivKeyListalgorithmClass	blockSizekeySizeivSizesaltroundsdecKeyr   privKeyListcheck1check2s                          r5   _fromPrivateOpenSSH_v1zKey._fromPrivateOpenSSH_v1  sI   : 

''))chhuQrT{3344!!"566 	DBCCC#122445(.Wa(@(@%ZM$RaR))!,66-  
  &|DHa88>1W 'I   FFF!+	fQqSk**a/"!"GV"G"GHHHi#\*55
dtT"1"X66q9f$&*   ""=c"="=>>>N##i/A55!-000vhwh/00	&7V+;!;<=='))   ikk	 
 $**>::Y=O=O=Q=QQKKg~~!kGJssL   )Kt[!_55a8t[1%566q9VCvvFVVWWW++KO<<<r4   c                 	   |                                                                 }|d         dd         }|d                             d          r|st          d          	 |d                             dd          \  }}|                                                    d	d          \  }n&# t          $ r t          d
|d                   w xY w|dv rZt          j	        }t          |                    d          d                   dz  }	t                    dk    rt          d          nI|dk    r1t          j        }d}	t                    dk    rt          d          nt          d|          t          t          fdt          dt                    d          D                                 }
t!          ||
dd         z                                             }t!          ||z   |
dd         z                                             }||z   d|	         }t%          d                    |dd                             }t)           ||          t+          j        |
          t/                                                                }|                    |          |                                z   }t7          |dd                   }|d|          }n,d                    |dd                   }t%          |          }	 t9          j        |          d         }n$# t<          $ r}t          d|           d}~ww xY w|dk    r& | t?          ||t/                                          S |dk    rt          |          dk    r|d         }t          |          dk     rt          d          d  |dd!         D             \  }}}}}}}} | tA          j!        ||||||tA          j"        ||"          #          #                    t/                                          S |d$k    rd% |dd         D             \  }}}}}t          |          dk     rt          d&           | tI          j%        |tI          j&        |tI          j'        |||'          (          )          #                    t/                                          S t          d*|           )+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      rv      Proc-Type: 4,ENCRYPTEDr   rc          ,zinvalid DEK-info )s   AES-128-CBCs   AES-256-CBC   -r   r   zAES encrypted key with a bad IVs   DES-EDE3-CBC   r   zDES encrypted key with a bad IVr   c              3   N   K   | ]}t          ||d z            d          V   dS )rc   r   Nr   )rH   iivdatas     r5   rJ   z.Key._fromPrivateOpenSSH_PEM.<locals>.<genexpr>#  s:      WW#fQQY/44WWWWWWr4   Nr4   r   r   r   z(Failed to decode key (Bad Passphrase?): s   ECs   RSAr   z!RSA key failed to decode properlyc              3   4   K   | ]}t          |          V  d S Nr   rH   values     r5   rJ   z.Key._fromPrivateOpenSSH_PEM.<locals>.<genexpr>C  s(      .W.Wes5zz.W.W.W.W.W.Wr4   	   r   r   rp   rq   r   dmp1dmq1iqmppublic_numberss   DSAc              3   4   K   | ]}t          |          V  d S r   r   r   s     r5   rJ   z.Key._fromPrivateOpenSSH_PEM.<locals>.<genexpr>P  s(      EEESZZEEEEEEr4   z!DSA key failed to decode properlyro   rs   r   r   unknown key type )(r   r   r   r:   r   rstrip
ValueErrorr-   r   r   r   r   	TripleDESbytes	bytearrayranger   digestr   r   r   r   CBCr   r   r   r   ord
berDecoderdecoder   r   r   RSAPrivateNumbersr{   private_keyr   DSAPrivateNumbersr}   r~   ) r[   ri   rR   r   kindr   cipherIVInfor   r   r   ivbabbr   b64Datar   keyData	removeLen
decodedKey	asn1Errorr   r   r   rp   rq   r   r   r   rr   rt   r   r   s                                   @r5   _fromPrivateOpenSSH_PEMzKey._fromPrivateOpenSSH_PEM  sL   J 

''))Qx38899 ,	+ 'I  
D"'(..q"9"9<!-!4!4!6!6!<!<T1!E!E D D D!"BeAh"B"BCCCD 999!+fll4003449v;;"$$%&GHHH %?**!+!5v;;"$$%&GHHH % ""GV"G"GHHH WWWWeAs6{{TU>V>VWWWWW B Z"RaR&())0022BR*_r"1"v-..5577B2gxx(F!#((52;"7"788Gv&&	"?P?P  ikk   &&w//)2D2D2F2FFGGBCCL))Ik	zk*GGhhuQrT{++G!'**G	V#*733A6JJ 	V 	V 	VTTTUUU	V 5==3+D*o>O>OPPQQQ6>>:!##']
:""!"EFFF.W.WzRSTURU.W.W.W+Aq!Q4t3%#&#7!q#A#A#A   +o//00
 
 
 V^^EEZ!_EEEMAq!Q:""!"EFFF3%#&#7s/FaST/U/U/U$ $ $  
 +o&7&7+88   8$88999s%   &A
B1 1#CL4 4
M>MMc                     |                                                                 d         dd         dk    r|                     ||          S |                     ||          S )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
        r   r   r   s   OPENSSH)r   r   r   r  )r[   ri   rR   s      r5   _fromString_PRIVATE_OPENSSHzKey._fromString_PRIVATE_OPENSSH^  s_    , ::<<""$$Q'3/:==--dJ??? ..tZ@@@r4   c                 *   t          j        t          |dd                             }|d         dk    sJ i }|d         dd         D ]4\  }}t          j        t          j        |                    d         ||<   5|d         d         dk    r1|                     |d         |d         |d	         |d
                   S |d         d         dk    r#|                     |d         |d                   S t          d|d         d                    )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
        rv   r   r   
   public-keyN   dsa   y   g   p   qrt   rr   rp   rq      rsa-pkcs1-sha1   n   er   r   unknown lsh key type )	r   parser   r   rz   NSr   r   r-   r[   ri   sexpkdr   s        r5   _fromString_PUBLIC_LSHzKey._fromString_PUBLIC_LSH{  s   " {;tAbDz2233Aw-''''q'!""+ 	8 	8JD$|FIdOO44Q7BtHH71:))T(bh"T(bh *    !WQZ,,,))BtH4)AAABd1gajBBCCCr4   c                 2   t          j        |          }|d         dk    sJ i }|d         dd         D ]4\  }}t          j        t          j        |                    d         ||<   5|d         d         dk    rbt          |          dk    sJ t          |                      |                     |d         |d         |d	         |d
         |d                   S |d         d         dk    rt          |          dk    sJ t          |                      |d	         |d
         k    r|d
         |d	         c|d	<   |d
<   |                     |d         |d         |d         |d	         |d
                   S t          d|d         d                    )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
        r      private-keyrv   Nr	  r   r
  r  r  r     xr   	   rsa-pkcs1r   r  r     dr   r  )	r   r  r   rz   r  r   r   r   r-   r  s        r5   _fromString_PRIVATE_LSHzKey._fromString_PRIVATE_LSH  s   " {4  Aw.((((q'!""+ 	8 	8JD$|FIdOO44Q7BtHH71:r77a<<<R<<<))T(bh"T(bh"T( *    !WQZ<''r77a<<<R<<<$x"T(""%'Xr$x"4"T())T(bh"T(bh"T( *   
 Bd1gajBBCCCr4   c                    t          j        |          \  }}|dk    rt          j        |          \  }}t          j        |          \  }}t          j        |          \  }}t          j        |          \  }}t          j        |          \  }}|                     |||||          S |dk    rt          j        |          \  }}t          j        |          \  }	}t          j        |          \  }
}t          j        |          \  }}t          j        |          \  }}t          j        |          \  }}|                     |
||	|||          S t          d|           )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
        rm   r   rl   r   r   r   rp   rq   r   r   )r   ry   rz   r   r   r-   )r[   ri   r   rp   rq   rr   rt   r   r   r   r   r   s               r5   _fromString_AGENTV3zKey._fromString_AGENTV3  sU   < T**j  l4((GAtl4((GAtl4((GAtl4((GAtl4((GAt))Aa1)BBB
""l4((GAtl4((GAtl4((GAtl4((GAtl4((GAtl4((GAt))Aa1Q)GGG;';;<<<r4   c                    |                     d          s|                     d          rdS |                     d          rdS |                     d          rdS |                     d          rd	S |                     d
          s*|                     d          s|                     d          rCt          j        |          \  }}d}|r|dz  }t          j        |          \  }}||dk    rdS dS dS )z
        Guess the type of key in data.  The types map to _fromString_*
        methods.

        @type data: L{bytes}
        @param data: The key data.
        s   ssh-   ecdsa-sha2-public_opensshs
   -----BEGINprivate_openssh   {
public_lsh   (private_lshs      ssh-s
      ecdsa-s      ssh-ed25519r   rv   rn   agentv3r   N)r   r   ry   rz   )r[   ri   ignoredr   counts        r5   rd   zKey._guessStringType  s%    ??7## 	t~'F'F 	##__]++ 	$$__T"" 	<__T"" 	 =OO344	899	 =>>	
 #L..MGTE 3
 &T 2 2  3 qyy yv	 	r4   c                 v   t          j        ||          }|"|                    t                                }nut          j        |||t          j        ||          t          j        ||          t          j        ||          |          }	|	                    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.
        r   Nr   )	r   r{   r|   r   r   rsa_crt_dmp1rsa_crt_dmq1rsa_crt_iqmpr   )
r[   r   r   r   rp   rq   r   publicNumbers	keyObjectprivateNumberss
             r5   r   zKey._fromRSAComponents  s    6 ,qA6669%001B1BCCII 2%a++%a++%a++,  N '22?3D3DEEIs9~~r4   c                 $   t          j        |t          j        |||                    }|"|                    t	                                }n7t          j        ||          }|                    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.
        ro   rs   Nr   )r   r}   r~   r|   r   r   r   )	r[   rt   rp   rq   rr   r   r2  r3  r4  s	            r5   r   zKey._fromDSAComponents?  s    . ,3#:Q!q#I#I#I
 
 
 9%001B1BCCII 2Q}UUUN&22?3D3DEEIs9~~r4   c                    t          j        ||t          |                   }|"|                    t	                                }n7t          j        ||          }|                    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}
        r   rt   r   N)private_valuer   )r   EllipticCurvePublicNumbersr   r|   r   EllipticCurvePrivateNumbersr   )r[   r   rt   r   r   r2  r3  r4  s           r5   _fromECComponentszKey._fromECComponentsb  s    $ 51K.
 
 
 %001B1BCCII;*=  N '22?3D3DEEIs9~~r4   c                     |,t           j                            t          |         |          }n-t          j        |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}
        )r   r   r   r   derive_private_keyr   )r[   r   r   r   r3  s        r5   r   zKey._fromECEncodedPoint  sd      1DDE"L II -k%0/2C2C I s9~~r4   c                     t           t          t          d          |t          j        |          }nt          j        |          } | |          S )a  Build a key from Ed25519 components.

        @param a: The Ed25519 public key, as defined in RFC 8032 section
            5.1.5.
        @type a: L{bytes}

        @param k: The Ed25519 private key, as defined in RFC 8032 section
            5.1.5.
        @type k: L{bytes}
        Nz)Ed25519 keys not supported on this system)r*   r+   r-   from_public_bytesfrom_private_bytes)r[   r   r   r3  s       r5   r   zKey._fromEd25519Components  sT     #'8'@IJJJ9(:1==II)<Q??Is9~~r4   c                     || _         dS )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)selfr3  s     r5   __init__zKey.__init__  s     $r4   otherreturnc                     t          |t                    rT|                                 |                                k    o)|                                 |                                k    S t          S )zN
        Return True if other represents an object with the same key.
        )rL   rU   r]   ri   NotImplemented)rC  rE  s     r5   __eq__z
Key.__eq__  sQ     eS!! 	"99;;%**,,.N499;;%**,,3NN!!r4   c                 j   |                                  dk    r|                                 }|d                             d          }|                                 rd|dd          d}nd|dd          d}t	          |                                          D ]\  }}|dk    r	|d	| z  }|d
| d| z  } |dz   S dt          |                                            d|                                 rdpdd|                                 dg}t	          |                                                                           D ]\  }}|                    d| d           |                                  dk    r|nt          j
        |          dd         }|ru|dd         }|dd         }d}	t          |          D ]}
|	t          |
          ddz   }	t          |          dk     r
|	dd         }	|                    d|	z              |u|d         dz   |d<   d
                    |          S )z@
        Return a pretty representation of this object.
        ECr   ra   z<Elliptic Curve Public Key (Nz bits)z<Elliptic Curve Private Key (z	
curve:
	
z:
	z>
< z
Public KeyzPrivate Keyz (zattr :Ed25519rn       02xr   	>)r]   ri   r   isPublicsorteditemsr"   sizeappendr   MPr!   r   r   r   )rC  ri   r   outr   vr   bymorI   s              r5   __repr__zKey.__repr__  so    99;;$99;;D=''00D}} HFT"##YFFFGd233iGGGtzz||,, , ,1<<0$000CC++++++CC; ( !----MMOO4EEEIIKKKK	E tyy{{002233 + +1\Q\\\***))++22QQ	!QRR8H +3B3ABCCBA&q\\ 1 13q66 0 0 0 001vv{{crcFLL***  + b	CE"I99U###r4   c                     t          | j        t          j        t          j        t          j        t          j	        f          S )zl
        Check if this instance is a public key.

        @return: C{True} if this is a public key.
        )
rL   rB  r   RSAPublicKeyr   DSAPublicKeyr   r   r   r*   rC  s    r5   rW  zKey.isPublic  s8     O  )(	
 
 	
r4   c                 z    |                                  r| S t          | j                                                  S )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.
        )rW  rU   rB  r|   rf  s    r5   publicz
Key.public  s5     ==?? 	5Kt1133444r4   c                    |t           j        u rMt          t          t	          |                                                                                               S |t           j        u rjt          d                    d t          t          |                                                                                     D                                 S t          d|           )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}
           :c                 6    g | ]}t          j        |          S r3   )binasciihexlifyrH   r   s     r5   
<listcomp>z#Key.fingerprint.<locals>.<listcomp>4  s#    WWWQX%a((WWWr4   z Unsupported fingerprint format: )r>   r@   r"   r   r   r   r   r?   r   r!   r   r<   )rC  formats     r5   fingerprintzKey.fingerprint  s    : '555	&*=*=*D*D*F*F G GHHH)111		WW)C		<L<L<S<S<U<U2V2VWWW    ''R&'R'RSSSr4   c                    t          | j        t          j        t          j        f          rdS t          | j        t
          j        t
          j        f          rdS t          | j        t          j	        t          j
        f          rdS t          | j        t          j        t          j        f          rdS t          d| j                  )z
        Return the type of the object we wrap.  Currently this can only be
        'RSA', 'DSA', 'EC', or 'Ed25519'.

        @rtype: L{str}
        @raises RuntimeError: If the object type is unknown.
        RSADSArK  rQ  zunknown type of object: )rL   rB  r   rd  RSAPrivateKeyr   re  DSAPrivateKeyr   r   EllipticCurvePrivateKeyr   r*   r+   RuntimeErrorrf  s    r5   r]   zKey.type:  s     do(8#:K'LMM 	O5#*:C<M)NOO 	O5Ob79ST
 
 		O 4Og68QR
 
 	O 9M$/MMNNNr4   c                     |                                  dk    r2dt          | j        j        j                            d                   z   S dddd|                                           S )a  
        Get the type of the object we wrap as defined in the SSH protocol,
        defined in RFC 4253, Section 6.6 and RFC 8332, section 4 (this is a
        public key format name, not a public key algorithm name). Currently
        this can only be b'ssh-rsa', b'ssh-dss', b'ecdsa-sha2-[identifier]'
        or b'ssh-ed25519'.

        identifier is the standard NIST curve name

        @return: The key type format.
        @rtype: L{bytes}
        rK  r$  r   rl   rm   rw   )rs  rt  rQ  )r]   r   rB  r   r   rP   rf  s    r5   sshTypezKey.sshTypeQ  sk     99;;$DO,A,F,M,Mg,V,V!WW
 "!)  iikk	 r4   c                 d    |                                  dk    rg dS |                                 gS )z
        Get the public key signature algorithms supported by this key.

        @return: A list of supported public key signature algorithm names.
        @rtype: L{list} of L{bytes}
        rs  )   rsa-sha2-512   rsa-sha2-256rl   )r]   rz  rf  s    r5   supportedSignatureAlgorithmsz Key.supportedSignatureAlgorithmsi  s4     99;;%AAAALLNN##r4   c                     |                                  dk    rs||                                 k    rY|                                 }|dk    rt          j                    S |dk    rt          j                    S t          j                    S dS t          j                    t          j                    t          j                    t          j                    t          j                    d                    |                                  |f          S )z
        Return a hash algorithm for this key type given an SSH signature
        algorithm name, or L{None} if no such hash algorithm is defined for
        this key type.
        rK     i  N))rs  rl   )rs  r}  )rs  r|  )rt  rm   )rQ  rw   )	r]   rz  rZ  r   SHA256SHA384SHA512SHA1get)rC  signatureTyper   s      r5   _getHashAlgorithmzKey._getHashAlgorithmu  s     99;;$..))++c>>!=??*^^!=??*!=??*t &,[]]*0-//*0-//%+[]]-3]__  c499;;.//0r4   c                     | j         dS |                                 dk    r| j         j        j        S |                                 dk    rdS | j         j        S )zv
        Return the size of the object we wrap.

        @return: The size of the key.
        @rtype: L{int}
        Nr   rK  rQ  r  )rB  r]   r   key_sizerf  s    r5   rZ  zKey.size  sU     ?"1YY[[D  ?(11YY[[I%%3''r4   c           	      $   t          | j        t          j                  r(| j                                        }|j        |j        dS t          | j        t          j                  rb| j                                        }|j        j        |j        j        |j	        |j
        |j        t          j        |j        |j
                  dS t          | j        t          j                  rC| j                                        }|j        |j        j        |j        j
        |j        j        dS t          | j        t          j                  r]| j                                        }|j        |j        j        |j        j        j        |j        j        j
        |j        j        j        dS t          | j        t(          j                  r;| j                                        }|j        |j        |                                 dS t          | j        t(          j                  rK| j                                        }|j        j        |j        j        |j        |                                 dS t          | j        t2          j                  r;d| j                            t8          j        j        t8          j        j                  iS t          | j        t2          j                   r| j        !                                                    t8          j        j        t8          j        j                  | j        "                    t8          j        j        t8          j#        j        t9          j$                              dS tK          d	| j                   )
z_
        Return the values of the public key as a dictionary.

        @rtype: L{dict}
        r  r!  r  )r   rt   rr   rp   rq   r7  )r   rt   r   r   r   )r   r   zUnexpected key type: )&rL   rB  r   rd  r   r   r   ru  private_numbersr   rp   rq   r1  r   re  rt   ru   rr   rv  r   r   r   rz  rw  r8  r   r*   public_bytesr   EncodingRawPublicFormatr+   r|   private_bytesPrivateFormatNoEncryptionrx  )rC  numberss     r5   ri   zKey.data  s+    dos'788 D	Jo4466GYY   ):;; >	Jo5577G+-+-YYY%gi;;   )9:: 3	Jo4466GY.0.0.0	   ):;; +	Jo5577GY+-+=?+=?+=?   )BCC "	Jo4466GYY  
 )CDD 	Jo5577G+-+- ' 5	   )ABB 	JT_11!*.0J0N  
 )BCC 	J_//11>>!*.0J0N  _22!*.!/3!.00 		 	 	 HtHHIIIr4   c                    |                                  }|                                 }|dk    rJt          j        d          t          j        |d                   z   t          j        |d                   z   S |dk    rt          j        d          t          j        |d                   z   t          j        |d                   z   t          j        |d	                   z   t          j        |d
                   z   S |dk    r| j        j        j        dz   dz  }t          j        |d                   t          j        |d         dd                   z   t          j        dt          j	        |d         |          z   t          j	        |d
         |          z             z   S |dk    r/t          j        d          t          j        |d                   z   S t          d|           )a  
        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

        Ed25519 keys::
            string 'ssh-ed25519'
            string a

        @rtype: L{bytes}
        rs  rl   r   r   rt  rm   rp   rq   rr   rt   rK     r   r   N   r   rQ  rw   r   unknown key type: )r]   ri   r   r  r\  rB  r   r  r
   r   r-   )rC  r]   ri   
byteLengths       r5   r   zKey.blob  s   @ yy{{yy{{5==9Z((69T#Y+?+??&)DQTIBVBVVVU]]	*%%)DI&&')DI&&' )DI&&' )DI&&	' T\\//81<BJ	$w-(()DM"##.//0)(cJ??@(cJ??@  Y9^,,vyc/C/CCC9499:::r4   c                    |                                  }|                                 }|dk    rt          j        |d         |d                   }t	          j        d          t	          j        |d                   z   t	          j        |d                   z   t	          j        |d                   z   t	          j        |          z   t	          j        |d                   z   t	          j        |d                   z   S |dk    rt	          j        d	          t	          j        |d                   z   t	          j        |d                   z   t	          j        |d
                   z   t	          j        |d                   z   t	          j        |d                   z   S |dk    r| j                                        	                    t          j        j        t          j        j                  }t	          j        |d                   t	          j        |d         dd                   z   t	          j        |          z   t	          j        |d                   z   S |dk    rSt	          j        d          t	          j        |d                   z   t	          j        |d         |d         z             z   S t          d|           )a1  
        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.

        Ed25519 keys::

            string 'ssh-ed25519'
            string a
            string k || a
        rs  rp   rq   rl   r   r   r   rt  rm   rr   rt   r   rK  r   r  Nr   rQ  rw   r   r   r  )r]   ri   r   r1  r   r  r\  rB  r|   r  r   r  X962r  UncompressedPointr-   )rC  r]   ri   r   encPubs        r5   privateBlobzKey.privateBlob'  sz   R yy{{yy{{5==#DItCy99D	*%%)DI&&')DI&&' )DI&&' )D//	"
 )DI&&' )DI&&' U]]	*%%)DI&&')DI&&' )DI&&' )DI&&	'
 )DI&&' T\\_//11>>&+*< F
 	$w-(()DM"##.//0)F##$ )D0112 Y	.)))DI&&')DIS	1223 9499:::r4   extracommentrR   c                 r   |5t          j        dt          d           |                                 r|}n|}t	          |t
                    r|                    d          }t          |          }t          | d|	                                 d          }|t          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}
        NzThe 'extra' argument to twisted.conch.ssh.keys.Key.toString was deprecated in Twisted 20.3.0; use 'comment' or 'passphrase' instead.r   )
stacklevelra   
_toString_r  )subtyper  rR   )warningswarnDeprecationWarningrW  rL   rM   rP   rS   re   rf   r-   )rC  r]   r  r  r  rR   rj   s          r5   toStringzKey.toStringz  s    Z MI #    }} #"
gs## 	.nnW--G)*55
:DJJLL::DAA>9499:::vgw:NNNNr4   c                    |                                  dk    rU|sd}| j                            t          j        j        t          j        j                  dz   |z                                   S t          | 	                                          
                    dd          }|sd}|                                 dz   |z   dz   |z                                   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.
        rK  r4   r      
)r]   rB  r  r   r  OpenSSHr  r   r   r   replacerz  )rC  r  r   s      r5   _toPublicOpenSSHzKey._toPublicOpenSSH  s     99;;$ ,,!*2M4N4V   	
 egg diikk**225#>> 	G%/$6@GGIIIr4   c           	      0   |r_t           j        }d}d}|j        dz  }d}|}t          j        |          }	d}
t          j        |	          t          j        d|
          z   }nd}d}d}d}t          j        d	          }||z   | 	                                z   t          j        |pd          z   }d
}t          |          |z  r-|dz  }|t          |dz  f          z  }t          |          |z  -|rt          j        ||	||z   d          }t           ||d|                   t          j        ||||z                      t#                                                                }|                    |          |                                z   }n|}dt          j        |          z   t          j        |          z   t          j        |          z   t          j        dd          z   t          j        |                                           z   t          j        |          z   }t-          |                              dd          dgfdt1          d
t                    d          D             z   dgz   }d                    |          dz   S )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.
        r   r   r   r   d   r   r   r4   rn   r   rv      Nr   r   r  s#   -----BEGIN OPENSSH PRIVATE KEY-----c                 *    g | ]}||d z            S @   r3   rH   r   r   s     r5   ro  z,Key._toPrivateOpenSSH_v1.<locals>.<listcomp>  s&    GGGqwq1r6z"GGGr4   r  s!   -----END OPENSSH PRIVATE KEY-----)r   r   
block_sizer    secureRandomr   r  r   packr  r   r   r   r   r   r   r   r   	encryptorr   r   r   r   r  r   r   )rC  r  rR   r   
cipherNamekdfNamer   r   r   r   r   r   checkr   padByteencKeyr  r   r   r   r   s                       @r5   _toPrivateOpenSSH_v1zKey._toPrivateOpenSSH_v1  s     	  ^F&JG)Q.IGF)&11DF46;tV+D+DDJJ JGIJ&q))emd&6&6&8&8869W^PS;T;TT+* 	4qLG5'D.!2333K +* 	4  		)Z
D'F2BCHHFvhwh'((	&7V+;!;<=='))   ikk	 
 '--k::Y=O=O=Q=QQNN(Ni
##$i  ! i
##$ k$""	#
 i		$$% i''( 	 d##++E37734GGGGE!S\\2,F,FGGGH345 	
 zz%  5((r4   c           
         |                                  dk    rd|st          j                    }nt          j        |          }| j                            t          j        j        t          j        j	        |          S |                                  dk    rt          d          |                                 }d                    d|                                                      d          df          g}|                                  dk    r[|d	         |d
         }}t          j        ||          }d|d         |d         |d         |||d         |dz
  z  |d         |dz
  z  |f	}n&d|d	         |d
         |d         |d         |d         f}t!          j                    }	t%          t'          j                    |          D ]-\  }
}|	                    |
t!          j        |                     .t/          j        |	          }|rt1          j        d          }d                    d t5          |          D                       }|                    d          }|                    d           |                    d|z   dz              t9          ||z                                             }t9          ||z   |z                                             }||z   dd         }dt=          |          dz  z
  }|t?          |f          |z  z  }tA          tC          j"        |          tG          j$        |          tK                                &                                }|'                    |          |(                                z   }tS          |          *                    dd          |fdtW          dt=                    d          D             z  }|                    d                    d|                                                      d          df                     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.
        rK  rQ  zBcannot serialize Ed25519 key to OpenSSH PEM format; use v1 insteadr4   s   -----BEGIN r   s    PRIVATE KEY-----rs  rp   rq   r   r   r   r   rv   rr   rt   r   r   rS  c                 0    g | ]}t          |          d S )02X)r   rn  s     r5   ro  z-Key._toPrivateOpenSSH_PEM.<locals>.<listcomp>L  s"    DDDA__DDDr4   r   s   DEK-Info: DES-EDE3-CBC,r  Nr   r   c                 *    g | ]}||d z            S r  r3   r  s     r5   ro  z-Key._toPrivateOpenSSH_PEM.<locals>.<listcomp>]  s&    JJJ!'!a"f*%JJJr4   r  s	   -----END ),r]   r   r  BestAvailableEncryptionrB  r  r  PEMr  TraditionalOpenSSLr   ri   r   rP   r   r1  r   Sequencezip	itertoolsr-  setComponentByPositionInteger
berEncoderr    r  r!   r[  r   r   r   r   r   r   r   r   r   r   r  r   r   r   r  r   )rC  rR   r  ri   r   rp   rq   r   objDataasn1Sequenceindexr   asn1Datar   hexivr   r   r  padLenr   s                      @r5   _toPrivateOpenSSH_PEMzKey._toPrivateOpenSSH_PEM  s    99;;$ N)688		)A*MM	?00&*+>  
 YY[[I%%W   yy{{HH!3!3G!<!<>RS 

 99;;%9d3iqA#Aq))DS	S	S	S	QU#S	QU#
GG $s)T#YS	49d3iPG}	 1 17;; 	L 	LLE5//t|E7J7JKKKK$\22 	I'**BGGDDimmDDDEEELL))ELL2333LL3e;eCDDDZ"_%%,,..BR*_r)**1133B2gss^F#h--!+,Fvi((611H$V,,eimm_EVEV  ikk  !''11I4F4F4H4HHHh''//s;;JJJJuQGb/I/IJJJJHHlDIIKK$6$6w$?$?AUVWW	
 	
 	
 zz%   r4   c                 $   |                                  r|                     |          S |dk    s|/|                                 dk    r|                     ||          S ||dk    r|                     |          S t          d|           )	ar  
        Return a public or private OpenSSH string.  See
        L{_fromString_PUBLIC_OPENSSH} and L{_fromPrivateOpenSSH_PEM} for the
        string formats.

        @param subtype: A subtype to emit.  Only supported for private 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: Comment for a public key.
        @type comment: L{bytes}

        @param passphrase: Passphrase for a private key.
        @type passphrase: L{bytes}

        @rtype: L{bytes}
        )r  v1NrQ  )r  rR   r  rQ   zunknown subtype )rW  r  r]   r  r  r   )rC  r  r  rR   s       r5   _toString_OPENSSHzKey._toString_OPENSSHc  s    & ==?? 	;(((999__TYY[[I5M5M,,W,TTT_5 0 0---DDD999:::r4   c                 ~   |                                  }|                                 }|                                 rK|dk    r_t          j        dddt          j        |d                   dd         gdt          j        |d	                   dd         gggg          }n|d
k    rt          j        dddt          j        |d                   dd         gdt          j        |d                   dd         gdt          j        |d                   dd         gdt          j        |d                   dd         gggg          }nt          d|           dt          |          	                    dd          z   dz   S |dk    rO|d         |d         }}t          j        ||          }t          j        dddt          j        |d                   dd         gdt          j        |d	                   dd         gdt          j        |d                   dd         gdt          j        |          dd         gdt          j        |          dd         gdt          j        |d         |dz
  z            dd         gdt          j        |d         |dz
  z            dd         gd t          j        |          dd         gg	gg          S |d
k    rt          j        dddt          j        |d                   dd         gdt          j        |d                   dd         gdt          j        |d                   dd         gdt          j        |d                   dd         gd!t          j        |d"                   dd         gggg          S t          d| d#          )$z
        Return a public or private LSH key.  See _fromString_PUBLIC_LSH and
        _fromString_PRIVATE_LSH for the key formats.

        @rtype: L{bytes}
        rs  r  r  r  r   rn   Nr  r   rt  r	  r  rp   r  rq   r  rr   r
  rt   r   r'  r  r4      }r  r  r  r      arv      b   cr  r   ')ri   r]   rW  r   r  r   r\  r-   r   r  r   r1  )rC  kwargsri   r]   r   rp   rq   r   s           r5   _toString_LSHzKey._toString_LSH  s    yy{{yy{{==?? G	?u}}* * 1!%vyc';';ABB'? @!%vyc';';ABB'? @	  * * &!%vyc';';ABB'? @!%vyc';';ABB'? @!%vyc';';ABB'? @!%vyc';';ABB'? @	  ""<d"<"<===+g..66ucBBBTIIu}}Cy$s)1'1--z + ,!%vyc';';ABB'? @!%vyc';';ABB'? @!%vyc';';ABB'? @!%vy||ABB'7 8!%vy||ABB'7 8!%vyca!e1D'E'Eabb'I J!%vyca!e1D'E'Eabb'I J!%vyqrr': ;
  $ z + &!%vyc';';ABB'? @!%vyc';';ABB'? @!%vyc';';ABB'? @!%vyc';';ABB'? @!%vyc';';ABB'? @
    ""=d"="="=>>>r4   c                    |                                  }|                                 s|                                 dk    r-|d         |d         |d         |d         |d         |d         f}n=|                                 dk    r%|d         |d         |d	         |d
         |d         f}t          j        |                                           d                    t          t          j        |                    z   S dS )z
        Return a private Secure Shell Agent v3 key.  See
        _fromString_AGENTV3 for the key format.

        @rtype: L{bytes}
        rs  r   r   r   r   rp   rq   rt  rr   rt   r   r4   N)	ri   rW  r]   r   r  rz  r   mapr\  )rC  r  ri   valuess       r5   _toString_AGENTV3zKey._toString_AGENTV3  s     yy{{}} 	Pyy{{e##IIIIII %%s)T#YS	49d3iP9T\\^^,,sxxFIv8N8N/O/OOO	P 	Pr4   c                    |                                  }||                                 }|                     |          }|t          d| d| d          |dk    rC| j                            |t          j                    |          }t          j	        |          }n|dk    rb| j                            ||          }t          |          \  }}t          j	        t          |d          t          |d          z             }nZ|dk    r!| j                            |t          j        |                    }	t          |	          \  }}t          |          }
t          |          }t          |
d	                   t          u rt          |
d	                   }n|
d	         }|d
z  rd|
z   }
t          |d	                   t          u rt          |d	                   }n|d	         }|d
z  rd|z   }t          j	        t          j	        |
          t          j	        |          z             }n2|dk    r,t          j	        | j                            |                    }t          j	        |          |z   S )a  
        Sign some data with this key.

        SECSH-TRANS RFC 4253 Section 6.6.

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

        @type signatureType: L{bytes}
        @param signatureType: The SSH public key algorithm name to sign this
        data with, or L{None} to use a reasonable default for the key.

        @rtype: L{bytes}
        @return: A signature for the given data.
        Nzpublic key signature algorithm z is not defined for z keysrs  rt     rK  r          rQ  )r]   rz  r  r7   rB  signr   PKCS1v15r   r  r&   r   r   ECDSArM   r   )rC  ri   r  r   hashAlgorithmsigretrs	signaturerW   sbrcompscomps                 r5   r  zKey.sign  sS     ))++ 
 !LLNNM..}== ,.- . .&. . .  
 e/&&tW-=-?-?OOC)C..CC/&&t];;C)#..FQ
 )LB//,q"2E2EEFFCC__,,T28M3J3JKKI))44FQaBaB BqE{{c!!BqE

1 t| "r\BqE{{c!!BqE

1t| "r\)FIbMMFIbMM9::CC	!!)DO006677Cy''#--r4   c                 l   t          |          dk    rdt          j        |          }}nt          j        |          \  }}|                     |          }|dS |                                 }|dk    r`| j        }|                                 s|                                }t          j        |          d         |t          j
                    |f}n|dk    rt          j        |          d         }t                              |dd         d	          }	t                              |dd         d	          }
t          |	|
          }| j        }|                                 s|                                }|||f}n|d
k    rt          j        |          d         }t          j        |d          \  }}}t                              |d	          }	t                              |d	          }
t          |	|
          }| j        }|                                 s|                                }||t          j        |          f}nQ|dk    rK| j        }|                                 s|                                }t          j        |          d         |f}	  |j        |  dS # t"          $ r Y dS w xY w)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.
        (   rm   NFrs  r   rt  r  bigrK  rc   rQ  T)r   r   r  ry   r  r]   rB  rW  r|   r   r  r   
from_bytesr'   r   r  verifyr   )rC  r  ri   r  r  r   r   argsconcatenatedSignaturer  r  rstrsstrr   s                 r5   r  z
Key.verify4  s    y>>R'169Y3G3G9MM'-|I'>'>$M9..}== 5))++eA==?? #LLNNY''* ""	DD $*L$;$;A$>!4SbS95AAA4RSS95AAA,Q22IA==?? #LLNNt]3DD__$*L$;$;A$>!%|,A1EED$tU++AtU++A,Q22IA==?? #LLNNtRXm%<%<=DD	!!A==?? #LLNNL++A.5D	AHdOO 4   	 	 	55	s   
J% %
J32J3)NN)NNNNr   )NNN)3r/   r0   r1   r2   classmethodr_   rY   r   r   r   r   r  r  r  r  r"  rd   r   r   r;  r   r   rD  objectboolrI  rM   rb  rW  rh  r>   r?   rq  r]   rz  r~  r  rZ  ri   r   r  r%   r  r  r  r  r  r  r  r  r  r3   r4   r5   rU   rU      s0         > > > [>( %, %, %, [%,N 6? 6? [6?p H? H? [H?T * * [*( V= V= [V=p {: {: [{:z A A [A8 D D [D> #D #D [#DJ .= .= [.=`   [> * * * [*X       [ D    [>    [6    [,$ $ $"F "t " " " "*$# *$ *$ *$ *$X
 
 
 5 5 5 "4!; &T &T &T &TPO O O.  0
$ 
$ 
$0 0 06( ( (JJ JJ JJX:; :; :;xQ; Q; Q;f ! i l#	
 :O :O :O :OxJ J J J4<) <) <) <)|M! M! M! M!^; ; ; ;:P? P? P?dP P P,J. J. J. J.XD D D D Dr4   rU      c                 ^   |                                                      d           |                                 st          j        d|t                                }|                    t          j        j	        t          j
        j        t          j                              }|                     |           |                     d          5 }t          j        |                                dt                                }t#          |          cddd           S # 1 swxY w Y   dS )	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)ignoreExistingDirectoryi  )public_exponentr  r   )encodingrp  encryption_algorithmrW   N)passwordr   )parentmakedirsexistsr   generate_private_keyr   r  r   r  r  r  r  r  
setContentrX   r   rZ   rU   )locationr   
privateKeypemkeyFiles        r5   _getPersistentRSAKeyr  {  sY     OOt<<< ?? !-!G_=N=N
 
 

 &&"+/ .A!.!;!=!= ' 
 
 	C    
t		 "7LLNNT?3D3D
 
 

 :	                 s   AD""D&)D&)r  )Yr2   rl  r  r   rF   r  base64r   r   r   hashlibr   r   typingr   r	   r   cryptographyr
   cryptography.exceptionsr   cryptography.hazmat.backendsr   cryptography.hazmat.primitivesr   r   )cryptography.hazmat.primitives.asymmetricr   r   r   r   r   &cryptography.hazmat.primitives.ciphersr   r   r   ,cryptography.hazmat.primitives.serializationr   r   pyasn1.codec.berr   r   r   r  pyasn1.errorr   pyasn1.typer   twisted.conch.sshr   r   twisted.conch.ssh.commonr   twisted.pythonr    twisted.python.compatr!   r"   twisted.python.constantsr#   r$   twisted.python.deprecater%   /cryptography.hazmat.primitives.asymmetric.utilsr&   r'   ImportErrorr(   r)   	SECP256R1	SECP384R1	SECP521R1r   r   r*   __annotations__r+   ed25519_supportedtwisted.conch.ssh._keys_pynacl	Exceptionr-   r7   r:   r<   r>   rB   rS   rU   r  r3   r4   r5   <module>r+     s  
  
            6 6 6 6 6 6 6 6 6 6         ! ! ! ! ! ! ! !        4 4 4 4 4 4 8 8 8 8 8 8 @ @ @ @ @ @ @ @ T T T T T T T T T T T T T T L L L L L L L L L L               % $ $ $ $ $       + + + + + + + + 1 1 1 1 1 1 $ $ $ $ $ $ 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 @ @ @ @ @ @
                      )BLNN(BLNN(BLNN   
 4 89: : : :D!:;< < < <?&&(( !/1!VVVVVVVVV ! ! ! !
    )              	       9   $ $ $ $ $ $ $ $"    9     >P P P P P P P Pf6( ( ( ( ( (s$   /B8 8CCE 	E+*E+