
    ,h                        d dl mZ d dlZd dlZd dlZd dlmZmZmZm	Z	m
Z
 d dlmZ d dl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 d	d
lmZmZmZ d	dlmZ   G d de!      Z" G d de#      Z$d Z%d Z&d'dZ'd Z(d(dZ)d Z*d Z+d Z,d Z-d Z.d Z/d Z0d Z1d Z2d'dZ3e4dk(  rd dl5Z5d Z6ed!   jn                  jq                         Z9d"Z: e5jj                         Z; e<e:      D ]  Z=e9e6z  Z>	  e?d# e5jj                         e;z
  e:z  d$z  d%        e5jj                         Z; e<e:      D ]  Z=e>e6z  Z>	  e?d& e5jj                         e;z
  e:z  d$z  d%       yy))    )print_functionN)bordtobytestostrbchr	is_string)Integer)DerObjectIdDerOctetStringDerSequenceDerBitString)_expand_subject_public_key_info_create_subject_public_key_info _extract_subject_public_key_info)SHA512SHAKE256)get_random_bytes   )EccPoint	EccXPoint_curves)CurveIDc                       e Zd Zy)UnsupportedEccFeatureN)__name__
__module____qualname__     V/var/www/html/Resume-Scraper/venv/lib/python3.12/site-packages/Crypto/PublicKey/ECC.pyr   r   7   s    r   r   c                       e Zd ZdZd Zd Zd Zd Zd Zd Z	e
d        Ze
d	        Ze
d
        Zd Zd Zd Zd Zd ZddZd Zd Zd Zd Zd Zd Zd Zy)EccKeya  Class defining an ECC key.
    Do not instantiate directly.
    Use :func:`generate`, :func:`construct` or :func:`import_key` instead.

    :ivar curve: The **canonical** name of the curve as defined in the `ECC table`_.
    :vartype curve: string

    :ivar pointQ: an ECC point representating the public component.
    :vartype pointQ: :class:`EccPoint` or :class:`EccXPoint`

    :ivar d: A scalar that represents the private component
             in NIST P curves. It is smaller than the
             order of the generator point.
    :vartype d: integer

    :ivar seed: A seed that representats the private component
                in Ed22519 (32 bytes), Curve25519 (32 bytes),
                Curve448 (56 bytes), Ed448 (57 bytes).
    :vartype seed: bytes
    c                 	   t        |      }|j                  dd      }|j                  dd      | _        |j                  dd      | _        |j                  dd      | _        |"| j                  r| j                  j
                  }|rt        dt        |      z         |t        vrt        d|z        t        |   | _
        | j                  j                  | _        t        | j                  du      t        | j                  du      z   }|dk(  r| j                  t        d	      y|d
k(  rt        d      | j                  j                  t        j                  k(  r| j                  t        d      t!        | j                        dk7  rt        d      t#        j$                  | j                        j'                         }|dd | _        t+        |dd       }|dxx   dz  cc<   |d   dz  dz  |d<   t-        j.                  |d      | _        y| j                  j                  t        j0                  k(  r| j                  t        d      t!        | j                        dk7  rt        d      t3        j$                  | j                        j5                  d      }|dd | _        t+        |dd       }|dxx   dz  cc<   |dxx   dz  cc<   d|d<   t-        j.                  |d      | _        y| j                  j                  t        j6                  k(  r| j                  t        d      t!        | j                        dk7  rt        d      t+        | j                        }|dxx   dz  cc<   |d   dz  dz  |d<   t-        j.                  |d      | _        y| j                  j                  t        j8                  k(  r| j                  t        d      t!        | j                        dk7  rt        d      t+        | j                        }|dxx   dz  cc<   |dxx   dz  cc<   t-        j.                  |d      | _        y| j                  t        d      t-        | j                        | _        d| j                  cxk  r#| j                  j:                  k  st        d        t        d       y)!a  Create a new ECC key

        Keywords:
          curve : string
            The name of the curve.
          d : integer
            Mandatory for a private key one NIST P curves.
            It must be in the range ``[1..order-1]``.
          seed : bytes
            Mandatory for a private key on Ed25519 (32 bytes),
            Curve25519 (32 bytes), Curve448 (56 bytes) or Ed448 (57 bytes).
          point : EccPoint or EccXPoint
            Mandatory for a public key. If provided for a private key,
            the implementation will NOT check whether it matches ``d``.

        Only one parameter among ``d``, ``seed`` or ``point`` may be used.
        curveNdseedpointUnknown parameters: zUnsupported curve (%s)r   zGAt lest one between parameters 'point', 'd' or 'seed' must be specified   z,Parameters d and seed are mutually exclusivez/Parameter d can only be used with NIST P curves    z0Parameter seed must be 32 bytes long for Ed25519         @   little	byteorder9   z.Parameter seed must be 57 bytes long for Ed448r      7      8   z3Parameter seed must be 32 bytes long for Curve25519z1Parameter seed must be 56 bytes long for Curve448z2Parameter 'seed' cannot be used with NIST P-curvesr   z;Parameter d must be an integer smaller than the curve order)dictpop_d_seed_pointr$   	TypeErrorstrr   
ValueError_curve	canonicalintid_CurveIDED25519lenr   newdigest_prefix	bytearrayr	   
from_bytesED448r   read
CURVE25519CURVE448order)selfkwargskwargs_
curve_namecount	seed_hashtmps          r    __init__zEccKey.__init__Q   s   & v,[[$/
++c4([[.
kk'40$++**J2S\ABBW$5
BCCj)[[**
DGG4'(3tzz/E+FFA:{{" !jkkA:KLL
 ;;>>X---ww" !RSS4::"$ !STT

4::.557I$RS>DLIcrN+CFdNF2w~-CG((ADG[[^^x~~-ww" !RSS4::"$ !QRR TZZ055c:I$RS>DLIcrN+CFdNFGtOGCG((ADG[[^^x222ww" !RSS4::"$ !VWWDJJ'CFdNF2w~-CG((ADG[[^^x000ww" !RSS4::"$ !TUUDJJ'CFdNFGtOG((ADG zz% !UVVdgg&DG3$++"3"33 !^__ 4 !^__ 4r   c                     t        |t              sy|j                         | j                         k7  ry|j                  | j                  k(  S )NF)
isinstancer"   has_privatepointQ)rQ   others     r    __eq__zEccKey.__eq__   s?    %($"2"2"44||t{{**r   c                     | j                         r[| j                  j                  r,dt        t	        j
                  | j                              z  }ndt        | j                        z  }nd}| j                  j                  t        j                  t        j                  fv r4| j                  j                  }d| j                  j                  ||fz  }|S | j                  j                   \  }}d| j                  j                  |||fz  }|S )Nz	, seed=%sz, d=%d z EccKey(curve='%s', point_x=%d%s)z,EccKey(curve='%s', point_x=%d, point_y=%d%s))r[   r@   
is_edwardsr   binasciihexlifyr;   rB   r:   rC   rD   rN   rO   r\   xrA   xy)rQ   extrard   resultys        r    __repr__zEccKey.__repr__   s    {{%%#eH,<,<TZZ,H&II 3tww</E;;>>h11&//1 1A74;;;P;PRSUZ:[[F  ;;>>DAqCt{{G\G\^_abdiFjjFr   c                     | j                   duS )zJ``True`` if this key can be used for making signatures or decrypting data.N)r:   rQ   s    r    r[   zEccKey.has_private   s     wwd""r   c                 `   d|cxk  r| j                   j                  k  sJ  J | j                   j                  }t        j                  d|      }| j                  |z  }||z  j                  |      }| j                   j                  |z  j                  |z  }|||z  ||z  z   z  |z  }||fS )Nr   r   )min_inclusivemax_exclusive)r@   rP   r	   random_ranger:   inverseGrd   )	rQ   zkrP   blindblind_dinv_blind_krss	            r    _signzEccKey._sign   s    1(t{{((((((!!$$138: ''E/qy))%0[[]]Q!!E)519w{23e;1vr   c                     | j                   j                  }|d   j                  |      }| j                   j                  ||z  |z  z  }| j                  ||d   z  |z  z  }||z   j
                  |d   k(  S )Nr   r   )r@   rP   rp   rq   r\   rd   )rQ   rr   rsrP   sinvpoint1point2s          r    _verifyzEccKey._verify   sr    !!!u}}U#4!8u"451 67""be++r   c                 P    | j                         st        d      | j                  S NzThis is not a private ECC key)r[   r?   r:   rk   s    r    r%   zEccKey.d   s#    !<==wwr   c                 P    | j                         st        d      | j                  S r   )r[   r?   r;   rk   s    r    r&   zEccKey.seed   s$    !<==zzr   c                     | j                   (| j                  j                  | j                  z  | _         | j                   S N)r<   r@   rq   r:   rk   s    r    r\   zEccKey.pointQ   s.    ;;++--$''1DK{{r   c                 X    t        | j                  j                  | j                        S )z^A matching ECC public key.

        Returns:
            a new :class:`EccKey` object
        )r$   r'   )r"   r@   rA   r\   rk   s    r    
public_keyzEccKey.public_key   s     DKK11EEr   c                    | j                   j                  st        d      | j                  j	                         }|rS| j                  j
                  j                         rd}nd}|| j                  j                  j                  |      z   }|S d| j                  j                  j                  |      z   | j                  j
                  j                  |      z   }|S )Nz/SEC1 format is only supported for NIST P curves         )	r@   is_weierstrassr?   r\   size_in_bytesrh   is_oddrd   to_bytes)rQ   compressmodulus_bytes
