
    <fI                     
   d dl mZ d dlZd dlZd dlZd dlmZ d dlmZm	Z	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mZ d dlmZmZmZmZmZmZmZ d d	lm Z m!Z!m"Z" d d
l#m$Z$m%Z% d dl&m'Z' d dl(m)Z)  edd          Z* edd          Z+ edd          Z,d Z- edd          Z.i Z/g da0d Z1 e1             [1g da2d Z3 e3             [3g da4d Z5 e5             [5g da6d Z7 e7             [7g da8d Z9 e9             [9d d!ga:d" Z; e;             [;d#d$ga<d% Z= e=             [= G d& d'e>          Z? G d( d)e@          ZA eAe/d*         jB        e/d*         jC        d*          ZDe/d*         E                    eD+          ZFe/G                    eHI                    t`          eF                     [D[Fb0 eAe/d,         jB        e/d,         jC        d,          ZJe/d,         E                    eJ+          ZKe/G                    eHI                    td          eK                     [J[Kb2 eAe/d-         jB        e/d-         jC        d-          ZLe/d-         E                    eL+          ZMe/G                    eHI                    th          eM                     [L[Mb4 eAe/d.         jB        e/d.         jC        d.          ZNe/d.         E                    eN+          ZOe/G                    eHI                    tl          eO                     [N[Ob6 eAe/d/         jB        e/d/         jC        d/          ZPe/d/         E                    eP+          ZQe/G                    eHI                    tp          eQ                     [P[Qb8 eAe/d!         jB        e/d!         jC        d!          ZRe/d!         E                    eR+          ZSe/G                    eHI                    tt          eS                     [R[Sb: eAe/d$         jB        e/d$         jC        d$          ZTe/d$         E                    eT+          ZUe/G                    eHI                    tx          eU                     [T[Ub< G d0 d1e@          ZVd2 ZWd3 ZXdFd4ZYd5 ZZdGd6Z[d7 Z\d8 Z]d9 Z^d: Z_d; Z`d< Zad= ZbdFd>Zcedd?k    rd dleZed@Zfe/d-         jg        h                                ZidAZj eeje                    Zk elej          D ]Zmeiefz  Zn eodB eeje                    ekz
  ejz  dCz  dD            eeje                    Zk elej          D ]Zmenefz  Zn eodE eeje                    ekz
  ejz  dCz  dD           dS dS )H    )print_functionN)
namedtuple)bordtobytestostrbchr	is_string)bytes_to_longlong_to_bytes)Integer)DerObjectIdDerOctetStringDerSequenceDerBitString)load_pycryptodome_raw_libVoidPointerSmartPointerc_size_tc_uint8_ptrc_ulonglongnull_pointer)_expand_subject_public_key_info_create_subject_public_key_info _extract_subject_public_key_info)SHA512SHAKE256)get_random_bytes)getrandbitszCrypto.PublicKey._ec_wsa  
typedef void EcContext;
typedef void EcPoint;
int ec_ws_new_context(EcContext **pec_ctx,
                      const uint8_t *modulus,
                      const uint8_t *b,
                      const uint8_t *order,
                      size_t len,
                      uint64_t seed);
void ec_free_context(EcContext *ec_ctx);
int ec_ws_new_point(EcPoint **pecp,
                    const uint8_t *x,
                    const uint8_t *y,
                    size_t len,
                    const EcContext *ec_ctx);
void ec_ws_free_point(EcPoint *ecp);
int ec_ws_get_xy(uint8_t *x,
                 uint8_t *y,
                 size_t len,
                 const EcPoint *ecp);
int ec_ws_double(EcPoint *p);
int ec_ws_add(EcPoint *ecpa, EcPoint *ecpb);
int ec_ws_scalar(EcPoint *ecp,
                 const uint8_t *k,
                 size_t len,
                 uint64_t seed);
int ec_ws_clone(EcPoint **pecp2, const EcPoint *ecp);
int ec_ws_cmp(const EcPoint *ecp1, const EcPoint *ecp2);
int ec_ws_neg(EcPoint *p);
zCrypto.PublicKey._ed25519ai  
typedef void Point;
int ed25519_new_point(Point **out,
                      const uint8_t x[32],
                      const uint8_t y[32],
                      size_t modsize,
                      const void *context);
int ed25519_clone(Point **P, const Point *Q);
void ed25519_free_point(Point *p);
int ed25519_cmp(const Point *p1, const Point *p2);
int ed25519_neg(Point *p);
int ed25519_get_xy(uint8_t *xb, uint8_t *yb, size_t modsize, Point *p);
int ed25519_double(Point *p);
int ed25519_add(Point *P1, const Point *P2);
int ed25519_scalar(Point *P, const uint8_t *scalar, size_t scalar_len, uint64_t seed);
zCrypto.PublicKey._ed448a*  
typedef void EcContext;
typedef void PointEd448;
int ed448_new_context(EcContext **pec_ctx);
void ed448_context(EcContext *ec_ctx);
void ed448_free_context(EcContext *ec_ctx);
int ed448_new_point(PointEd448 **out,
                    const uint8_t x[56],
                    const uint8_t y[56],
                    size_t len,
                    const EcContext *context);
