
    ÿigc                        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!         j7        8                                Z9d"Z: e5j5                    Z; e<e:          D ]Z=e9e6z  Z> e?d# e5j5                    e;z
  e:z  d$z  d%            e5j5                    Z; e<e:          D ]Z=e>e6z  Z> e?d& e5j5                    e;z
  e:z  d$z  d%           dS dS ))    )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dS )UnsupportedEccFeatureN)__name__
__module____qualname__     T/var/www/html/afkarena/venv/lib/python3.11/site-packages/Cryptodome/PublicKey/ECC.pyr   r   7   s        Dr   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dS )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          |          }|                    dd          }|                    dd          | _        |                    dd          | _        |                    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	          dS |d
k    rt          d          | j
        j        t          j        k    r| j        t          d          t!          | j                  dk    rt          d          t#          j        | j                                                  }|dd         | _        t+          |dd                   }|dxx         dz  cc<   |d         dz  dz  |d<   t-          j        |d          | _        dS | j
        j        t          j        k    r| j        t          d          t!          | j                  dk    rt          d          t3          j        | j                                      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          | _        dS | j
        j        t          j        k    r| j        t          d          t!          | j                  dk    rt          d          t+          | j                  }|dxx         dz  cc<   |d         dz  dz  |d<   t-          j        |d          | _        dS | j
        j        t          j        k    r| j        t          d          t!          | j                  dk    rt          d          t+          | j                  }|dxx         dz  cc<   |dxx         dz  cc<   t-          j        |d          | _        dS | j        t          d          t-          | j                  | _        d| j        cxk    r| j
        j        k     sn t          d           dS )!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0$+*J 	C2S\\ABBBW$$5
BCCCj)[*
DG4'((3tz/E+F+FFA::{" !jkkkFA::KLLL
 ;>X---w" !RSSS4:"$$ !STTT
4:..5577I$RSS>DLIcrcN++CFFFdNFFF2w~-CG(AAADGGG[^x~--w" !RSSS4:"$$ !QRRR TZ0055c::I$RSS>DLIcrcN++CFFFdNFFFGGGtOGGGCG(AAADGGG[^x222w" !RSSS4:"$$ !VWWWDJ''CFFFdNFFF2w~-CG(AAADGGG[^x000w" !RSSS4:"$$ !TUUUDJ''CFFFdNFFFGGGtOGGG(AAADGGG z% !UVVVdg&&DG3333$+"33333 !^___ 43r   c                     t          |t                    sdS |                                |                                 k    rdS |j        | j        k    S )NF)
isinstancer"   has_privatepointQ)rQ   others     r    __eq__zEccKey.__eq__   sP    %(( 	5$"2"2"4"4445|t{**r   c                    |                                  rN| j        j        r*dt          t	          j        | j                            z  }ndt          | j                  z  }nd}| j        j	        t          j        t          j        fv r| j        j        }d| j        j        ||fz  }n"| 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     	{% 0#eH,<TZ,H,H&I&II 3tw<</E;>h1&/1 1 1A74;;PRSUZ:[[FF;>DAqCt{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     wd""r   c                    d|cxk     r| j         j        k     sn J | j         j        }t          j        d|          }| j        |z  }||z                      |          }| 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0[]Q!E)519w{23e;1vr   c                     | j         j        }|d                             |          }| 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   sg    !!u}}U##4!8u"451 67"be++r   c                 V    |                                  st          d          | j        S NzThis is not a private ECC key)r[   r?   r:   rk   s    r    r%   zEccKey.d   s,    !! 	><===wr   c                 V    |                                  st          d          | j        S r   )r[   r?   r;   rk   s    r    r&   zEccKey.seed   s-    !! 	><===zr   c                 P    | j         | j        j        | j        z  | _         | j         S N)r<   r@   rq   r:   rk   s    r    r\   zEccKey.pointQ   s$    ;+-$'1DK{r   c                 B    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     DK1EEEEr   c                    | j         j        st          d          | j                                        }|rF| j        j                                        rd}nd}|| j        j                            |          z   }nBd| j        j                            |          z   | 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    {) 	PNOOO 1133 
	A{}##%% %$

$
$+-00??@JJ "+-00??@+-00??@J r   c                    | j         j        \  }}| j        j        t          j        k    r9t          |                    dd                    }|dz  dz  |d         z  |d<   nY| j        j        t          j        k    r0t          |                    dd                    }|dz  dz  |d<   nt          d	          t          |          S )
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ABBFq5Q,&*4F2JJ[^x~--qzz"zAABBFa%AF2JJ9:::V}}r   c                     | j         j        st          d          | j        j        }| j                                        }t          |                    |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,  sc    {( 	?=>>>KM[..00
1::jH:EEFFV}}r   c                 @   | j         j        r#| j         j        }|                                 }d }n_| j         j        r#| j         j        }|                                 }d }n0d}|                     |          }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    ;! 	2+/C2244JFF[& 	2+/C7799JFF%C**844J 11F.s/9/57 7 	7r   Tc                    |                                  sJ | j                                        }d| j        j                            |          z   | j        j                            |          z   }dt          | j                            |                    t          | j	        j
        d          t          |d          g}|s|d= t          |                                          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3km,,];;<km,,];;<
 dfoom<<==4;?Q777J3335
 ! 	A3&&(((r   c                 `   ddl m} |                    dd           d|vrt          d          | j        5| j        j        }t          | j                                                  }d }n1d}| 	                    d          }t          | j        j                  } |j        ||fd	|i|}|S )
Nr   PKCS8
passphrase
protectionz3At least the 'protection' parameter must be presentr   F)r   
key_params)Cryptodome.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:TRSSS:!+/C(44;;==KFF%C::U:SSK 11FK& &'-& %& & r   c                 d    ddl m} |                     |          }|                    |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Azz+|444r   c                 V    ddl m} |                                 } |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|  sD    %%%%%%6688sz+'7NNvNNNr   c                 b    ddl m} |                                 }|                    |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  s9    %%%%%%((**zz+}555r   c                     ddl m} |sJ d|vrt          d           | j        dd|i|}|                    |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  sl    %%%%%%v%%TUUU(d(IIJI&IIzz+'>???r   c                 `   |                                  rt          d          | j        j        }|t          d| j        z            |dk    r3|                                 }t          |          t          |          f}n| j                                        }|rQd| j        j	        
                                z   }t          |          | j        j                            |          z   }nBd| j        j                            |          z   | j        j	                            |          z   }|                    d          d         }t          |          t          |          |f}d                    d |D                       }|d	z   t!          t#          j        |                    z   S )