first_byter   s        r    _export_SEC1zEccKey._export_SEC1  s    {{))NOO 113{{}}##%$
$
$++--00?@J  "++--00?@++--00?@J r   c                    | j                   j                  \  }}| j                  j                  t        j
                  k(  r8t        |j                  dd            }|dz  dz  |d   z  |d<   t        |      S | j                  j                  t        j                  k(  r2t        |j                  dd            }|dz  dz  |d<   t        |      S t        d	      )
Nr*   r/   r0   r      r,   r2   r7   zNot an EdDSA key to export)r\   re   r@   rC   rD   rE   rJ   r   rL   r?   bytes)rQ   rd   rh   rg   s       r    _export_eddsa_publiczEccKey._export_eddsa_public   s    {{~~1;;>>X---qzz"zABFq5Q,&*4F2J V} [[^^x~~-qzz"zABFa%AF2J V} 9::r   c                     | j                   j                  st        d      | j                  j                  }| j                  j                         }t        |j                  |d            }t        |      S )NzNot a Montgomery key to exportr/   r0   )	r@   is_montgomeryr?   r\   rd   r   rJ   r   r   )rQ   rd   
field_sizerg   s       r    _export_montgomery_publicz EccKey._export_montgomery_public,  s[    {{((=>>KKMM[[..0
1::jH:EFV}r   c                 |   | j                   j                  r)| j                   j                  }| j                         }d }nq| j                   j                  r)| j                   j                  }| j                         }d }n2d}| j                  |      }t        | j                   j                        }t        |||      S )N1.2.840.10045.2.1)	r@   ra   oidr   r   r   r   r
   r   )rQ   r   r   r   paramss        r    _export_subjectPublicKeyInfoz#EccKey._export_subjectPublicKeyInfo4  s    ;;!!++//C224JF[[&&++//C779JF%C**84J 1F.s/9/57 	7r   c                    | j                         sJ | j                  j                         }d| j                  j                  j	                  |      z   | j                  j
                  j	                  |      z   }dt        | j                  j	                  |            t        | j                  j                  d      t        |d      g}|s|d= t        |      j                         S )Nr   r   r   explicitr)   )r[   r\   r   rd   r   rh   r   r%   r
   r@   r   r   r   encode)rQ   include_ec_paramsr   r   seqs        r    _export_rfc5915_private_derz"EccKey._export_rfc5915_private_derF  s    !! 113kkmm,,];<kkmm,,];<
 dffoom<=4;;??Q7J35
 !A3&&((r   c                 v   ddl m} |j                  dd       d|vrt        d      | j                  <| j
                  j                  }t        | j                        j                         }d }n3d}| j                  d      }t        | j
                  j                        } |j                  ||fd	|i|}|S )