int ed448_clone(PointEd448 **P, const PointEd448 *Q);
void ed448_free_point(PointEd448 *p);
int ed448_cmp(const PointEd448 *p1, const PointEd448 *p2);
int ed448_neg(PointEd448 *p);
int ed448_get_xy(uint8_t *xb, uint8_t *yb, size_t len, const PointEd448 *p);
int ed448_double(PointEd448 *p);
int ed448_add(PointEd448 *P1, const PointEd448 *P2);
int ed448_scalar(PointEd448 *P, const uint8_t *scalar, size_t scalar_len, uint64_t seed);
c                     | j         j        dk    rt          t          d|z             }nA| j         j        dk    rt          t          d|z             }nt          t
          d|z             }|S )NEd25519ed25519_Ed448ed448_ec_ws_)_curvedescgetattr_ed25519_lib
_ed448_lib_ec_lib)ecc_obj	func_nameresults      c/home/panchajanya/Development/work/volatility3/lib/python3.11/site-packages/Crypto/PublicKey/ECC.pylib_funcr/      sg    ~i''zI'=>>			'	'X	%9::(Y"677M    _Curvez<p b order Gx Gy G modulus_bits oid context desc openssh name)p192
NIST P-192zP-192
prime192v1	secp192r1nistp192c                  T   d} d}d}d}d}t          | d          }t          |d          }t          |d          }t                      }t                              |                                t          |          t          |          t          |          t          t          |                    t          t          d                              }	|	rt          d|	z            t          |                                t          j                  }
t          t          |           t          |          t          |          t          |          t          |          d d	d
|
ddd          }t                               t$                              t(          |                     d S )Nl   l   9{uDjSg9g(Bl   1(i&^#a;l   +' 1t:_|v!a:@ml   H<^W]dZ{cxW\Iq    @   z#Error %d initializing P-192 context   z1.2.840.10045.3.1.1r3   zecdsa-sha2-nistp192r2   )r   r   r*   ec_ws_new_context
address_ofr   r   lenr   r   ImportErrorr   getec_free_contextr1   r   _curvesupdatedictfromkeys
p192_names)pborderGxGyp192_modulusp192_b
p192_orderec_p192_contextr-   contextr2   s               r.   	init_p192rP      sn   :A:A>E	;B	;B B''L1b!!Fub))J!mmO&&'A'A'C'C'2<'@'@'26':':'2:'>'>'/L0A0A'B'B'2;r??'C'C) )F  J?&HIII?..00'2IJJG'!**!**%.."++"++'' D NN4==T2233333r0   )p224
NIST P-224zP-224
prime224v1	secp224r1nistp224c                  T   d} d}d}d}d}t          | d          }t          |d          }t          |d          }t                      }t                              |                                t          |          t          |          t          |          t          t          |                    t          t          d                              }	|	rt          d|	z            t          |                                t          j                  }
t          t          |           t          |          t          |          t          |          t          |          d d	d
|
ddd          }t                               t$                              t(          |                     d S )Nl              ?l   FeY8w-X"PVd/%PP!-l   =*8%(?l   !"X!#BXtJ9!'|%VA-l   4~ 
f&Dv@h!fE0m9_qlM/   r9   z#Error %d initializing P-224 context   z1.3.132.0.33rR   zecdsa-sha2-nistp224rQ   )r   r   r*   r;   r<   r   r   r=   r   r   r>   r   r?   r@   r1   r   rA   rB   rC   rD   
p224_names)rF   rG   rH   rI   rJ   p224_modulusp224_b
p224_orderec_p224_contextr-   rO   rQ   s               r.   	init_p224r^      sn   BABAFE	CB	CB B''L1b!!Fub))J!mmO&&'A'A'C'C'2<'@'@'26':':'2:'>'>'/L0A0A'B'B'2;r??'C'C) )F  J?&HIII?..00'2IJJG'!**!**%.."++"++ ' D NN4==T2233333r0   )p256
NIST P-256zP-256
prime256v1	secp256r1nistp256c                  T   d} d}d}d}d}t          | d          }t          |d          }t          |d          }t                      }t                              |                                t          |          t          |          t          |          t          t          |                    t          t          d                              }	|	rt          d|	z            t          |                                t          j                  }
t          t          |           t          |          t          |          t          |          t          |          d d	d
|
ddd          }t                               t$                              t(          |                     d S )Nl   ?               @ l   K`Opq^cv
3,e<1U]>{|R*Zl   Q%x+Ohbi+}s   @ l   B11e	%:f=K`wrH7gHK8hkl   Q~o]l+fUg+<)Z?8O?q!O    r9   z#Error %d initializing P-256 context   z1.2.840.10045.3.1.7r`   zecdsa-sha2-nistp256r_   )r   r   r*   r;   r<   r   r   r=   r   r   r>   r   r?   r@   r1   r   rA   rB   rC   rD   
p256_names)rF   rG   rH   rI   rJ   p256_modulusp256_b
p256_orderec_p256_contextr-   rO   r_   s               r.   	init_p256rl     sn   JAJANE	KB	KB B''L1b!!Fub))J!mmO&&'A'A'C'C'2<'@'@'26':':'2:'>'>'/L0A0A'B'B'2;r??'C'C) )F  J?&HIII?..00'2IJJG'!**!**%.."++"++'' D NN4==T2233333r0   )p384
NIST P-384zP-384
prime384v1	secp384r1nistp384c                  T   d} d}d}d}d}t          | d          }t          |d          }t          |d          }t                      }t                              |                                t          |          t          |          t          |          t          t          |                    t          t          d                              }	|	rt          d|	z            t          |                                t          j                  }
t          t          |           t          |          t          |          t          |          t          |          d d	d
|
ddd          }t                               t$                              t(          |                     d S )Nl          ~l   *'#.TEbc+Z'@=D 1 "(?7N2Z_+|S/1fl   s)e`gwlX_[nlv|l   
dxRjoyU8T(	:ss"nZL8k&"_Ul   _!uR/sX0
@qaNQNB&JxS8KJEY	K%l 0   r9   z#Error %d initializing P-384 contexti  z1.3.132.0.34rn   zecdsa-sha2-nistp384rm   )r   r   r*   r;   r<   r   r   r=   r   r   r>   r   r?   r@   r1   r   rA   rB   rC   rD   
p384_names)rF   rG   rH   rI   rJ   p384_modulusp384_b
p384_orderec_p384_contextr-   rO   rm   s               r.   	init_p384ry   0  sn   jAjAnE	kB	kB B''L1b!!Fub))J!mmO&&'A'A'C'C'2<'@'@'26':':'2:'>'>'/L0A0A'B'B'2;r??'C'C) )F  J?&HIII?..00'2IJJG'!**!**%.."++"++ ' D NN4==T2233333r0   )p521
NIST P-521zP-521
prime521v1	secp521r1nistp521c                  T   d} d}d}d}d}t          | d          }t          |d          }t          |d          }t                      }t                              |                                t          |          t          |          t          |          t          t          |                    t          t          d                              }	|	rt          d|	z            t          |                                t          j                  }
t          t          |           t          |          t          |          t          |          t          |          d d	d
|
ddd          }t                               t$                              t(          |                     d S )Nl#   l#    ?VQ(zO%b95~cte1oR{V;LHw>l-rZE]"Sr&Ga9}*Fl#   	dp"z\}[z3"nZ;PK#
`7roCQl#   f=xK)H-apY$3^Q	n%k{;/K!u{4-{?$Od8V1l3s:l#   Pf?QE$XN!85aZUWL9YLhzf$Du13otc!%pMxjRr`B   r9   z#Error %d initializing P-521 contexti	  z1.3.132.0.35r{   zecdsa-sha2-nistp521rz   )r   r   r*   r;   r<   r   r   r=   r   r   r>   r   r?   r@   r1   r   rA   rB   rC   rD   
p521_names)rF   rG   rH   rI   rJ   p521_modulusp521_b
p521_orderec_p521_contextr-   rO   rz   s               r.   	init_p521r   _  s}    	SA 	SA WE 
TB 
TB B''L1b!!Fub))J!mmO&&'A'A'C'C'2<'@'@'26':':'2:'>'>'/L0A0A'B'B'2;r??'C'C) )F  J?&HIII?..00'2IJJG'!**!**%.."++"++ ' D NN4==T2233333r0   ed25519r    c                  "   d} d}d}d}t          t          |           d t          |          t          |          t          |          d ddd ddd	          }t                              t                              t          |                     d S )
N   l   S9i@eM^w|o                l   UK5J,{$%Xci\-G'
lJ[sii!l   XfL33ffL33ffL33ffL33ff   1.3.101.112r    ssh-ed25519r   )r1   r   rA   rB   rC   rD   ed25519_names)rF   rH   rI   rJ   r   s        r.   init_ed25519r     s    JANE	KB	KBWQZZU^^R[[R[[""   G NN4==8899999r0   ed448r"   c                     d} d}d}d}t                      }t                              |                                          }|rt	          d|z            t          |                                t          j                  }t          t          |           d t          |          t          |          t          |          d dd|dd d	          }t                              t                              t          |                     d S )
N   ?l   DVJ
Ru8a6!m,&vD}D2_l   ^@ 518`b8Cl\p*At(qmj.<+FaS[/SDZ74_3	l   zadoeC@
ZK^DsxssZhNx02>Ilq2 vIZugt'z#Error %d initializing Ed448 contexti  1.3.101.113r"   r   )r   r)   ed448_new_contextr<   r>   r   r?   ed448_free_contextr1   r   rA   rB   rC   rD   ed448_names)rF   rH   rI   rJ   ed448_contextr-   rO   r   s           r.   
init_ed448r     s    zA~E	{B	{BMMM))-*B*B*D*DEEF J?&HIII=,,..
0MNNG71::5>>2;;2;;  E NN4==e4455555r0   c                       e Zd ZdS )UnsupportedEccFeatureN)__name__
__module____qualname__ r0   r.   r   r     s        Dr0   r   c                       e Zd ZdZdd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 Zd Zd ZdS )EccPointaP  A class to model a point on an Elliptic Curve.

    The class supports operators for:

    * Adding two points: ``R = S + T``
    * In-place addition: ``S += T``
    * Negating a point: ``R = -T``
    * Comparing two points: ``if S == T: ...`` or ``if S != T: ...``
    * Multiplying a point by a scalar: ``R = S*k``
    * In-place multiplication by a scalar: ``T *= k``

    :ivar x: The affine X-coordinate of the ECC point
    :vartype x: integer

    :ivar y: The affine Y-coordinate of the ECC point
    :vartype y: integer

    :ivar xy: The tuple with affine X- and Y- coordinates
    r_   c                    	 t           |         | _        n-# t          $ r  t          dt	          |          z            w xY w|| _        |                                 }t          ||          }t          ||          }t          |          |k    st          |          |k    rt          d          t          | d          }t          | d          }t                      | _        	 | j        j                                        }	n# t          $ r
 t          }	Y nw xY w || j                                        t#          |          t#          |          t%          |          |	          }
|
r'|
dk    rt          d          t          d|
z            t'          | j                                        |          | _        d S )NzUnknown curve name %szIncorrect coordinate length	new_point
free_point   z)The EC point does not belong to the curvez(Error %d while instantiating an EC point)rA   r%   KeyError
ValueErrorstr_curve_namesize_in_bytesr   r=   r/   r   _pointrO   r?   AttributeErrorr   r<   r   r   r   )selfxycurvemodulus_bytesxbybr   	free_funcrO   r-   s              r.   __init__zEccPoint.__init__  s   	C!%.DKK 	C 	C 	C4s5zzABBB	C **,,1m,,1m,,r77m##s2ww-'?'?:;;;T;//	T<00	!mm	#k)--//GG 	# 	# 	#"GGG	#4;1133&r??&r??#M22"	$ $  	R|| !LMMMG&PQQQ #4;??#4#4i@@s    *?&D DDc                 `   t          | d          }t          | d          }t                      | _         || j                                        |j                                                  }|rt          d|z            t          | j                                        |          | _        | S )Ncloner   z"Error %d while cloning an EC point)r/   r   r   r<   r?   r   r   )r   pointr   r   r-   s        r.   setzEccPoint.set
  s    w''T<00	!mmt{--//|''))+ +  	LAFJKKK"4;??#4#4i@@r0   c                     t          |t                    sdS t          | d          }d || j                                        |j                                                  k    S )NFcmpr   )
isinstancer   r/   r   r?   )r   r   cmp_funcs      r.   __eq__zEccPoint.__eq__  sY    %** 	5D%((HHT[__..0@0@0B0BCCCCr0   c                     | |k     S Nr   )r   r   s     r.   __ne__zEccPoint.__ne__   s    5=  r0   c                     t          | d          }|                                 } ||j                                                  }|rt	          d|z            |S )Nnegz$Error %d while inverting an EC point)r/   copyr   r?   r   )r   neg_funcnpr-   s       r.   __neg__zEccPoint.__neg__#  sY    D%((YY[[")--//** 	NCfLMMM	r0   c                 F    | j         \  }}t          ||| j                  }|S )zReturn a copy of this point.)xyr   r   )r   r   r   r   s       r.   r   zEccPoint.copy+  s&    w1aD,--	r0   c                     | j         j        dv S )Nr   r   )r%   namer   s    r.   	_is_eddsazEccPoint._is_eddsa1      {#777r0   c                 V    |                                  r| j        dk    S | j        dk    S )z,``True`` if this is the *point-at-infinity*.r   )r   r   )r   r   r   r   s    r.   is_point_at_infinityzEccPoint.is_point_at_infinity4  s/     >> 	%6Q;7f$$r0   c                     |                                  rt          dd| j                  S t          dd| j                  S )z-Return the *point-at-infinity* for the curve.r      )r   r   r   r   s    r.   point_at_infinityzEccPoint.point_at_infinity<  s@     >> 	4Aq$"2333Aq$"2333r0   c                     | j         d         S )Nr   r   r   s    r.   r   z
EccPoint.xD      wqzr0   c                     | j         d         S )Nr   r   r   s    r.   r   z
EccPoint.yH  r   r0   c                    |                                  }t          |          }t          |          }t          | d          } |t          |          t          |          t	          |          | j                                                  }|rt          d|z            t          t          |                    t          t          |                    fS )Nget_xyz#Error %d while encoding an EC point)
r   	bytearrayr/   r   r   r   r?   r   r   r
   )r   r   r   r   r   r-   s         r.   r   zEccPoint.xyL  s    **,,}%%}%%$))B#B //))+ +  	MBVKLLLb))**GM"4E4E,F,FGGr0   c                 6    |                                  dz   dz  S )z"Size of each coordinate, in bytes.      )size_in_bitsr   s    r.   r   zEccPoint.size_in_bytes[  s    !!##a'A--r0   c                     | j         j        S )z!Size of each coordinate, in bits.)r%   modulus_bitsr   s    r.   r   zEccPoint.size_in_bits_  s    {''r0   c                     t          | d          } || j                                                  }|rt          d|z            | S )zuDouble this point (in-place operation).

        Returns:
            This same object (to enable chaining).
        doublez#Error %d while doubling an EC pointr/   r   r?   r   )r   double_funcr-   s      r.   r   zEccPoint.doublec  sP     tX..T[__..// 	MBVKLLLr0   c                     t          | d          } || j                                        |j                                                  }|r'|dk    rt          d          t          d|z            | S )zAdd a second point to this oneadd   z#EC points are not on the same curvez#Error %d while adding two EC pointsr   )r   r   add_funcr-   s       r.   __iadd__zEccPoint.__iadd__p  sx     D%(($+//++U\-=-=-?-?@@ 	M|| !FGGGBVKLLLr0   c                 8    |                                  }||z  }|S )z8Return a new point, the addition of this one and anotherr   )r   r   r   s      r.   __add__zEccPoint.__add__{  s     YY[[