Nz"Cannot export OpenSSH private keysz Cannot export %s keys as OpenSSHssh-ed25519r)   r   -r   c                 X    g | ]'}t          j        d t          |                    |z   (S )>I)structpackrF   ).0rd   s     r    
<listcomp>z*EccKey._export_openssh.<locals>.<listcomp>  s/    FFF1T3q6622Q6FFFr    )r[   r?   r@   opensshr$   r   r   r\   r   rh   r   r   rd   r   splitjoinr   rb   
b2a_base64)	rQ   r   descr   compsr   r   middleblobs	            r    _export_opensshzEccKey._export_openssh  s    	CABBB{"<?$*LMMM]""2244JT]]GJ$7$78EE K5577M E!5!5!7!77
":.."km44]CCD

 &"km44]CCD"km44]CCD
 ZZ__Q'FT]]GFOOZ@ExxFFFFFGGczE("5d";";<<<<r   c                    |                                 }|                    d          }|dvrt          d|z            |                    dd          }|                                 r2|                    dd          }t	          |          r t          |          }|st          d          |                    d	d
          }|du rI| j        j        rt          d          | j        j        rt          d          d|v rt          d          |dk    r4|r$|r | j	        |fi |S | 
                                S  | j        |fi |S |dk    r8|r|st          d          |r | j        dd|i|S |                                 S t          d|z            |rt          d|z            |dk    r|                     |          S |dk    r|                     |          S |dk    r|                     |          S |dk    rU| j        j        r|                                 S | j        j        r|                                 S |                     |          S |                     |          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:`Cryptodome.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  s   t {{}}XXh''
EEE2Z?@@@88J.. 4	6,55J$$ 9$Z00
! 9$%7888d33IE!!;) N$%LMMM;, L$%JKKK4''$%PQQQU"" H! OPtPQ[dd_cddd#LLNNN343JGG$GGGu$$ ai a$%_``` >-4-LLLtLLL;;===  "68B"C D D D  G !>!EFFFU""..x888u$$88BBBv%%((222u$$;) 744666[. 799;;;,,X666++H5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+ + +  "# # #  , , ,   X
   X
   X
F F F  8
 
 
  7 7 7$) ) ) )6  *5 5 5O O O6 6 6@ @ @= = =:U6 U6 U6 U6 U6r   r"   c                     |                      d          }t          |         }|                      dt                    }| rt          dt	          |           z             t          |         j        t          j        k    r |d          }t          ||          }n.t          |         j        t          j	        k    r |d          }t          ||          }nt          |         j        t          j
        k    rB |d          }t          ||          }t          |                             |j                   nt          |         j        t          j        k    rB |d          }t          ||          }t          |                             |j                   n-t          j        d|j        |	          }t          ||
          }|S )a5  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:`Cryptodome.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77H >.V<===z!111x||z555			8>	1	1x||z555			8#6	6	6x||z555
$$W^4444			8#4	4	4x||z555
$$W^4444 q/4{*24 4 4 zQ///Nr   c                     | d         }t           |         }|                     dd          }|                     dd          }d| v rt          d          |j        t          j        k    r<|t          ||          | d<   t          di | }|                    |j	                   n|j        t          j
        k    r<|t          ||          | d<   t          di | }|                    |j	                   nid||fvrt          |||          | d<   t          di | }|                                r/d| v r+|j        |j        z  }|j        ||fk    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1x8&&&'<<F7O""6""w~&&&&	X&	&	&'<<F7O""6""w~&&&& )))&wDDF7O""6""    	MW%6%6g	)Gzgw/// !KLLLNr   c                    t          j                    D ]\  }}|r|j        |k    r n/||k    r n'|rt          d|z            t          d|z            |j                                        }t          | d                   }|dk    rgt          |           dd|z  z   k    rt          d          t          j
        | d|dz                      }t          j
        | |dz   d                   }n|d	v rt          |           d|z   k    rt          d          t          j
        | dd                   }|d
z  |d
z  z
  |j        z                       |j                  }|dk    r|                                r
|j        |z
  }|d
k    r|                                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    &moo 	S 	SU 	i//E$$E %  	S'(II(UVVV'(Dz(QRRR G))++Mhqk""J Tx==Q]!22338999x-/(9:;;xa(8(89::	|	#	#x==Q.//8999x|,,TAaCZ%'!''00!((**!A!))++!A6777;1====r   c                 |   t          |           \  }}}d}dt          fdt          fd}dt          fdt          fd}||v rj|st          d|z            	 t                                          |          j        }n# t
          $ r t          d	          w xY wt          ||
          S ||v r?||         \  }	}
|rt          d|z             |
|          \  }}t          |||	          S ||v r;||         \  }	}|rt          d|z             ||          }t          ||	          S t          d|z            )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DC6K "#=>#;< J
 %&CD"$?@ H
 k  	LDsJKKK	:#,,V44:II 	: 	: 	:8999	: "(i@@@@	
		.8o+
+  	OG#MNNN&&x001AZ@@@@	,4SM)
)  	OG#MNNN!!(++*5555 $$=$CDDDs   &A< <Bc                    t                                          | d          }|d         dk    rt          d          t                                          |d                   j        }d}|t          |          k     r^	 t          d                              ||                   j        }|||k    rt          d          |}|dz  }n# t          $ r Y nw xY w|t          d	          t          j	                    D ]\  }}|j
        |k    r nt          d
|z            |j                                        }	t          |          |	k    rt          d          d x}
}|t          |          k     rn	 t          d                              ||                   j        }t          ||          }|j        j        }
|j        j        }|dz  }n# t          $ r Y nw xY wt'          j        |          }t+          |||
|          S )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  sQ    !]]))'y)IINaA<===!##**>!+<==ELL c.))))	$a00077|8TUU[J$y)@)@ !1222"IALL 	 	 	D	 )***$]__ S S
E9	!!E " $$E	$QRRRG))++M
<M))3444 Ggc.))))	)1555<<^L=YZZ`N+NiPPPJ ')G ')GALL 	 	 	D	 	<((A:GWMMMMs&   AC 
CC:AG 
G$#G$c                 Z   ddl m} |                    | |          \  }}}d}ddd}ddd	}||v r7t                                          |          j        }	t          |||	          S ||v rP|t          d
          d }	t                                          |          j	        }