Nr   PKCS8
passphrase
protectionz3At least the 'protection' parameter must be presentr   F)r   
key_params)	Crypto.IOr   getr?   r;   r@   r   r   r   r   r
   wrap)rQ   rR   r   r   private_keyr   rg   s          r    _export_pkcs8zEccKey._export_pkcs8a  s    #::lD)5,f:TRSS::!++//C(4;;=KF%C::U:SK 1FK&'-& %& r   c                 T    ddl m} | j                  |      }|j                  |d      S )Nr   PEMz
PUBLIC KEY)r   r   r   r   )rQ   r   r   encoded_ders       r    _export_public_pemzEccKey._export_public_pemv  s&    !77Azz+|44r   c                 X    ddl m} | j                         } |j                  |d|fi |S )Nr   r   zEC PRIVATE KEY)r   r   r   r   rQ   r   rR   r   r   s        r    _export_private_pemzEccKey._export_private_pem|  s.    !668szz+'7NvNNr   c                 R    ddl m} | j                         }|j                  |d      S )Nr   r   zPRIVATE KEY)r   r   r   r   )rQ   r   r   s      r    (_export_private_clear_pkcs8_in_clear_pemz/EccKey._export_private_clear_pkcs8_in_clear_pem  s$    !((*zz+}55r   c                     ddl m} |sJ d|vrt        d       | j                  dd|i|}|j	                  |d      S )Nr   r   r   z5At least the 'protection' parameter should be presentr   zENCRYPTED PRIVATE KEYr   )r   r   r?   r   r   r   s        r    ,_export_private_encrypted_pkcs8_in_clear_pemz3EccKey._export_private_encrypted_pkcs8_in_clear_pem  sK    !v%TUU(d((IJI&Izz+'>??r   c                    | j                         rt        d      | j                  j                  }|t        d| j                  z        |dk(  r'| j                         }t        |      t        |      f}n| j                  j                         }|rYd| j                  j                  j                         z   }t        |      | j                  j                  j                  |      z   }nNd| j                  j                  j                  |      z   | j                  j                  j                  |      z   }|j                  d      d   }t        |      t        |      |f}dj                  |D cg c]$  }t!        j"                  dt%        |            |z   & c}      }	|d	z   t'        t)        j*                  |	            z   S c c}w )
Nz"Cannot export OpenSSH private keysz Cannot export %s keys as OpenSSHssh-ed25519r)   r   -r   >I )r[   r?   r@   opensshr$   r   r   r\   r   rh   r   r   rd   r   splitjoinstructpackrF   r   rb   
b2a_base64)
rQ   r   descr   compsr   r   middlerd   blobs
             r    _export_opensshzEccKey._export_openssh  s{   ABB{{""<?$**LMM]"224JT]GJ$78E KK557M!5!5!77
":."kkmm44]CD
 &"kkmm44]CD"kkmm44]CD
 ZZ_Q'FT]GFOZ@ExxF1T3q62Q6FGczE("5"5d";<<< Gs   5)G	c                 ~   |j                         }|j                  d      }|dvrt        d|z        |j                  dd      }| j                         r#|j                  dd      }t	        |      rt        |      }|st        d      |j                  d	d
      }|du rQ| j                  j                  rt        d      | j                  j                  rt        d      d|v rt        d      |dk(  r:|r%|r | j                  |fi |S | j                         S  | j                  |fi |S |dk(  r5|r|st        d      |r | j                  dd|i|S | j                         S t        d|z        |rt        d|z        |dk(  r| j                  |      S |dk(  r| j                  |      S |dk(  r| j!                  |      S |dk(  r]| j                  j                  r| j#                         S | j                  j                  r| j%                         S | j!                  |      S | j'                  |      S )a  Export this ECC key.

        Args:
          format (string):
            The output format:

            - ``'DER'``. The key will be encoded in ASN.1 DER format (binary).
              For a public key, the ASN.1 ``subjectPublicKeyInfo`` structure
              defined in `RFC5480`_ will be used.
              For a private key, the ASN.1 ``ECPrivateKey`` structure defined
              in `RFC5915`_ is used instead (possibly within a PKCS#8 envelope,
              see the ``use_pkcs8`` flag below).
            - ``'PEM'``. The key will be encoded in a PEM_ envelope (ASCII).
            - ``'OpenSSH'``. The key will be encoded in the OpenSSH_ format
              (ASCII, public keys only).
            - ``'SEC1'``. The public key (i.e., the EC point) will be encoded
              into ``bytes`` according to Section 2.3.3 of `SEC1`_
              (which is a subset of the older X9.62 ITU standard).
              Only for NIST P-curves.
            - ``'raw'``. The public key will be encoded as ``bytes``,
              without any metadata.

              * For NIST P-curves: equivalent to ``'SEC1'``.
              * For Ed25519 and Ed448: ``bytes`` in the format
                defined in `RFC8032`_.
              * For Curve25519 and Curve448: ``bytes`` in the format
                defined in `RFC7748`_.

          passphrase (bytes or string):
            (*Private keys only*) The passphrase to protect the
            private key.

          use_pkcs8 (boolean):
            (*Private keys only*)
            If ``True`` (default and recommended), the `PKCS#8`_ representation
            will be used.
            It must be ``True`` for Ed25519, Ed448, Curve25519, and Curve448.

            If ``False`` and a passphrase is present, the obsolete PEM
            encryption will be used.

          protection (string):
            When a private key is exported with password-protection
            and PKCS#8 (both ``DER`` and ``PEM`` formats), this parameter MUST be
            present,
            For all possible protection schemes,
            refer to :ref:`the encryption parameters of PKCS#8<enc_params>`.
            It is recommended to use ``'PBKDF2WithHMAC-SHA512AndAES128-CBC'``.

          compress (boolean):
            If ``True``, the method returns a more compact representation
            of the public key, with the X-coordinate only.

            If ``False`` (default), the method returns the full public key.

            This parameter is ignored for Ed25519/Ed448/Curve25519/Curve448,
            as compression is mandatory.

          prot_params (dict):
            When a private key is exported with password-protection
            and PKCS#8 (both ``DER`` and ``PEM`` formats), this dictionary
            contains the  parameters to use to derive the encryption key
            from the passphrase.
            For all possible values,
            refer to :ref:`the encryption parameters of PKCS#8<enc_params>`.
            The recommendation is to use ``{'iteration_count':21000}`` for PBKDF2,
            and ``{'iteration_count':131072}`` for scrypt.

        .. warning::
            If you don't provide a passphrase, the private key will be
            exported in the clear!

        .. note::
            When exporting a private key with password-protection and `PKCS#8`_
            (both ``DER`` and ``PEM`` formats), any extra parameters
            to ``export_key()`` will be passed to :mod:`Crypto.IO.PKCS8`.

        .. _PEM:        http://www.ietf.org/rfc/rfc1421.txt
        .. _`PEM encryption`: http://www.ietf.org/rfc/rfc1423.txt
        .. _OpenSSH:    http://www.openssh.com/txt/rfc5656.txt
        .. _RFC5480:    https://tools.ietf.org/html/rfc5480
        .. _SEC1:       https://www.secg.org/sec1-v2.pdf
        .. _RFC7748:    https://tools.ietf.org/html/rfc7748

        Returns:
            A multi-line string (for ``'PEM'`` and ``'OpenSSH'``) or
            ``bytes`` (for ``'DER'``, ``'SEC1'``, and ``'raw'``) with the encoded key.
        format)r   DEROpenSSHSEC1rawzUnknown format '%s'r   Fr   NzEmpty passphrase	use_pkcs8Tz%'pkcs8' must be True for EdDSA curvesz#'pkcs8' must be True for Curve25519r   z)'protection' is only supported for PKCS#8r   r   z8Private keys can only be encrpyted with DER using PKCS#8z2Private keys cannot be exported in the '%s' formatzUnexpected parameters: '%s'r   r   r   )copyr9   r?   r[   r   r   r@   ra   r   r   r   r   r   r   r   r   r   r   r   r   )rQ   rR   args
ext_formatr   r   r   s          r    
export_keyzEccKey.export_key  sX   t {{}XXh'
EE2Z?@@88J.,5J$$Z0
!$%788d3IE!;;))$%LMM;;,,$%JKK4'$%PQQU"!PtPPQ[d_cdd#LLNN3433JG$GGu$i$%_``-4--LLtLL;;==  "68B"C D D  !>!EFFU"..x88u$88BBv%((22u$;;))4466[[..99;;,,X66++H55r   N)T)r   r   r   __doc__rX   r^   ri   r[   ry   r   propertyr%   r&   r\   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r    r"   r"   ;   s    *``D+"#,  
  
  
F8
7$)6*5O6@=:U6r   r"   c                  V   | j                  d      }t        |   }| j                  dt              }| rt        dt	        |       z         t        |   j
                  t        j                  k(  r |d      }t        ||      }|S t        |   j
                  t        j                  k(  r |d      }t        ||      }|S t        |   j
                  t        j                  k(  r9 |d      }t        ||      }t        |   j                  |j                         |S t        |   j
                  t        j                  k(  r9 |d      }t        ||      }t        |   j                  |j                         |S t        j                  d|j                   |	      }t        ||
      }|S )a1  Generate a new private key on the given curve.

    Args:

      curve (string):
        Mandatory. It must be a curve name defined in the `ECC table`_.

      randfunc (callable):
        Optional. The RNG to read randomness from.
        If ``None``, :func:`Crypto.Random.get_random_bytes` is used.
    r$   randfuncr(   r*   r$   r&   r2   r7   r   )rm   rn   r   )r$   r%   )r9   r   r   r=   r>   rC   rD   rE   r"   rL   rN   validater\   rO   r	   ro   rP   )rR   rT   r$   r   r&   new_keyr%   s          r    generater   F  s|    G$JJEzz*&67H.V<==z!1!11|z5$ N# 
			8>>	1|z5 N 
			8#6#6	6|z5
