3
¬ �eI  ã               @   sî  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d„ Z-eddƒZ.i Z/ddddddga0dd„ Z1e1ƒ  [1dd d!d"d#d$ga2d%d&„ Z3e3ƒ  [3d'd(d)d*d+d,ga4d-d.„ Z5e5ƒ  [5d/d0d1d2d3d4ga6d5d6„ Z7e7ƒ  [7d7d8d9d:d;d<ga8d=d>„ Z9e9ƒ  [9d?d@ga:dAdB„ Z;e;ƒ  [;dCdDga<dEdF„ Z=e=ƒ  [=G dGdH„ dHe>ƒZ?G dIdJ„ dJe@ƒZAeAe/d jBe/d jCdƒZDe/d jEeDdK�ZFe/jGeHjIt0eFƒƒ [D[Fb0eAe/d jBe/d jCdƒZJe/d jEeJdK�ZKe/jGeHjIt2eKƒƒ [J[Kb2eAe/d' jBe/d' jCd'ƒZLe/d' jEeLdK�ZMe/jGeHjIt4eMƒƒ [L[Mb4eAe/d/ jBe/d/ jCd/ƒZNe/d/ jEeNdK�ZOe/jGeHjIt6eOƒƒ [N[Ob6eAe/d7 jBe/d7 jCd7ƒZPe/d7 jEePdK�ZQe/jGeHjIt8eQƒƒ [P[Qb8eAe/d@ jBe/d@ jCd@ƒZRe/d@ jEeRdK�ZSe/jGeHjIt:eSƒƒ [R[Sb:eAe/dD jBe/dD jCdDƒZTe/dD jEeTdK�ZUe/jGeHjIt<eUƒƒ [T[Ub<G dLdM„ dMe@ƒZVdNdO„ ZWdPdQ„ ZXdodRdS„ZYdTdU„ ZZdpdVdW„Z[dXdY„ Z\dZd[„ Z]d\d]„ Z^d^d_„ Z_d`da„ Z`dbdc„ Zaddde„ Zbdqdfdg„Zceddhk�rêd dleZediZfe/d' jgjhƒ ZidjZjeejeƒ ZkxelejƒD ]Zmeief Zn�q|W eodkeejeƒ ek ej dl dmƒ eejeƒ ZkxelejƒD ]Zmenef Zn�q¼W eodneejeƒ ek ej dl dmƒ dS )ré    )Ú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             C   sJ   | j jdkrttd| ƒ}n*| j jdkr8ttd| ƒ}nttd| ƒ}|S )NÚEd25519Zed25519_ÚEd448Zed448_Zec_ws_)Ú_curveÚdescÚgetattrÚ_ed25519_libÚ
_ed448_libÚ_ec_lib)Zecc_objÚ	func_nameÚresult© r(   ú[/var/www/html/wholesaler-api-python-env/lib/python3.6/site-packages/Crypto/PublicKey/ECC.pyÚlib_func�   s    r*   Ú_Curvez<p b order Gx Gy G modulus_bits oid context desc openssh nameÚp192z
NIST P-192zP-192Z
prime192v1Z	secp192r1Znistp192c              C   sÔ   d} d}d}d}d}t | dƒ}t |dƒ}t |dƒ}tƒ }tj|jƒ t|ƒt|ƒt|ƒtt|ƒƒtt	dƒƒƒ}	|	r|t
d|	 ƒ‚t|jƒ tjƒ}
tt| ƒt|ƒt|ƒt|ƒt|ƒd d	d
|
dddƒ}tjtjt|ƒƒ d S )Nl   ÿÿÿÿïÿÿÿÿÿÿÿÿl   ±9�³{ÆuŸ†DÜjôSg9–g(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.1z
NIST P-192zecdsa-sha2-nistp192r,   )r
   r   r%   Úec_ws_new_contextÚ
address_ofr   r   Úlenr   r   ÚImportErrorr   ÚgetÚec_free_contextr+   r   Ú_curvesÚupdateÚdictÚfromkeysÚ
p192_names)ÚpÚbÚorderÚGxÚGyZp192_modulusZp192_bZ
p192_orderZec_p192_contextr'   Úcontextr,   r(   r(   r)   Ú	init_p192£   s>    




rA   Úp224z
NIST P-224zP-224Z
prime224v1Z	secp224r1Znistp224c              C   sÔ   d} d}d}d}d}t | dƒ}t |dƒ}t |dƒ}tƒ }tj|jƒ t|ƒt|ƒt|ƒtt|ƒƒtt	dƒƒƒ}	|	r|t
d|	 ƒ‚t|jƒ tjƒ}
tt| ƒt|ƒt|ƒt|ƒt|ƒd d	d
|
dddƒ}tjtjt|ƒƒ d S )Nl              Àÿÿÿÿÿÿÿÿ?l   ´«FeY8¢ûwõ-X"PVdÕ/�%ÀPP!-l   =*¸8%éá¸(‹ÿÿÿÿÿÿÿ?l   !¸"X”!#BXÕtàJ9!'È|û%»V—AÃ-l   4~ 
f¬&Dvè@hº!Íf¿E0m9_qlM/é   r.   z#Error %d initializing P-224 contextéà   z1.3.132.0.33z
NIST P-224zecdsa-sha2-nistp224rB   )r
   r   r%   r0   r1   r   r   r2   r   r   r3   r   r4   r5   r+   r   r6   r7   r8   r9   Ú
p224_names)r;   r<   r=   r>   r?   Zp224_modulusZp224_bZ
p224_orderZec_p224_contextr'   r@   rB   r(   r(   r)   Ú	init_p224Ò   s>    