t          ||         |
          S ||v r[||         }|t          d|z            d }	t                                          |          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  st   ######$)LL*$E$E!Hk6K ! J
 $! H
 ;MM((006	";
IFFF	Z		MNNN	&&{33;z(3$????	X		h'
J'( ) ) )	&&{33;x1====#$G($RSSSr   c                 >    t          |           }t          |          S r   )r   r  )r  rR   sp_infos      r    _import_x509_certr    s    .w77G'0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 nw xY wt          d          )NzNot an ECC DER key)r  r   r?   r=   
IndexErrorr  r  r  )r  r   errs      r    _import_derr#    so   +GZ@@@    		:.    *555    		:.   "7J777    		:.   Wj111    		:.    )
*
**sm    
;;;A 
A8AA87A8<B 
B5BB54B59C	 	
C2CC21C2c                 j   |                      d          }t          |          dvrt          d          	 t          j        |d                   }g }t          |          dk    rct          j        d|d d                   d         }|                    |dd|z                       |d|z   d          }t          |          dk    c|d         |d         k    rt          d          |d                             d	          rt          j
                    D ]c\  }}|j        |j                            d
          s(t          |j                             d          d                   }|d         |k    r ndt          d|z             t          |d         |j                  }nO|d         dk    r+t          |d                   \  }	}