e	r0   c           
      b   t          | d          }|dk     rt          d          t          |          } || j                                        t          |          t          t          |                    t          t          d                              }|rt          d|z            | S )zMultiply this point by a scalarscalarr   z?Scalar multiplication is only defined for non-negative integersr9   z%Error %d during scalar multiplication)
r/   r   r   r   r?   r   r   r=   r   r   )r   r   scalar_funcsbr-   s        r.   __imul__zEccPoint.__imul__  s     tX..A::^___6""T[__..(__%c"gg..(R99; ;  	ODvMNNNr0   c                 8    |                                  }||z  }|S )z2Return a new point, the scalar product of this oner   )r   r   r   s      r.   __mul__zEccPoint.__mul__  s     YY[[
f	r0   c                 ,    |                      |          S r   )r   )r   	left_hands     r.   __rmul__zEccPoint.__rmul__  s    ||I&&&r0   N)r_   )r   r   r   __doc__r   r   r   r   r   r   r   r   r   propertyr   r   r   r   r   r   r   r   r   r   r   r   r0   r.   r   r     s~        ($A $A $A $AL  D D D! ! !    8 8 8% % %4 4 4   X   X H H XH. . .( ( (  	 	 	      ' ' ' ' 'r0   r   r2   )GrQ   r_   rm   rz   c                       e Zd 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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 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`

    :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 EdDSA curves
                (Ed25519, 32 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          |                                 s^| j        t          d          t          | j                  | _        d| j        cxk    r| j
        j        k     sn t          d          dS | j        t          d          | j
        j        dk    rt%          | 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<   n| j
        j        dk    rt%          | j                  dk    rt          d          t1          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 )!ai  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 the Ed25519 (32 bytes)
            or Ed448 (57 bytes) curve.
          point : EccPoint
            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.
        r   Ndseedr   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 exclusivez7Parameter 'seed' can only be used with Ed25519 or Ed448r   z;Parameter d must be an integer smaller than the curve orderz/Parameter d can only be used with NIST P curvesr   re   z0Parameter seed must be 32 bytes long for Ed25519         r9   r   9   z.Parameter seed must be 57 bytes long for Ed448r      7      8   little	byteorder)rC   pop_d_seedr   r   	TypeErrorr   rA   r   r%   r&   r   intr   r   rH   r   r=   r   newdigest_prefixr   r   read
from_bytes)r   kwargskwargs_
curve_namecount	seed_hashtmps          r.   r   zEccKey.__init__  s-   & v,,[[$//
++c4(([[..
kk'400$+0J 	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 ~~ 	Bz% !Z[[[dg&&DG3333$+"33333 !^___ 43 w" !RSSS{9,,tz??b(($%WXXX"Jtz2299;;	(~	#2#//A$r7T>T1B!W,,tz??b(($%UVVV$L4499#>>	(~	#2#//A$B4B(AAADGGGr0   c                     | j         j        dv S )N)r    r"   )r%   r&   r   s    r.   r   zEccKey._is_eddsa#  r   r0   c                     t          |t                    sdS |                                |                                 k    rdS |j        | j        k    S )NF)r   r   has_privatepointQ)r   others     r.   r   zEccKey.__eq__&  sP    %(( 	5$"2"2"4"4445|t{**r0   c                    |                                  rV|                                 r*dt          t          j        | j                            z  }ndt          | j                  z  }nd}| j        j	        \  }}d| j
        j        |||fz  S )Nz	, seed=%sz, d=%d z,EccKey(curve='%s', point_x=%d, point_y=%d%s))r  r   r   binasciihexlifyr  r  r  r  r   r%   r&   )r   extrar   r   s       r.   __repr__zEccKey.__repr__/  s     	~~ 0#eH,<TZ,H,H&I&II 3tw<</E{~1=AQSTVWY^@___r0   c                     | j         duS )zJ``True`` if this key can be used for making signatures or decrypting data.N)r  r   s    r.   r  zEccKey.has_private:  s     wd""r0   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%   rH   r   random_ranger  inverser   r   )	r   zkrH   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r0   c                     | j         j        }|d                             |          }| j         j        ||z  |z  z  }| j        ||d         z  |z  z  }||z   j        |d         k    S )Nr   r   )r%   rH   r,  r   r  r   )r   r-  rsrH   sinvpoint1point2s          r.   _verifyzEccKey._verifyO  sg    !!u}}U##4!8u"451 67"be++r0   c                 V    |                                  st          d          | j        S NzThis is not a private ECC key)r  r   r  r   s    r.   r   zEccKey.dV  s,    !! 	><===wr0   c                 V    |                                  st          d          | j        S r<  )r  r   r  r   s    r.   r   zEccKey.seed\  s-    !! 	><===zr0   c                 P    | j         | j        j        | j        z  | _         | j         S r   )r   r%   r   r  r   s    r.   r  zEccKey.pointQb  s$    ;+-$'1DK{r0   c                 B    t          | j        j        | j                  S )z^A matching ECC public key.

        Returns:
            a new :class:`EccKey` object
        )r   r   )r   r%   r&   r  r   s    r.   
public_keyzEccKey.public_keyh  s     DK,DK@@@@r0   c                    |                                  r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 unsupported for EdDSA curves         )r   r   r  r   r   is_oddr   to_bytes)r   compressr   
first_byter@  s        r.   _export_SEC1zEccKey._export_SEC1q  s    >> 	LJKKK 1133 
	A{}##%% %$

$
$+-00??@JJ "+-00??@+-00??@J r0   c                 n   | j         j        \  }}| j        j        dk    r9t	          |                    dd                    }|dz  dz  |d         z  |d<   nO| j        j        dk    r0t	          |                    d	d                    }|dz  dz  |d
<   nt          d          t          |          S )Nr   re   r	  r
  r   r   r  r   r  r  zNot an EdDSA key to export)r  r   r%   r   r   rF  r   bytes)r   r   r   r-   s       r.   _export_eddsazEccKey._export_eddsa  s    {~1;y((qzz"zAABBFq5Q,&*4F2JJ[((qzz"zAABBFa%AF2JJ9:::V}}r0   c                     |                                  r#| j        j        }|                                 }d }n0d}|                     |          }t          | j        j                  }t          |||          S )N1.2.840.10045.2.1)r   r%   oidrL  rI  r   r   )r   rG  rO  r@  paramss        r.   _export_subjectPublicKeyInfoz#EccKey._export_subjectPublicKeyInfo  sx    >> 	2+/C++--JFF%C**844J 11F.s/9/57 7 	7r0   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 )NrD  r   r   explicitr   )r  r  r   r   rF  r   r   r   r   r%   rO  r   r   encode)r   include_ec_paramsr   r@  seqs        r.   _export_rfc5915_private_derz"EccKey._export_rfc5915_private_der  s    !!!!! 1133km,,];;<km,,];;<
 dfoom<<==4;?Q777J3335
 ! 	A3&&(((r0   c                 z   ddl m} |                    dd           d|vrt          d          |                                 r5| 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 presentrN  F)rV  
key_params)	Crypto.IOr[  r?   r   r   r%   rO  r   r  rU  rX  r   wrap)r   r  r[  rO  private_keyrP  r-   s          r.   _export_pkcs8zEccKey._export_pkcs8  s    ######::lD))5,f:T:TRSSS>> 	2+/C(44;;==KFF%C::U:SSK 11FK& &'-& %& & r0   c                 d    ddl m} |                     |          }|                    |d          S )Nr   PEMz
PUBLIC KEY)r_  re  rQ  rU  )r   rG  re  encoded_ders       r.   _export_public_pemzEccKey._export_public_pem  s;    !!!!!!77AAzz+|444r0   c                 V    ddl m} |                                 } |j        |d|fi |S )Nr   rd  zEC PRIVATE KEY)r_  re  rX  rU  r   r\  r  re  rf  s        r.   _export_private_pemzEccKey._export_private_pem  sD    !!!!!!6688sz+'7NNvNNNr0   c                 b    ddl m} |                                 }|                    |d          S )Nr   rd  zPRIVATE KEY)r_  re  rb  rU  )r   re  rf  s      r.   (_export_private_clear_pkcs8_in_clear_pemz/EccKey._export_private_clear_pkcs8_in_clear_pem  s9    !!!!!!((**zz+}555r0   c                     ddl m} |sJ d|vrt          d           | j        dd|i|}|                    |d          S )Nr   rd  r]  z5At least the 'protection' parameter should be presentr\  zENCRYPTED PRIVATE KEYr   )r_  re  r   rb  rU  ri  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+'>???r0   c                 j   |                                  rt          d          | j        j        }|t          d| j        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 OpenSSHr   r   rD  -r0   c                 X    g | ]'}t          j        d t          |                    |z   (S )>I)structpackr=   ).0r   s     r.   
<listcomp>z*EccKey._export_openssh.<locals>.<listcomp>  s/    FFF1T3q6622Q6FFFr0    )r  r   r%   opensshr   rL  r   r  r   r   rE  r   r   rF  splitjoinr   r#  
b2a_base64)	r   rG  r&   r@  compsr   rH  middleblobs	            r.   _export_opensshzEccKey._export_openssh  s    	CABBB{"<?$+BRRSSS]""++--J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";";<<<<r0   c                 ~   |                                 }|                    d          }|dvrt          d|z            |                    dd          }|                                 r|                    dd          }t	          |          r t          |          }|st          d          |                    d	d
          }|s6|                                 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    r7| j        j        dv 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 EdDSA curves: ``bytes`` in the format defined in `RFC8032`_.

          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 EdDSA curves.

            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-SHA5126AndAES128-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 EdDSA curves, 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

        Returns:
            A multi-line string (for ``'PEM'`` and ``'OpenSSH'``) or
            ``bytes`` (for ``'DER'``, ``'SEC1'``, and ``'raw'``) with the encoded key.
        format)re  DEROpenSSHSEC1rawzUnknown format '%s'rG  Fr\  NzEmpty passphrase	use_pkcs8Tz%'pkcs8' must be True for EdDSA curvesr]  z)'protection' is only supported for PKCS#8re  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   r   )r   r  r   r  r	   r   r   rn  rl  rj  rb  rX  rg  rQ  rI  r%   r   rL  r  )r   r  args