$$W^^4 N 
			8#4#4	4|z5
$$W^^4 N   q/4{{*24 zQ/Nr   c                     | d   }t         |   }| j                  dd      }| j                  dd      }d| v rt        d      |j                  t        j
                  k(  r9|t        ||      | d<   t        di | }|j                  |j                         |S |j                  t        j                  k(  r9|t        ||      | d<   t        di | }|j                  |j                         |S d||fvrt        |||      | d<   t        di | }|j                         r9d| v r5|j                  |j                  z  }|j                  ||fk7  rt!        d      |S )	a  Build a new ECC key (private or public) starting
    from some base components.

    In most cases, you will already have an existing key
    which you can read in with :func:`import_key` instead
    of this function.

    Args:
      curve (string):
        Mandatory. The name of the elliptic curve, as defined in the `ECC table`_.

      d (integer):
        Mandatory for a private key and a NIST P-curve (e.g., P-256).
        It must be an integer in the range ``[1..order-1]``.

      seed (bytes):
        Mandatory for a private key and curves Ed25519 (32 bytes),
        Curve25519 (32 bytes), Curve448 (56 bytes) and Ed448 (57 bytes).

      point_x (integer):
        The X coordinate (affine) of the ECC point.
        Mandatory for a public key.

      point_y (integer):
        The Y coordinate (affine) of the ECC point.
        Mandatory for a public key,
        except for Curve25519 and Curve448.

    Returns:
      :class:`EccKey` : a new ECC key object
    r$   point_xNpoint_yr'   zUnknown keyword: pointz(Private and public ECC keys do not matchr   )r   r9   r=   rC   rD   rN   r   r"   r   r\   rO   r   r[   rq   r%   re   r?   )rR   rT   r$   r   r   r   pub_keys          r    	constructr   p  s]   B JJEjjD)GjjD)G&011xx8&&&'<F7O"6"w~~&, N) 