rF   Úp256z
NIST P-256zP-256Z
prime256v1Z	secp256r1Znistp256c              C   sÔ   d} d}d}d}d}t | dƒ}t |dƒ}t |dƒ}tƒ }tj|jƒ t|ƒt|ƒt|ƒtt|ƒƒtt	dƒƒƒ}	|	r|t
d|	 ƒ‚t|jƒ tjƒ}
tt| ƒt|ƒt|ƒt|ƒt|ƒd d	d
|
dddƒ}tjtjt|ƒƒ d S )Nl   ÿÿÿÿÿÿ?               @ÿÿ l   K`¤Oøpq^cv
3,ƒe<1ÚUê]>{|RŽ*ìÆZl   Q%Æx+ÎOhóbi+}s¼ÿÿÿÿ   @ÿÿ l   –B11e	%:f=K`¾wr�HŽ7g‹HK8ùhkl   õQ~o ²]ìl+fÚUg+<ð)Z?î8óO†?q!ãOé    r.   z#Error %d initializing P-256 contexté   z1.2.840.10045.3.1.7z
NIST P-256zecdsa-sha2-nistp256rG   )r
   r   r%   r0   r1   r   r   r2   r   r   r3   r   r4   r5   r+   r   r6   r7   r8   r9   Ú
p256_names)r;   r<   r=   r>   r?   Zp256_modulusZp256_bZ
p256_orderZec_p256_contextr'   r@   rG   r(   r(   r)   Ú	init_p256  s>    




rK   Úp384z
NIST P-384zP-384Z
prime384v1Z	secp384r1Znistp384c              C   sÔ   d} d}d}d}d}t | dƒ}t |dƒ}t |dƒ}tƒ }tj|jƒ t|ƒt|ƒt|ƒtt|ƒƒtt	dƒƒƒ}	|	r|t
d|	 ƒ‚t|jƒ tjƒ}
tt| ƒt|ƒt|ƒt|ƒt|ƒd d	d
|
dddƒ}tjtjt|ƒƒ d S )Nl   ÿÿ       Àÿÿ~ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿl   ï*Ø'·#.TÒÚEbc+ÆZ'@=D 1 "( ?7N2Zà_+à“|¹ñS/1fl   s)Š«e`g®w’lX_[nÐlv|ÿÿÿÿÿÿÿÿÿÿÿÿÿl   ·
ìdáx¢RÃ¥joyU8T(	:Ÿssé"±nèZ‚L÷8kñ&Á"_ÊUl   _Ô!òuR×Ð/‡sX0
@qa×NˆQ�N�B&JÞôxS8KJüEéYë‹	K%Þl é0   r.   z#Error %d initializing P-384 contexti€  z1.3.132.0.34z
NIST P-384zecdsa-sha2-nistp384rL   )r
   r   r%   r0   r1   r   r   r2   r   r   r3   r   r4   r5   r+   r   r6   r7   r8   r9   Ú
p384_names)r;   r<   r=   r>   r?   Zp384_modulusZp384_bZ
p384_orderZec_p384_contextr'   r@   rL   r(   r(   r)   Ú	init_p3840  s>    




rO   Úp521z
NIST P-521zP-521Z
prime521v1Z	secp521r1Znistp521c              C   sÔ   d} d}d}d}d}t | dƒ}t |dƒ}t |dƒ}tƒ }tj|jƒ t|ƒt|ƒt|ƒtt|ƒƒtt	dƒƒƒ}	|	r|t
d|	 ƒ‚t|jƒ tjƒ}
tt| ƒt|ƒt|ƒt|ƒt|ƒd d	d
|
dddƒ}tjtjt|ƒƒ d S )Nl#   ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿl#    ? VQ(zO†%bï95~cîte1oR{¨VÂÄ;ŒLHw>ÅlÌ-rZE]´"Sr‡&Ga9}*Fl#   	dp"z\}[ëzˆ3"näZ;PKÜ#
`ü7ÍrËoÁC†Qôÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿl#   f=ËÇxóK¿)H-apY$3^Q‹	ná%kù{;/K!u{4-{Š?$íO‚�d8ÑV1¶lÇ3s:·l#   Pf¢?ÚQôE$XN¨!85aZþÈUÈ½WL9îYLù¹hûzÑf«$Du13otc!û%‘pMxjRr`éB   r.   z#Error %d initializing P-521 contexti	  z1.3.132.0.35z
NIST P-521zecdsa-sha2-nistp521rP   )r
   r   r%   r0   r1   r   r   r2   r   r   r3   r   r4   r5   r+   r   r6   r7   r8   r9   Ú
p521_names)r;   r<   r=   r>   r?   Zp521_modulusZp521_bZ
p521_orderZec_p521_contextr'   r@   rP   r(   r(   r)   Ú	init_p521_  s>    