t!          d|	|
          }nt          d|d         z             n8# t"          t$          t          j        f$ r t          d|d         z             w xY w|S )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_publicr3    sO   MM$E
5zz4555$D'a11	)nnq  tYrr]33A6BOOIaBh/000!!b&''*I )nnq  
 8x{""=>>> 8~.. 	F%,]__ 	E 	E!
E=(}//==  !4!4S!9!9!!<==A;&((E ) !!:V!CDDD(!	JJJGG 1X''-hqk::DAqiAFFFGG9E!HDEEE	8>2 D D D7%(BCCCD Ns   GG; ;5H0c                    ddl m}m}m}m}  || |          \  }}ddt
          dfi}|                    d          r ||          \  }	}|	t          vrt          d|	z            t          |	         }
|
j	        dz   d	z  } ||          \  }}t          |d
                   dk    rt          d          t          |          d|z  dz   k    rt          d          t          j        |dd|z                      }t          j        |d|z   d                    } ||          \  }}t          j        |          }||	d}n\||v rF||         \  }}} ||          \  }} ||          \  }} ||          \  }}|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   )_opensshr5  r6  r7  r8  r  r,  r   r   modulus_bitsr   r?   rF   r	   rK   r   )datapasswordr5  r6  r7  r8  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_eccrF    s   C C C C C C C C C C C C 98xHHHi 		#=rBJ
 <(( #E&1k)&<&<#)7**'(BEU(UVVV()+a/A5 *
9 5 5
I
1!##NOOOz??a-/!333:;;;$Z!M/0A%BCC$Z-0@0@%ABB!+I!6!6Y{++#344	Z		8B88L5
+X *
9 5 5
I22:>>(2
9(=(=%I!)8),4488CDDDI&&IAvM&@Wg@@@@@r   c                     t          |           dk    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dS |dz  dz
  |z  }|dz  |z  |z  dz   |z  }	 |                    |          }||z  |z  }	t          j        |	|          }
|
dz  |k    r||
z
  }
n# t          $ r t          d          w xY w|
|fS )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  !  sP   " 7||rTUUURSSAUA'AbEQJEbEEETMEEE h777G!||2333!||t	!a1A
1*q.A		!Q&A7		!%i1_)"a00aKE!!'kG 7 7 756667Gs   .A C/ /D	c                     t          |           dk    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  s`    " 7||r:;;;'AbEEETMEEE h777GNr   c                 v    t          |           dk    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  s>    " 7||r8999 H===GNr   c                    t          |           dk    rt          d          t          d         j        }|dz
  }| dd         }t	          | d                   dz	  }t          j        |d	          }||k    rt          d
          |dk    rdS |dz  dz
  |z  }|dz  |z  |z  dz
  |z  }	 |                    |          }||z  |z  }	t          j        |	|          }
|
dz  |k    r||
z
  }
n# t          $ r t          d          w xY w|
|fS )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   rH  r)   zInvalid Ed448 public key)	rF   r?   r   r   r   r	   rK   rp   rI  rJ  s              r    r  r    sG   " 7||rRSSS
A	E	AA"E h777G!||0111!||t	!a1A
1*q.A		!Q&A5		!%i1_)"a00aKE!!'kG 5 5 534445Gs   ,A C- -Dc                    ddl m} t          |           } |t          |          }|                     d          r;t	          |           }|                    ||          \  }}}t          ||          }|S |                     d          rt	          |           }d}	d}
t          j        |	dz   |
z   d	|t          j	        
          }|                    ||          \  }}}|rd}	 t          ||          }n,# t          $ r}|d}~wt          $ r t          d          w xY w|S |                     d          rt          |           S t          |           dk    r)t          | d                   dk    rt          | |          S t          |           dk    r9t          | d                   dv r"|t          d          t!          | |          S t          d          )a  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:`Cryptodome.Signature.eddsa.import_public_key`, or
        * :func:`Cryptodome.Signature.eddsa.import_private_key`.

    .. note::

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

        * :func:`Cryptodome.Protocol.DH.import_x25519_public_key`
        * :func:`Cryptodome.Protocol.DH.import_x25519_private_key`
        * :func:`Cryptodome.Protocol.DH.import_x448_public_key`
        * :func:`Cryptodome.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  rF  resubDOTALLr#  r   r?   r3  rF   r   r   )r  r   rT   r   text_encodedopenssh_encodedmarkerenc_flagrg   ecparams_startecparams_endder_encodeduefs                r    
import_keyrb    s1   R "!!!!!gGZ((
 ;<< W~~,/JJ|Z,P,P),_jII			H	%	% W~~ 94vnu4|CR*$&I/ / / ),

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