X&&	&'<F7O"6"w~~& N ))&wDF7O"6"  W%6gg		)Gzzgw// !KLLNr   c                 F   t        j                         D ]  \  }}|r|j                  |k(  r n'||k(  s n |rt        d|z        t        d|z        |j                  j                         }t        | d         }|dk(  rVt        |       dd|z  z   k7  rt        d      t        j                  | d|dz          }t        j                  | |dz   d       }n|d	v rt        |       d|z   k7  rt        d      t        j                  | dd       }|d
z  |d
z  z
  |j                  z   j                  |j                        }|dk(  r|j                         r|j                  |z
  }|d
k(  r+|j                         r|j                  |z
  }nt        d      t        |||      S )a  Convert an encoded EC point into an EccKey object

    ec_point: byte string with the EC point (SEC1-encoded)
    curve_oid: string with the name the curve
    curve_name: string with the OID of the curve

    Either curve_id or curve_name must be specified

    Unsupported ECC curve (OID: %s)zUnsupported ECC curve (%s)r      r   r)   zIncorrect EC point lengthNr)      r   zIncorrect EC point encodingr$   r   r   )r   itemsr   r   pr   r   rF   r?   r	   rK   bsqrtr   is_evenr   )	ec_point	curve_oidrT   _curve_namer$   r   
point_typerd   rh   s	            r    _import_public_derr     s    &mmo 	SUi/$		S '(II(UVV'(Dz(QRR GG))+Mhqk"J Tx=Q]!223899x-/:;xa(89:	|	#x=Q./899x|,TAaCZ%''!''0!((*!A!))+!A677;1==r   c                 
   t        |       \  }}}d}dt        fdt        fd}dt        fdt        fd}||v rA|st        d|z        	 t               j                  |      j                  }t        ||
      S ||v r1||   \  }	}
|rt        d|z         |
|      \  }}t        |||	      S ||v r-||   \  }	}|rt        d|z         ||      }t        ||	      S t        d|z        # t
        $ r t        d	      w xY w)z4Convert a subjectPublicKeyInfo into an EccKey objectr   z1.3.132.1.12z1.3.132.1.13Ed25519Ed448z1.3.101.112z1.3.101.113
Curve25519Curve448z1.3.101.110z1.3.101.111z%Missing ECC parameters for ECC OID %szError decoding namedCurver   z(Unexpected ECC parameters for ECC OID %s)r   r   r$   )r   r$   zUnsupported ECC OID: %s)r   _import_ed25519_public_key_import_ed448_public_key_import_curve25519_public_key_import_curve448_public_keyr?   r
   decodevaluer   r   r   )encodedrR   r   r   r   nist_p_oids