rS   Úed25519r   c              C   sT   d} d}d}d}t t| ƒd t|ƒt|ƒt|ƒd ddd ddd	ƒ}tjtjt|ƒƒ d S )
Nl   íÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿl   íSë9i“@eMó^¨w|o                l   UK‚5±J,{´$%Xci\¸-÷G'
lJ[sii!l   XfÌL™33ffÌL™33ffÌL™33ffÌL™33fféÿ   z1.3.101.112r   zssh-ed25519rT   )r+   r   r6   r7   r8   r9   Úed25519_names)r;   r=   r>   r?   rT   r(   r(   r)   Úinit_ed25519�  s"    rW   Úed448r   c              C   sˆ   d} d}d}d}t ƒ }tj|jƒ ƒ}|r4td| ƒ‚t|jƒ tjƒ}tt	| ƒd t	|ƒt	|ƒt	|ƒd dd|dd d	ƒ}t
jtjt|ƒƒ d S )
Nl   ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿ?ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿl   óD°VJ
ÆRu±8£a6!m,»&ÚvD}D2_ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿl   ^@¯ 51â8`b8ÀCÊlª\×p*AŒtô(’qmjÏ.<‚+FaS[Í/SDZ74_3ã	l   zadoeC@Ù
ùZK‰^ýDsx™sø­sZhNx�0Ž2›§>Ilq2« vIðZugt'z#Error %d initializing Ed448 contextiÀ  z1.3.101.113r   rX   )r   r$   Zed448_new_contextr1   r3   r   r4   Zed448_free_contextr+   r   r6   r7   r8   r9   Úed448_names)r;   r=   r>   r?   Zed448_contextr'   r@   rX   r(   r(   r)   Ú
init_ed448ª  s,    rZ   c               @   s   e Zd ZdS )ÚUnsupportedEccFeatureN)Ú__name__Ú
__module__Ú__qualname__r(   r(   r(   r)   r[   Ë  s   r[   c               @   s¾   e Zd ZdZd,dd„Zdd„ Zdd„ Zd	d
„ Zdd„ Zdd„ Z	dd„ Z
dd„ Zdd„ Zedd„ ƒZedd„ ƒZedd„ ƒZdd„ Zdd„ Zdd „ Zd!d"„ Zd#d$„ Zd%d&„ Zd'd(„ Zd)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
    rG   c             C   s  yt | | _W n$ tk
r2   tdt|ƒ ƒ‚Y nX || _| jƒ }t||ƒ}t||ƒ}t|ƒ|ksnt|ƒ|krvtdƒ‚t	| dƒ}t	| dƒ}t
ƒ | _y| jjjƒ }	W n tk
rº   t}	Y nX || jjƒ t|ƒt|ƒt|ƒ|	ƒ}
|
rþ|
dkròtdƒ‚td|
 ƒ‚t| j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)r6   r    ÚKeyErrorÚ
ValueErrorÚstrÚ_curve_nameÚsize_in_bytesr
   r2   r*   r   Ú_pointr@   r4   ÚAttributeErrorr   r1   r   r   r   )ÚselfÚxÚyÚcurveÚmodulus_bytesÚxbÚybr`   Ú	free_funcr@   r'   r(   r(   r)   Ú__init__ä  s6    





zEccPoint.__init__c             C   sX   t | dƒ}t | dƒ}tƒ | _|| jjƒ |jjƒ ƒ}|rBtd| ƒ‚t| jjƒ |ƒ| _| S )NÚclonera   z"Error %d while cloning an EC point)r*   r   rh   r1   r4   rd   r   )rj   Úpointrs   rq   r'   r(   r(   r)   Úset
  s    


zEccPoint.setc             C   s2   t |tƒsdS t| dƒ}d|| jjƒ |jjƒ ƒkS )NFZcmpr   )Ú
isinstancer_   r*   rh   r4   )rj   rt   Zcmp_funcr(   r(   r)   Ú__eq__  s    

zEccPoint.__eq__c             C   s
   | |k S )Nr(   )rj   rt   r(   r(   r)   Ú__ne__   s    zEccPoint.__ne__c             C   s4   t | dƒ}| jƒ }||jjƒ ƒ}|r0td| ƒ‚|S )NÚnegz$Error %d while inverting an EC point)r*   Úcopyrh   r4   rd   )rj   Zneg_funcÚnpr'   r(   r(   r)   Ú__neg__#  s    
zEccPoint.__neg__c             C   s   | j \}}t||| jƒ}|S )zReturn a copy of this point.)Úxyr_   rf   )rj   rk   rl   r{   r(   r(   r)   rz   +  s    
zEccPoint.copyc             C   s   | j jdkS )NrT   rX   )rT   rX   )r    Úname)rj   r(   r(   r)   Ú	_is_eddsa1  s    zEccPoint._is_eddsac             C   s    | j ƒ r| jdkS | jdkS dS )z,``True`` if this is the *point-at-infinity*.r   N)r   r   )r   rk   r}   )rj   r(   r(   r)   Úis_point_at_infinity4  s    
zEccPoint.is_point_at_infinityc             C   s(   | j ƒ rtdd| jƒS tdd| jƒS dS )z-Return the *point-at-infinity* for the curve.r   é   N)r   r_   rf   )rj   r(   r(   r)   Úpoint_at_infinity<  s    zEccPoint.point_at_infinityc             C   s
   | j d S )Nr   )r}   )rj   r(   r(   r)   rk   D  s    z
EccPoint.xc             C   s
   | j d S )Nr�   )r}   )rj   r(   r(   r)   rl   H  s    z
EccPoint.yc             C   sj   | j ƒ }t|ƒ}t|ƒ}t| dƒ}|t|ƒt|ƒt|ƒ| jjƒ ƒ}|rRtd| ƒ‚tt	|ƒƒtt	|ƒƒfS )NÚget_xyz#Error %d while encoding an EC point)
rg   Ú	bytearrayr*   r   r   rh   r4   rd   r   r	   )rj   rn   ro   rp   rƒ   r'   r(   r(   r)   r}   L  s    
zEccPoint.xyc             C   s   | j ƒ d d S )z"Size of each coordinate, in bytes.é   é   )Úsize_in_bits)rj   r(   r(   r)   rg   [  s    zEccPoint.size_in_bytesc             C   s   | j jS )z!Size of each coordinate, in bits.)r    Úmodulus_bits)rj   r(   r(   r)   r‡   _  s    zEccPoint.size_in_bitsc             C   s,   t | dƒ}|| jjƒ ƒ}|r(td| ƒ‚| S )zuDouble this point (in-place operation).

        Returns:
            This same object (to enable chaining).
        Údoublez#Error %d while doubling an EC point)r*   rh   r4   rd   )rj   Zdouble_funcr'   r(   r(   r)   r‰   c  s
    