ext_formatrG  r\  r  s          r.   
export_keyzEccKey.export_key  s   j {{}}XXh''
EEE2Z?@@@88J.. 0	6,55J$$ 9$Z00
! 9$%7888d33I R>>## N$%LMMM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$$;#';;;--///,,X666++H555r0   N)T)r   r   r   r   r   r   r   r&  r  r4  r:  r   r   r   r  r@  rI  rL  rQ  rX  rb  rg  rj  rl  rn  r  r  r   r0   r.   r   r     s        *JB JB JBX8 8 8+ + +	` 	` 	`# # #  , , ,   X
   X
   X
A A A  8
 
 
7 7 7) ) ) )6  *5 5 5O O O6 6 6@ @ @= = =:L6 L6 L6 L6 L6r0   r   c                     |                      d          }t          |         }|                      dt                    }| rt          dt	          |           z             t          |         j        dk    r |d          }t          ||          }n`t          |         j        dk    r |d          }t          ||          }n-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   re   r   r   r   r  r   )r)  r*  r  )r   r   )
r  rA   r   r  r   r   r   r   r+  rH   )r  r  r   r  r   new_keyr   s          r.   generater    s     G$$JJEzz*&677H >.V<===z9,,x||z555			!W	,	,x||z555 q/4{*24 4 4 zQ///Nr0   c                     | d         }t           |         }|                     dd          }|                     dd          }d| v rt          d          d||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):
        the integer in the range ``[1..order-1]`` that represents the key.

      seed (bytes):
        Mandatory for a private key and an EdDSA curve.
        It must be 32 bytes for Ed25519, and 57 bytes for Ed448.

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

      point_y (integer):
        Mandatory for a public key: the Y coordinate (affine) of the ECC point.

    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   )
rA   r  r  r   r   r  r   r   r   r   )r  r  r   r  r  r  pub_keys          r.   	constructr    s    < JJEjjD))GjjD))G&0111GW%%%"7GZ@@wvG  IF!2!2'GI%:'7+++GHHHNr0   c                    t                                           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  )rA   itemsrO  r   rF   r   r   r=   r   r   r  rG   sqrtrE  is_evenr  )	ec_point	curve_oidr  r   r   r   
point_typer   r   s	            r.   _import_public_derr    s    &mmoo 	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====r0   c                    t          |           \  }}}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 t          d
|z            )z4Convert a subjectPublicKeyInfo into an EccKey objectrN  z1.3.132.1.12z1.3.132.1.13r    r"   r   r   z%Missing ECC parameters for ECC OID %szError decoding namedCurver  z(Unexpected ECC parameters for ECC OID %s)r  r  r   zUnsupported ECC OID: %s)
r   _import_ed25519_public_key_import_ed448_public_keyr   r   decodevaluer  r  r   )encodedr  rO  r  rP  nist_p_oids
eddsa_oidsr  r  import_eddsa_public_keyr   r   s               r.   _import_subjectPublicKeyInfor  .  sA    <GDDC6K "#=>#;< J
 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@@@@#$=$CDDDs   &A) )Bc                    t                                          | d          }|d         dk    rt          d          	 t          d                              |d                   j        }|||k    rt          d          |}n# t          $ r Y nw xY w|t          d	          t
                                          D ]\  }}|j        |k    r nt          d
|z            t                                          |d                   j
        }|j                                        }t          |          |k    rt          d          t          j        |          }	t          |          dk    rXt!          d                              |d                   j        }
t#          |
|          }|j        j        }|j        j        }nd x}}t+          ||	||          S )N)r  r  )nr_elementsr   r   z!Incorrect ECC private key versionrS  r   zCurve mismatchzNo curve foundr  zPrivate key is too smallr  )r   r   r  r  )r   r  r   r   r  rA   r  rO  r   r   payloadrF   r   r=   r   r  r   r  r  r   r   r  )r  r\  r  ra  
parametersr  r   scalar_bytesr   r   public_key_encr@  r  r  s                 r.   _import_rfc5915_derr  b  s    --&&wF&CCK1~<=== !,,,33KNCCI
 Z9%<%<-...		    )***$]]__ S S
E9	!!E " $$E	$QRRR!##**;q>::BLG))++M
<M))3444<((A ;!%q11188RIIO')LLL
#%#%  ':GWMMMMs    AB 
BBc                    ddl m} |                    | |          \  }}}d}ddd}||v r7t                                          |          j        }t          |||          S ||v rP|t          d          d }t                                          |          j	        }	t          ||         |	          S t          d	|z            )
Nr   rZ  r  r    r"   r  z.EdDSA ECC private key must not have parametersr  z!Unsupported ECC purpose (OID: %s))r_  r[  unwrapr   r  r  r  r   r   r  r  r   )
r  r\  r[  algo_oidra  rP  r  r  r  r   s
             r.   _import_pkcs8r    s    $)LL*$E$E!Hk6K ! J
 ;MM((006	";
IFFF	Z		MNNN	&&{33;z(3$????#$G($RSSSr0   c                 >    t          |           }t          |          S r   )r   r  )r  r  sp_infos      r.   _import_x509_certr    s    .w77G'000r0   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                 v   |                      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          
                                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  rr  r   zMismatch in openssh public key   ecdsa-sha2-
ecdsa-sha2rp  r   zUnsupported ECC curve: r     ssh-ed25519r    r  zUnsupported SSH key type: zError parsing SSH key type: )ry  r=   r   r#  
a2b_base64rs  unpackappend
startswithrA   r  rx  r   r  rO  r  r  r  r  Error)r  parts	keystringkeypartslkr  r   r}  ecc_keyr   r   s              r.   _import_openssh_publicr    sQ   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	H 5H6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    re   r  zUnsupported ECC curve %sr   r   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   )_opensshr  r  r  r  r  r  rA   r   r   r   r   r=   r   r  r  )datapasswordr  r  r  r  key_type	decrypted
eddsa_keysecdsa_curve_namer   r   r@  r  r  ra  r   rP  r  r  seed_lenprivate_public_keyr   _paddeds                            r.   _import_openssh_private_eccr    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@@@@@r0   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 )a~  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:
      :class:`EccKey` : a new ECC key object

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

    .. _RFC8032: https://datatracker.ietf.org/doc/html/rfc8032
    re   z9Incorrect length. Only Ed25519 public keys are supported.r   l   x&(7Z/
;(P8 se:8
w6Rr  r   r  r	  r
  zInvalid Ed25519 key (y)r   r   r   r   zInvalid Ed25519 public key)r=   r   r   r   r  r,  _tonelli_shanksr  rF   r   r   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          }d}| 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 )az  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:
      :class:`EccKey` : a new ECC key object

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

    .. _RFC8032: https://datatracker.ietf.org/doc/html/rfc8032
    r  z7Incorrect length. Only Ed448 public keys are supported.r   l   Vg?Nr  r   r	  r
  zInvalid Ed448 key (y)r   r  r   zInvalid Ed448 public key)r=   r   r   r   r  r,  r  r  s              r.   r  r  i  sM   " 7||rRSSS  C  	D  	DAzA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:`Crypto.Signature.eddsa.import_public_key`, or
        * :func:`Crypto.Signature.eddsa.import_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   rd  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  rs   )r   r  r  zNo curve name was provided)r  zECC key format is not supported)r_  re  r   r  r   r  r  resubDOTALLr  r   r   r  r=   r   r  )r  r\  r  re  text_encodedopenssh_encodedmarkerenc_flagr-   ecparams_startecparams_endder_encodeduefs                r.   