eddsa_oidsxdh_oidsr   rT   import_eddsa_public_keyrd   rh   import_xdh_public_keys                 r    _import_subjectPublicKeyInfor    s[    <GDC6K "#=>#;<J
 %&CD"$?@H
 k DsJKK	:#,,V4::I
 "(i@@	
	.8o+
+ G#MNN&x01AZ@@	,4SM)
) G#MNN!(+*55 $$=$CDD9  	:899	:s   	#C- -Dc                    t               j                  | d      }|d   dk7  rt        d      t               j                  |d         j                  }d}|t        |      k  rB	 t        d      j                  ||         j                  }|||k7  rt        d      |}|dz  }|t        d	      t        j                         D ]  \  }}|j                  |k(  s n t        d
|z        |j                  j                         }	t        |      |	k7  rt        d      d x}
}|t        |      k  rg	 t        d      j                  ||         j                  }t        ||      }|j                   j"                  }
|j                   j$                  }|dz  }t'        j(                  |      }t+        |||
|      S # t        $ r Y $w xY w# t        $ r Y ?w xY w)Nr)   r   r   )nr_elementsr   r   z!Incorrect ECC private key versionr)   r   zCurve mismatchzNo curve foundr   zPrivate key is too smallr   )r$   r%   r   r   )r   r  r?   r   payloadrF   r
   r  r   r   r   r   r   r   r   r   r\   rd   rh   r	   rK   r   )r  r   r   ec_private_keyscalar_bytesnext_element
parametersrT   r$   r   r   r   public_key_encr   r%   s                  r    _import_rfc5915_derr  2  s    !]))'y)INaA<==!#**>!+<=EELL c.))	$a077|8TU[[J$y)@ !122"IAL )**$]]_ S
E99	!S $$E	$QRRGG))+M
<M)344 Ggc.))	)15<<^L=YZ``N+NiPJ ''))G ''))GAL 	<(A:GWMM;  		2  		s&   &AF? 5A&G ?	GG	GGc                    ddl m} |j                  | |      \  }}}d}ddd}ddd	}||v r0t               j	                  |      j
                  }	t        |||	      S ||v rB|t        d
      d }	t               j	                  |      j                  }
t        ||   |
      S ||v rJ||   }|t        d|z        d }	t               j	                  |      j                  }
t        ||   |
      S t        d|z        )Nr   r   r   r   r   r   r   r   r   z.EdDSA ECC private key must not have parametersr   z+%s ECC private key must not have parametersz!Unsupported ECC purpose (OID: %s))r   r   unwrapr
   r  r  r  r?   r   r  r   r   )r  r   r   algo_oidr   r   r  r  r  r   r&   rT   s               r    _import_pkcs8r  m  s-   $)LL*$E!Hk6K !J
 $!H
 ;M((066	";
IFF	Z	MNN	&&{3;;z(3$??	X	h'
J'( ) )	&&{3;;x1==#$G($RSSr   c                 .    t        |       }t        |      S r   )r   r  )r  rR   sp_infos      r    _import_x509_certr    s    .w7G'00r   c                    	 t        | |      S # t        $ r}|d }~wt        t        t        f$ r Y nw xY w	 t        | |      S # t        $ r}|d }~wt        t        t        f$ r Y nw xY w	 t        | |      S # t        $ r}|d }~wt        t        t        f$ r Y nw xY w	 t        | |      S # t        $ r}|d }~wt        t        t        f$ r Y t        d      w xY w)NzNot an ECC DER key)r  r   r?   r=   
IndexErrorr  r  r  )r  r   errs      r    _import_derr     s    +GZ@@  		:.  *55  		:. "7J77  		:. Wj11  		:. 
)
**sm    	333A 	A(AA('A(,A8 8	BBBB!B- -	C6B88CCc                    | j                  d      }t        |      dvrt        d      	 t        j                  |d         }g }t        |      dkD  rJt        j                  d|d d       d   }|j                  |dd|z           |d|z   d  }t        |      dkD  rJ|d   |d   k7  rt        d      |d   j                  d	      rt        j                         D ]_  \  }}|j                  |j                  j                  d
      s/t        |j                  j                  d      d         }|d   |k(  s_ n t        dz         t        |d   |j                        }|S |d   dk(  r!t        |d         \  }	}
t!        d|	|
      }|S t        d|d   z         # t"        t$        t        j&                  f$ r t        d|d   z         w xY w)N    r   zNot an openssh public keyr   r   r   r   zMismatch in openssh public key   ecdsa-sha2-
ecdsa-sha2r   r)   zUnsupported ECC curve: r      ssh-ed25519r   r   zUnsupported SSH key type: zError parsing SSH key type: )r   rF   r?   rb   
a2b_base64r   unpackappend
startswithr   r   r   r   r   r   r   r   r  r=   Error)r  parts	keystringkeypartslkrT   r$   r   ecc_keyrd   rh   s              r    _import_openssh_publicr0    s   MM$E
5z455$D''a1	)nq tYr]3A6BOOIaB/0!!b&'*I )nq 
 8x{"=>> 8~.%,]]_ 	E!
E==(}}//= !4!4S!9!!<=A;&(	E !!:V!CDD(!		JG N 1X'-hqk:DAqiAFG N 9E!HDEE	8>>2 D7%(BCCDs%   A1F! BF! :+F! ''F! F! !0Gc                    ddl m}m}m}m}  || |      \  }}ddt
        dfi}|j                  d      r ||      \  }	}|	t        vrt        d|	z        t        |	   }
|
j                  dz   d	z  } ||      \  }}t        |d
         dk7  rt        d      t        |      d|z  dz   k7  rt        d      t        j                  |dd|z          }t        j                  |d|z   d        } ||      \  }}t        j                  |      }||	d}nG||v r5||   \  }}} ||      \  }} ||      \  }} ||      \  }}|d | }||d}nt        d|z          ||      \  }} ||       t        d||d|S )Nr   )import_openssh_private_generic