zEccPoint.doublec             C   sD   t | dƒ}|| jjƒ |jjƒ ƒ}|r@|dkr4tdƒ‚td| ƒ‚| 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 points)r*   rh   r4   rd   )rj   rt   Zadd_funcr'   r(   r(   r)   Ú__iadd__p  s    
zEccPoint.__iadd__c             C   s   | j ƒ }||7 }|S )z8Return a new point, the addition of this one and another)rz   )rj   rt   r{   r(   r(   r)   Ú__add__{  s    zEccPoint.__add__c             C   s^   t | dƒ}|dk rtdƒ‚t|ƒ}|| jjƒ t|ƒtt|ƒƒtt	dƒƒƒ}|rZtd| ƒ‚| S )zMultiply this point by a scalarÚscalarr   z?Scalar multiplication is only defined for non-negative integersr.   z%Error %d during scalar multiplication)
r*   rd   r
   rh   r4   r   r   r2   r   r   )rj   rŽ   Zscalar_funcZsbr'   r(   r(   r)   Ú__imul__‚  s    


zEccPoint.__imul__c             C   s   | j ƒ }||9 }|S )z2Return a new point, the scalar product of this one)rz   )rj   rŽ   r{   r(   r(   r)   Ú__mul__‘  s    zEccPoint.__mul__c             C   s
   | j |ƒS )N)r�   )rj   Z	left_handr(   r(   r)   Ú__rmul__˜  s    zEccPoint.__rmul__N)rG   )r\   r]   r^   Ú__doc__rr   ru   rw   rx   r|   rz   r   r€   r‚   Úpropertyrk   rl   r}   rg   r‡   r‰   rŒ   r�   r�   r�   r‘   r(   r(   r(   r)   r_   Ï  s*   
&r_   )ÚGc               @   sÎ   e Zd ZdZdd„ Zdd„ Zdd„ Zdd	„ Zd
d„ Zdd„ Z	dd„ Z
edd„ ƒZedd„ ƒZedd„ ƒZdd„ Zdd„ Zdd„ Zdd„ Zd0dd „Zd!d"„ Zd#d$„ Zd%d&„ Zd'd(„ Zd)d*„ Zd+d,„ Zd-d.„ Zd/S )1Ú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             K   sP  t |ƒ}|jddƒ}|jddƒ| _|jddƒ| _|jddƒ| _|dkrT| jrT| jj}|rhtdt|ƒ ƒ‚|tkr|t	d| ƒ‚t| | _
| j
j| _t| jdk	ƒt| jdk	ƒ }|dkrÊ| jdkrÆt	d	ƒ‚dS |d
krÚt	dƒ‚| jƒ �s0| jdk	röt	dƒ‚t| jƒ| _d| j  k�o| j
jk n  �sLt	dƒ‚�n| jdk	�rDt	dƒ‚| j
jdk�r¾t| jƒdk�rjt	dƒ‚tj| jƒjƒ }|dd… | _t|dd… ƒ}|d  dM  < |d d@ dB |d< n~| j
jdk�r<t| jƒdk�rät	dƒ‚tj| jƒjdƒ}|dd… | _t|dd… ƒ}|d  dM  < |d  dO  < d|d< tj|d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.
        rm   NÚdÚseedrt   z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 curvesrT   rH   z0Parameter seed must be 32 bytes long for Ed25519éø   é   é   r.   rX   é9   z.Parameter seed must be 57 bytes long for Ed448ér   éü   é7   é€   é8   Úlittle)Ú	byteorder)r8   ÚpopÚ_dÚ_seedrh   rf   Ú	TypeErrorre   r6   rd   r    r!   rm   Úintr   r   r=   r~   r2   r   ÚnewÚdigestÚ_prefixr„   r   ÚreadÚ