import_keyr    s1   ~ 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 i  z	(P-256 G)i  msz(P-256 arbitrary point))NNr   )p
__future__r   r  rs  r#  collectionsr   Crypto.Util.py3compatr   r   r   r   r	   Crypto.Util.numberr
   r   Crypto.Math.Numbersr   Crypto.Util.asn1r   r   r   r   Crypto.Util._raw_apir   r   r   r   r   r   r   Crypto.PublicKeyr   r   r   Crypto.Hashr   r   Crypto.Randomr   Crypto.Random.randomr   r*   r(   r)   r/   r1   rA   rE   rP   rY   r^   rg   rl   rt   ry   r   r   r   r   r   r   r   r   objectr   rI   rJ   p192_G_replacer2   rB   rC   rD   p224_GrQ   p256_Gr_   p384_Grm   p521_Grz   	ed25519_Gr   ed448_Gr   r   r  r  r  r  r  r  r  r  r  r  r  r  r  r   timer   r   r   r   r  startranger   pointXprintr   r0   r.   <module>r     s  > & % % % % % 				   " " " " " " G G G G G G G G G G G G G G ; ; ; ; ; ; ; ; ' ' ' ' ' ', , , , , , , , , , , ,= = = = = = = = = = = = = = = = = =@ @ @ @ @ @ @ @ @ @ ) ( ( ( ( ( ( ( * * * * * * , , , , , , $
#$= @  > )()D G  " '&'@ C  
,  4 
H\	]	]
  
$4 $4 $4N 
	  
$4 $4 $4N 
	  
$4 $4 $4N 
	  
$4 $4 $4N 
	  
$4 $4 $4N 
	 I&: : :,   6 6 6: 
	 	 	 	 	J 	 	 	J' J' J' J' J'v J' J' J'\ 
'&/$gfo&8&	A	Av&)) t}}Z.. / / /
D*	'&/$gfo&8&	A	Av&)) t}}Z.. / / /
D*	'&/$gfo&8&	A	Av&)) t}}Z.. / / /
D*	'&/$gfo&8&	A	Av&)) t}}Z.. / / /
D*	'&/$gfo&8&	A	Av&)) t}}Z.. / / /
D*HWY'*GI,>,A9MM	
)

%
%	
%
2
2 t}}]G44 5 5 5w
(77#&(8(;W
E
E!!G!,, t}}[%00 1 1 1UKZ6 Z6 Z6 Z6 Z6V Z6 Z6 Z6z  D3 3 3l5> 5> 5> 5>p1E 1E 1Eh/N /N /N /NdT T T81 1 1+ + +B+ + +\4A 4A 4An* * *Z) ) )Xq8 q8 q8 q8h 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# r0   