read_bytesread_stringcheck_paddingr   r   r*   r$  zUnsupported ECC curve %sr      r   r   z/Only uncompressed OpenSSH EC keys are supportedr)   zIncorrect public key length)r%   r$   )r&   r$   zUnsupport SSH agent key type:)r   r   r   )_opensshr2  r3  r4  r5  r   r)  r   r   modulus_bitsr   r?   rF   r	   rK   r   )datapasswordr2  r3  r4  r5  key_type	decrypted
eddsa_keysecdsa_curve_namer$   r   r   r   r   r   r%   r   rT   r	  seed_lenprivate_public_keyr&   _paddeds                            r    _import_openssh_private_eccrC    s   C C 9xHHi 		#=rBJ
 <(&1)&<#)7*'(BEU(UVV()++a/A5 *9 5
I
1!#NOOz?a-/!33:;;$$Z!M/%BC$$Z-0@%AB!+I!6Y{+#34	Z	8B88L5
+X *9 5
I2:>(29(=%I!)8,488CDDI&IAv&@Wg@@@r   c                    t        |       dk7  rt        d      t        d      }d}t        |       }|d   dz	  }|dxx   dz  cc<   t        j                  |d	      }||k\  rt        d
      |dk(  ry|dz  dz
  |z  }|dz  |z  |z  dz   |z  }	 |j                  |      }||z  |z  }	t        j                  |	|      }
|
dz  |k7  r||
z
  }
|
|fS # t        $ r t        d      w xY w)ai  Import an Ed25519 ECC public key, encoded as raw bytes as described
    in RFC8032_.

    Args:
      encoded (bytes):
        The Ed25519 public key to import. It must be 32 bytes long.

    Returns:
      x and y (integer)

    Raises:
      ValueError: when the given key cannot be parsed.

    .. _RFC8032: https://datatracker.ietf.org/doc/html/rfc8032
    r*   z9Incorrect length. Only Ed25519 public keys are supported.l   l   x&(7Z/
;(P8 se:8
w6Rr,   r   r-   r/   r0   zInvalid Ed25519 key (y)r   r   r   r)   zInvalid Ed25519 public key)rF   r?   r	   rJ   rK   rp   _tonelli_shanksr  r   r%   rh   x_lsbr   uvv_invx2r   s              r    r   r   !  s   " 7|rTUURSAUA'AbEQJEbETME  h7G!|233!|	!a1A
1*q.A		!Q&A7		!%i1_))"a0aKE!'kG G  75667s   <C C&c                     t        |       dk7  rt        d      t        |       }|dxx   dz  cc<   t        j                  |d      }|S )ah  Import a Curve25519 ECC public key,
    encoded as raw bytes as described in RFC7748_.

    Args:
      encoded (bytes):
        The Curve25519 public key to import. It must be 32 bytes long.

    Returns:
      x (integer)

    Raises:
      ValueError: when the given key cannot be parsed.

    .. _RFC7748: https://datatracker.ietf.org/doc/html/rfc7748
    r*   zIncorrect Curve25519 key lengthr,   r-   r/   r0   )rF   r?   rJ   r	   rK   )r  rd   r   s      r    r  r  N  sJ    " 7|r:;;'AbETME  h7GNr   c                 f    t        |       dk7  rt        d      t        j                  | d      }|S )ad  Import a Curve448 ECC public key,
    encoded as raw bytes as described in RFC7748_.

    Args:
      encoded (bytes):
        The Curve448 public key to import. It must be 56 bytes long.

    Returns:
      x (integer)

    Raises:
      ValueError: when the given key cannot be parsed.

    .. _RFC7748: https://datatracker.ietf.org/doc/html/rfc7748
    r7   zIncorrect Curve448 key lengthr/   r0   )rF   r?   r	   rK   )r  r   s     r    r  r  j  s3    " 7|r899  H=GNr   c                    t        |       dk7  rt        d      t        d   j                  }|dz
  }| dd }t	        | d         dz	  }t        j                  |d	      }||k\  rt        d
      |dk(  ry|dz  dz
  |z  }|dz  |z  |z  dz
  |z  }	 |j                  |      }||z  |z  }	t        j                  |	|      }
|
dz  |k7  r||
z
  }
|
|fS # t        $ r t        d      w xY w)ag  Import an Ed448 ECC public key, encoded as raw bytes as described
    in RFC8032_.

    Args:
      encoded (bytes):
        The Ed448 public key to import. It must be 57 bytes long.

    Returns:
        x and y (integer)

    Raises:
      ValueError: when the given key cannot be parsed.

    .. _RFC8032: https://datatracker.ietf.org/doc/html/rfc8032
    r2   z7Incorrect length. Only Ed448 public keys are supported.curve448i  Nr7   r   r/   r0   zInvalid Ed448 key (y)r   rE  r)   zInvalid Ed448 public key)	rF   r?   r   r   r   r	   rK   rp   rF  rG  s              r    r   r     s    " 7|rRSS
A	E	AA"E  h7G!|011!|	!a1A
1*q.A		!Q&A5		!%i1_))"a0aKE!'kG G  53445s   <C C'c                 
   ddl m} t        |       } |t        |      }| j                  d      r/t	        |       }|j                  ||      \  }}}t        ||      }|S | j                  d      ret	        |       }d}	d}