from_bytes)rj   ÚkwargsZkwargs_Ú
curve_nameÚcountZ	seed_hashÚtmpr(   r(   r)   rr   ×  s\    




"zEccKey.__init__c             C   s   | j jdkS )Nr   r   )r   r   )r    r!   )rj   r(   r(   r)   r   #  s    zEccKey._is_eddsac             C   s.   t |tƒsdS |jƒ | jƒ kr"dS |j| jkS )NF)rv   r•   Úhas_privateÚpointQ)rj   Úotherr(   r(   r)   rw   &  s
    
zEccKey.__eq__c             C   sZ   | j ƒ r6| jƒ r&dttj| jƒƒ }q:dt| jƒ }nd}| jj	\}}d| j
j|||f 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!   )rj   Úextrark   rl   r(   r(   r)   Ú__repr__/  s    zEccKey.__repr__c             C   s
   | j dk	S )zJ``True`` if this key can be used for making signatures or decrypting data.N)r¥   )rj   r(   r(   r)   r²   :  s    zEccKey.has_privatec       	      C   s€   d|  k o| j jk n  s t‚| j j}tjd|d�}| j| }|| j|ƒ}| j j| j| }||| ||   | }||fS )Nr   r�   )Úmin_inclusiveÚmax_exclusive)	r    r=   ÚAssertionErrorr   Úrandom_ranger¥   Úinverser”   rk   )	rj   ÚzÚkr=   ZblindZblind_dZinv_blind_kÚrÚsr(   r(   r)   Ú_sign@  s     
zEccKey._signc             C   sR   | j j}|d j|ƒ}| j j|| |  }| j||d  |  }|| j|d kS )Nr�   r   )r    r=   r¾   r”   r³   rk   )rj   r¿   Zrsr=   ZsinvZpoint1Zpoint2r(   r(   r)   Ú_verifyO  s
    zEccKey._verifyc             C   s   | j ƒ stdƒ‚| jS )NzThis is not a private ECC key)r²   rd   r¥   )rj   r(   r(   r)   r–   V  s    zEccKey.dc             C   s   | j ƒ stdƒ‚| jS )NzThis is not a private ECC key)r²   rd   r¦   )rj   r(   r(   r)   r—   \  s    zEccKey.seedc             C   s    | j d kr| jj| j | _ | j S )N)rh   r    r”   r¥   )rj   r(   r(   r)   r³   b  s    
zEccKey.pointQc             C   s   t | jj| jd�S )z^A matching ECC public key.

        Returns:
            a new :class:`EccKey` object
        )rm   rt   )r•   r    r!   r³   )rj   r(   r(   r)   Ú
public_keyh  s    zEccKey.public_keyc             C   sl   | j ƒ rtdƒ‚| jjƒ }|rH| jjjƒ r0d}nd}|| jjj|ƒ }n d| jjj|ƒ | jjj|ƒ }|S )Nz+SEC1 format is unsupported for EdDSA curvesó   ó   ó   )r   rd   r³   rg   rl   Úis_oddrk   Úto_bytes)rj   Úcompressrn   Ú
first_byterÅ   r(   r(   r)   Ú_export_SEC1q  s    
zEccKey._export_SEC1c             C   s„   | j j\}}| jjdkrDt|jddd�ƒ}|d@ d> |d B |d< n8| jjdkrtt|jd	dd�ƒ}|d@ d> |d
< ntdƒ‚t|ƒS )NrT   rH   r¢   )r£   r�   r…   rš   rX   rœ   r¡   zNot an EdDSA key to export)r³   r}   r    r~   r„   rÊ   rd   Úbytes)rj   rk   rl   r'   r(   r(   r)   Ú_export_eddsa�  s    zEccKey._export_eddsac             C   sD   | j ƒ r| jj}| jƒ }d }nd}| j|ƒ}t| jjƒ}t|||ƒS )Nz1.2.840.10045.2.1)r   r    ÚoidrÏ   rÍ   r   r   )rj   rË   rÐ   rÅ   Úparamsr(   r(   r)   Ú_export_subjectPublicKeyInfo™  s    
z#EccKey._export_subjectPublicKeyInfoTc             C   sx   | j ƒ st‚| jjƒ }d| jjj|ƒ | jjj|ƒ }dt| jj|ƒƒt	| j
jdd�t|dd�g}|sl|d= t|ƒjƒ S )NrÈ   r�   r   )Úexplicitr˜   )r²   r¼   r³   rg   rk   rÊ   rl   r   r–   r   r    rÐ   r   r   Úencode)rj   Úinclude_ec_paramsrn   rÅ   Úseqr(   r(   r)   Ú_export_rfc5915_private_der§  s    

z"EccKey._export_rfc5915_private_derc             K   sˆ   ddl m} |jdd ƒd k	r,d|kr,tdƒ‚| jƒ rP| jj}t| jƒj	ƒ }d }nd}| j
dd�}t| jjƒ}|j||fd	|i|—Ž}|S )
Nr   )ÚPKCS8Ú
passphraseÚ
protectionz3At least the 'protection' parameter must be presentz1.2.840.10045.2.1F)rÕ   Z
key_params)Ú	Crypto.IOrØ   r4   rd   r   r    rÐ   r   r¦   rÔ   r×   r   Úwrap)rj   r®   rØ   rÐ   Úprivate_keyrÑ   r'   r(   r(   r)   Ú_export_pkcs8Â  s    zEccKey._export_pkcs8c             C   s"   ddl m} | j|ƒ}|j|dƒS )Nr   )ÚPEMz
PUBLIC KEY)rÛ   rß   rÒ   rÔ   )rj   rË   rß   Úencoded_derr(   r(   r)   Ú_export_public_pem×  s    
zEccKey._export_public_pemc             K   s&   ddl m} | jƒ }|j|d|f|ŽS )Nr   )rß   zEC PRIVATE KEY)rÛ   rß   r×   rÔ   )rj   rÙ   r®   rß   rà   r(   r(   r)   Ú_export_private_pemÝ  s    zEccKey._export_private_pemc             C   s    ddl m} | jƒ }|j|dƒS )Nr   )rß   zPRIVATE KEY)rÛ   rß   rÞ   rÔ   )rj   rß   rà   r(   r(   r)   Ú(_export_private_clear_pkcs8_in_clear_pemã  s    z/EccKey._export_private_clear_pkcs8_in_clear_pemc             K   sD   ddl m} |st‚d|kr$tdƒ‚| jf d|i|—Ž}|j|dƒS )Nr   )rß   rÚ   z5At least the 'protection' parameter should be presentrÙ   zENCRYPTED PRIVATE KEY)rÛ   rß   r¼   rd   rÞ   rÔ   )rj   rÙ   r®   rß   rà   r(   r(   r)   Ú,_export_private_encrypted_pkcs8_in_clear_pemé  s    z3EccKey._export_private_encrypted_pkcs8_in_clear_pemc       	      C   sô   | j ƒ rtdƒ‚| jj}|d kr2td| jj ƒ‚n˜|dkrT| jƒ }t|ƒt|ƒf}nv| jjƒ }|rŠd| jj	j
ƒ  }t|ƒ| jjj|ƒ }n d| jjj|ƒ | jj	j|ƒ }|jdƒd }t|ƒt|ƒ|f}djdd	„ |D ƒƒ}|d
 ttj|ƒƒ S )Nz"Cannot export OpenSSH private keysz Cannot export %s keys as OpenSSHzssh-ed25519r˜   rÈ   ú-ó    c             S   s    g | ]}t jd t|ƒƒ| ‘qS )z>I)ÚstructÚpackr2   )Ú.0rk   r(   r(   r)   ú