t        j                  |	dz   |
z   d	|t        j                  
      }|j                  ||      \  }}}|rd}	 t        ||      }|S | j                  d      rt        |       S t        |       dkD  rt        | d         dk(  rt        | |      S t        |       dkD  r*t        | d         dv r|t        d      t!        | |      S t        d      # t        $ r}|d}~wt        $ r t        d      w xY w)ap  Import an ECC key (public or private).

    Args:
      encoded (bytes or multi-line string):
        The ECC key to import.
        The function will try to automatically detect the right format.

        Supported formats for an ECC **public** key:

        * X.509 certificate: binary (DER) or ASCII (PEM).
        * X.509 ``subjectPublicKeyInfo``: binary (DER) or ASCII (PEM).
        * SEC1_ (or X9.62), as ``bytes``. NIST P curves only.
          You must also provide the ``curve_name`` (with a value from the `ECC table`_)
        * OpenSSH line, defined in RFC5656_ and RFC8709_ (ASCII).
          This is normally the content of files like ``~/.ssh/id_ecdsa.pub``.

        Supported formats for an ECC **private** key:

        * A binary ``ECPrivateKey`` structure, as defined in `RFC5915`_ (DER).
          NIST P curves only.
        * A `PKCS#8`_ structure (or the more recent Asymmetric Key
          Package, RFC5958_): binary (DER) or ASCII (PEM).
        * `OpenSSH 6.5`_ and newer versions (ASCII).

        Private keys can be in the clear or password-protected.

        For details about the PEM encoding, see `RFC1421`_/`RFC1423`_.

      passphrase (byte string):
        The passphrase to use for decrypting a private key.
        Encryption may be applied protected at the PEM level (not recommended)
        or at the PKCS#8 level (recommended).
        This parameter is ignored if the key in input is not encrypted.

      curve_name (string):
        For a SEC1 encoding only. This is the name of the curve,
        as defined in the `ECC table`_.

    .. note::

        To import EdDSA private and public keys, when encoded as raw ``bytes``, use:

        * :func:`Crypto.Signature.eddsa.import_public_key`, or
        * :func:`Crypto.Signature.eddsa.import_private_key`.

    .. note::

        To import X25519/X448 private and public keys, when encoded as raw ``bytes``, use:

        * :func:`Crypto.Protocol.DH.import_x25519_public_key`
        * :func:`Crypto.Protocol.DH.import_x25519_private_key`
        * :func:`Crypto.Protocol.DH.import_x448_public_key`
        * :func:`Crypto.Protocol.DH.import_x448_private_key`

    Returns:
      :class:`EccKey` : a new ECC key object

    Raises:
      ValueError: when the given key cannot be parsed (possibly because
        the pass phrase is wrong).

    .. _RFC1421: https://datatracker.ietf.org/doc/html/rfc1421
    .. _RFC1423: https://datatracker.ietf.org/doc/html/rfc1423
    .. _RFC5915: https://datatracker.ietf.org/doc/html/rfc5915
    .. _RFC5656: https://datatracker.ietf.org/doc/html/rfc5656
    .. _RFC8709: https://datatracker.ietf.org/doc/html/rfc8709
    .. _RFC5958: https://datatracker.ietf.org/doc/html/rfc5958
    .. _`PKCS#8`: https://datatracker.ietf.org/doc/html/rfc5208
    .. _`OpenSSH 6.5`: https://flak.tedunangst.com/post/new-openssh-key-format-and-bcrypt-pbkdf
    .. _SEC1: https://www.secg.org/sec1-v2.pdf
    r   r   Ns   -----BEGIN OPENSSH PRIVATE KEYs   -----z-----BEGIN EC PARAMETERS-----z-----END EC PARAMETERS-----z.*?r`   )flagsz(Invalid DER encoding inside the PEM file)r#  r%  0   r  zNo curve name was provided)rT   zECC key format is not supported)r   r   r   r)  r   r  rC  resubDOTALLr   r   r?   r0  rF   r   r   )r  r   rT   r   text_encodedopenssh_encodedmarkerenc_flagrg   ecparams_startecparams_endder_encodeduefs                r    
import_keyr_    s   R gGZ(
 ;<W~,/JJ|Z,P),_jI			H	%W~ 94vvnu4|CR*$&II/ ),

<(L%VXJ	I j9F
  :;%g.. 7|aD,47J// 7|aD,0BB9::!'jAA
6
77) % 	I 	IGHH	Is   E 	F(E**F__main__l   _,)N$chKf-5lk<Xk#E p256i  z	(P-256 G)i  msz(P-256 arbitrary point))NNr   )@
__future__r   rT  r   rb   Crypto.Util.py3compatr   r   r   r   r   Crypto.Math.Numbersr	   Crypto.Util.asn1r
   r   r   r   Crypto.PublicKeyr   r   r   Crypto.Hashr   r   Crypto.Randomr   r<   r   r   r   r   rD   r?   r   objectr"   r   r   r   r  r  r  r  r   r0  rC  r   r  r  r   r_  r   timer%   rq   r   r'   rU   startrangerd   pointXprintr   r   r    <module>rp     s  > & 	   G G ', ,@ @ ) * 0 0 '	J 	H6V H6V'TDN5>p@EF8Nv%TP1+B+\4An*Z82)X{8| zJAFO""$EEDIIKE5\ 	+			e+u4t;TBDIIKE5\ !	
#idiikE&9U%BT%I4P# r   