<listcomp>  s    z*EccKey._export_openssh.<locals>.<listcomp>ú )r²   rd   r    Úopensshr~   rÏ   r   r³   rg   rl   rÉ   r   rk   rÊ   ÚsplitÚjoinr   r¶   Ú
b2a_base64)	rj   rË   r!   rÅ   Úcompsrn   rÌ   ÚmiddleZblobr(   r(   r)   Ú_export_opensshò  s&    
zEccKey._export_opensshc             K   s¢  |j ƒ }|jdƒ}|dkr&td| ƒ‚|jdd	ƒ}| jƒ �r|jd
dƒ}t|ƒrdt|ƒ}|sdtdƒ‚|jddƒ}|s”| jƒ r„tdƒ‚d|kr”tdƒ‚|dkrÌ|r¼|r²| j|f|ŽS | jƒ S n| j	|f|ŽS nL|dk�r|rè| rètdƒ‚|�r| j
f d
|i|—ŽS | jƒ S ntd| ƒ‚n„|�r,td| ƒ‚|dk�r@| j|ƒS |dk�rT| j|ƒS |dk�rh| j|ƒS |dk�r”| jjdk�rˆ| jƒ S | j|ƒS n
| j|ƒS d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.
        Úformatrß   ÚDERÚOpenSSHÚSEC1ÚrawzUnknown format '%s'rË   FrÙ   NzEmpty passphraseÚ	use_pkcs8Tz%'pkcs8' must be True for EdDSA curvesrÚ   z)'protection' is only supported for PKCS#8z8Private keys can only be encrpyted with DER using PKCS#8z2Private keys cannot be exported in the '%s' formatzUnexpected parameters: '%s'rT   rX   )rß   rô   rõ   rö   r÷   )rT   rX   )rz   r¤   rd   r²   r   r   r   rä   rã   râ   rÞ   r×   rá   rÒ   rÍ   r    r~   rÏ   rò   )rj   r®   ÚargsZ
ext_formatrË   rÙ   rø   r(   r(   r)   Ú
export_key  sX    U













zEccKey.export_keyN)T)r\   r]   r^   r’   rr   r   rw   r¹   r²   rÃ   rÄ   r“   r–   r—   r³   rÅ   rÍ   rÏ   rÒ   r×   rÞ   rá   râ   rã   rä   rò   rú   r(   r(   r(   r)   r•   Á  s.   L		
	r•   c              K   sœ   | j dƒ}t| }| j dtƒ}| r2tdt| ƒ ƒ‚t| jdkrV|dƒ}t||d�}nBt| jdkrz|dƒ}t||d�}ntjd	|j	|d
�}t||d�}|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.
    rm   ÚrandfunczUnknown parameters: rT   rH   )rm   r—   rX   rœ   r�   )rº   r»   rû   )rm   r–   )
r¤   r6   r   r§   re   r~   r•   r   r½   r=   )r®   r¯   rm   rû   r—   Únew_keyr–   r(   r(   r)   Úgeneratež  s     
rý   c              K   s”   | d }t | }| jddƒ}| jddƒ}d| kr8tdƒ‚d||fkrTt|||ƒ| d< tf | Ž}|jƒ r�d| kr�|j|j }|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
    rm   Úpoint_xNÚpoint_yrt   zUnknown keyword: pointz(Private and public ECC keys do not match)
r6   r¤   r§   r_   r•   r²   r”   r–   r}   rd   )r®   r¯   rm   rþ   rÿ   rü   Zpub_keyr(   r(   r)   Ú	constructÀ  s    
r   c       	      C   s\  xLt jƒ D ]"\}}|r"|j|kr"P ||kr
P q
W |rBtd| ƒ‚ntd| ƒ‚|jjƒ }t| d ƒ}|dkr¶t| ƒdd|  krˆtdƒ‚t	j
| d|d … ƒ}t	j
| |d d… ƒ}n˜|dk�rFt| ƒd| krØtdƒ‚t	j
| dd… ƒ}|d	 |d	  |j j|jƒ}|dk�r&|jƒ �r&|j| }|d	k�rN|jƒ �rN|j| }ntd
ƒ‚t|||d�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

    zUnsupported ECC curve (OID: %s)zUnsupported ECC curve (%s)r   é   r�   r˜   zIncorrect EC point lengthNé   zIncorrect EC point encoding)rm   rþ   rÿ   )r˜   r  )r6   ÚitemsrÐ   r[   r;   rg   r   r2   rd   r   r­   r<   ÚsqrtrÉ   Zis_evenr   )	Úec_pointÚ	curve_oidr¯   rf   rm   rn   Z
point_typerk   rl   r(   r(   r)   Ú_import_public_derö  s4    



r  c             G   sÆ   t | ƒ\}}}d}dtfdtfdœ}||krx|s<td| ƒ‚ytƒ j|ƒj}W n tk
rj   tdƒ‚Y nX t||d	�S ||kr¶|| \}}	|rœtd
| ƒ‚|	|ƒ\}
}t|
||d�S t	d| ƒ‚dS )z4Convert a subjectPublicKeyInfo into an EccKey objectú1.2.840.10045.2.1ú1.3.132.1.12ú1.3.132.1.13r   r   )z1.3.101.112z1.3.101.113z%Missing ECC parameters for ECC OID %szError decoding namedCurve)r  z(Unexpected ECC parameters for ECC OID %s)rþ   rÿ   rm   zUnsupported ECC OID: %sN)r  r	  r
  )
r   Ú_import_ed25519_public_keyÚ_import_ed448_public_keyrd   r   ÚdecodeÚvaluer  r   r[   )Úencodedr®   rÐ   r  rÑ   Únist_p_oidsÚ
eddsa_oidsr  r¯   Úimport_eddsa_public_keyrk   rl   r(   r(   r)   Ú_import_subjectPublicKeyInfo.  s*      
r  c             C   sB  t ƒ j| dd�}|d dkr$tdƒ‚y6tdd�j|d ƒj}|d k	rT||krTtd	ƒ‚|}W n tk
rn   Y nX |d kr€td
ƒ‚x,tjƒ D ]\}}|j|krŠP qŠW td| ƒ‚t	ƒ j|d ƒj
}|jjƒ }t|ƒ|krÞtdƒ‚tj|ƒ}	t|ƒdk�r*tdd�j|d ƒj}
t|
|d�}|jj}|jj}nd  }}t||	||d�S )Nr  r  )Znr_elementsr   r�   z!Incorrect ECC private key version)rÓ   r˜   zCurve mismatchzNo curve foundzUnsupported ECC curve (OID: %s)zPrivate key is too small)r  )rm   r–   rþ   rÿ   )r  r  éÿÿÿÿ)r   r  rd   r   r  r6   r  rÐ   r[   r   Úpayloadr;   rg   r2   r   r­   r   r  r³   rk   rl   r   )r  rÙ   r  rÝ   Ú
parametersr¯   rm   Zscalar_bytesrn   r–   Zpublic_key_encrÅ   rþ   rÿ   r(   r(   r)   Ú_import_rfc5915_derb  s8    



r  c       
      C   s˜   ddl m} |j| |ƒ\}}}d}dddœ}||krNtƒ j|ƒj}t|||ƒS ||krˆ|d k	rftd	ƒ‚d }tƒ j|ƒj	}	t
|| |	d
�S td| ƒ‚d S )Nr   )rØ   ú1.2.840.10045.2.1ú1.3.132.1.12ú1.3.132.1.13r   r   )z1.3.101.112z1.3.101.113z.EdDSA ECC private key must not have parameters)rm   r—   z!Unsupported ECC purpose (OID: %s))r  r  r  )rÛ   rØ   Úunwrapr   r  r  r  rd   r   r  r   r[   )
r  rÙ   rØ   Zalgo_oidrÝ   rÑ   r  r  r  r—   r(   r(   r)   Ú_import_pkcs8”  s"      r  c             G   s   t | ƒ}t|ƒS )N)r   r  )r  r®   Zsp_infor(   r(   r)   Ú_import_x509_cert°  s    r  c          :   C   s8  y
t | |ƒS  tk
r0 } z
|‚W Y d d }~X n tttfk
rH   Y nX y
t| |ƒS  tk
rz } z
|‚W Y d d }~X n tttfk
r’   Y nX y
t| |ƒS  tk
rÄ } z
|‚W Y d d }~X n tttfk
rÜ   Y nX y
t| |ƒS  tk
�r } z
|‚W Y d d }~X n tttfk
�r*   Y nX tdƒ‚d S )NzNot an ECC DER key)r  r[   rd   r§   Ú
IndexErrorr  r  r  )r  rÙ   Úerrr(   r(   r)   Ú_import_der¶  s2    



r   c             C   s’  | j dƒ}t|ƒdkrtdƒ‚�y>tj|d ƒ}g }xNt|ƒdkr‚tjd|d d… ƒd }|j|dd| … ƒ |d| d … }q6W |d |d krœtd	ƒ‚|d jd
ƒ�rx\t	j
ƒ D ]D\}}|jd krÊq¶|jjdƒsØq¶t|jj dƒd ƒ}|d |kr¶P q¶W td| ƒ‚t|d |jd�}n>|d dk�rLt|d ƒ\}	}
td|	|
d�}ntd|d  ƒ‚W n. tttjfk
�rŒ   td|d  ƒ‚Y nX |S )Nó    r˜   r  zNot an openssh public keyr�   r  z>Ir   zMismatch in openssh public keys   ecdsa-sha2-z
ecdsa-sha2rå   zUnsupported ECC curve: )r  s   ssh-ed25519r   )rm   rþ   rÿ   zUnsupported SSH key type: zError parsing SSH key type: )r˜   r  )rí   r2   rd   r¶   Ú
a2b_base64rç   ÚunpackÚappendÚ
startswithr6   r  rì   r   r  rÐ   r  r   r  r§   ÚError)r  ÚpartsZ	keystringZkeypartsZlkr¯   rm   rñ   Zecc_keyrk   rl   r(   r(   r)   Ú_import_openssh_public×  s<    

r(  c             C   sŒ  ddl m}m}m}m} || |ƒ\}}ddtdfi}|jdƒ�r||ƒ\}	}|	tkr`td|	 ƒ‚t|	 }
|
j	d d	 }||ƒ\}}t
|d
 ƒdkrštdƒ‚t|ƒd| d kr¶tdƒ‚tj|dd| … ƒ}tj|d| d … ƒ}||ƒ\}}tj|ƒ}||	dœ}n`||k�rX|| \}}}||ƒ\}}||ƒ\}}||ƒ\}}|d |… }||dœ}ntd| ƒ‚||ƒ\}}||ƒ tf ||dœ|—ŽS )Nr�   )Úimport_openssh_private_genericÚ
read_bytesÚread_stringÚcheck_paddingzssh-ed25519r   rH   z
ecdsa-sha2zUnsupported ECC curve %sr…   r†   r   r  z/Only uncompressed OpenSSH EC keys are supportedr˜   zIncorrect public key length)r–   rm   )r—   rm   zUnsupport SSH agent key type:)rþ   rÿ   )Z_opensshr)  r*  r+  r,  r  r%  r6   r[   rˆ   r   rd   r2   r   r­   r   )ÚdataÚpasswordr)  r*  r+  r,  Zkey_typeZ	decryptedZ
eddsa_keysZecdsa_curve_namerm   rn   rÅ   rþ   rÿ   rÝ   r–   rÑ   r¯   r  Zseed_lenZprivate_public_keyr—   Ú_Zpaddedr(   r(   r)   Ú_import_openssh_private_ecc  s<    

r0  c             C   sö   t | ƒdkrtdƒ‚tdƒ}d}t| ƒ}|d d? }|d  dM  < tj|dd	�}||krbtd
ƒ‚|dkrndS |d d | }|d | | d | }y:|j|ƒ}|| | }	tj|	|ƒ}
|
d@ |krÎ||
 }
W n tk
rì   tdƒ‚Y nX |
|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
    rH   z9Incorrect length. Only Ed25519 public keys are supported.l   íÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿl   £x²&(7Z/·
;(P8 ÑsÝe:Ì8ÎÛ
w6Rrš   r…   r›   r¢   )r£   zInvalid Ed25519 key (y)r�   r   r˜   zInvalid Ed25519 public key)r   r�   )r2   rd   r   r„   r­   r¾   Ú_tonelli_shanks)r  r;   r–   rl   Úx_lsbrÿ   ÚuÚvÚv_invÚx2rþ   r(   r(   r)   r  <  s.    
r  c             C   sî   t | ƒdkrtdƒ‚tdƒ}d}| dd… }t| d ƒd? }tj|dd	�}||krZtd
ƒ‚|dkrfdS |d d | }|d | | d | }y:|j|ƒ}|| | }	tj|	|ƒ}
|
d@ |krÆ||
 }
W n tk
rä   tdƒ‚Y nX |
|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.l   ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿ?ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿl   Vgþÿÿÿÿÿÿÿÿÿÿÿÿÿ?ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿNr¡   r…   r¢   )r£   zInvalid Ed448 key (y)r�   r   r˜   zInvalid Ed448 public key)r   r�   )r2   rd   r   r   r­   r¾   r1  )r  r;   r–   rl   r2  rÿ   r3  r4  r5  r6  rþ   r(   r(   r)   r  i  s,    
r  c             C   s‚  ddl m} t| ƒ} |dk	r$t|ƒ}| jdƒrVt| ƒ}|j||ƒ\}}}t||ƒ}|S | jdƒrút| ƒ}d}	d}
tj|	d |
 d	|tj	d
�}|j||ƒ\}}}|r¦d}yt
||ƒ}W n@ tk
rÚ } z
|‚W Y dd}~X n tk
rô   tdƒ‚Y nX |S | jdƒ�rt| ƒS t| ƒdk�r8t| d ƒdk�r8t
| |ƒS t| ƒdk�rvt| d ƒdk�rv|dk�rjtdƒ‚t| |d�S tdƒ‚dS )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   )rß   Ns   -----BEGIN OPENSSH PRIVATE KEYs   -----z-----BEGIN EC PARAMETERS-----z-----END EC PARAMETERS-----z.*?rµ   )Úflagsz(Invalid DER encoding inside the PEM fileó   ecdsa-sha2-ó   ssh-ed25519rM   r˜   r  r  zNo curve name was provided)r¯   zECC key format is not supported)r8  r9  )r˜   r  r  )rÛ   rß   r   r%  r   r  r0  ÚreÚsubÚDOTALLr   r[   rd   r(  r2   r   r  )r  rÙ   r¯   rß   Ztext_encodedZopenssh_encodedÚmarkerZenc_flagr'   Zecparams_startZecparams_endZder_encodedZuefr(   r(   r)   Ú
import_key•  sF    ?



 
 
r>  Ú__main__l   ýö_,)¶NÌ$ÔcÐhKf-5lk<X÷k©#E i¸  z	(P-256 G)iè  Úmsz(P-256 arbitrary point))NN)N)NN)pÚ
__future__r   r:  rç   r¶   Úcollectionsr   ZCrypto.Util.py3compatr   r   r   r   r   ZCrypto.Util.numberr	   r
   ZCrypto.Math.Numbersr   ZCrypto.Util.asn1r   r   r   r   ZCrypto.Util._raw_apir   r   r   r   r   r   r   ZCrypto.PublicKeyr   r   r   ZCrypto.Hashr   r   ZCrypto.Randomr   ZCrypto.Random.randomr   r%   r#   r$   r*   r+   r6   r:   rA   rE   rF   rJ   rK   rN   rO   rR   rS   rV   rW   rY   rZ   rd   r[   Úobjectr_   r>   r?   Zp192_GÚ_replacer,   r7   r8   r9   Zp224_GrB   Zp256_GrG   Zp384_GrL   Zp521_GrP   Z	ed25519_GrT   Zed448_GrX   r•   rý   r   r  r  r  r  r  r   r(  r0  r  r  r>  r\   Útimer–   r”   rz   rt   r°   ÚstartÚrangerk   ZpointXÚprintr(   r(   r(   r)   Ú<module>   sè   $

'
'
'
'
' O   `"6
84
2!.7-,
t
