ffugdZddlZddlZddlmZddlmZmZmZddl m Z m Z ddl m Z ddlmZmZmZddlmZmZmZGd d eZdd ZddZdZdZdZdZdZdZdZ ddZ!e!Z"dZ#dS))generate construct import_keyRsaKeyoidN)Random)tobytesbordtostr) DerSequenceDerNull)Integer)test_probable_primegenerate_probable_prime COMPOSITE)_expand_subject_public_key_info_create_subject_public_key_info _extract_subject_public_key_infoceZdZdZdZedZedZedZedZ edZ edZ ed Z ed Z ed Zed Zd ZdZdZdZdZdZdZdZdZdZdZdZdZ d%dZeZeZdZ dZ!d Z"d!Z#d"Z$d#Z%d$Z&dS)&raClass defining an actual RSA key. Do not instantiate directly. Use :func:`generate`, :func:`construct` or :func:`import_key` instead. :ivar n: RSA modulus :vartype n: integer :ivar e: RSA public exponent :vartype e: integer :ivar d: RSA private exponent :vartype d: integer :ivar p: First factor of the RSA modulus :vartype p: integer :ivar q: Second factor of the RSA modulus :vartype q: integer :ivar invp: Chinese remainder component (:math:`p^{-1} \text{mod } q`) :vartype invp: integer :ivar invq: Chinese remainder component (:math:`q^{-1} \text{mod } p`) :vartype invq: integer :ivar u: Same as ``invp`` :vartype u: integer :undocumented: exportKey, publickey c t|}td}|tdz}|||fvrtd|D]\}}t |d|z|||kr7|j|jdz z|_|j|jdz z|_ d|_ dSdS)a.Build an RSA key. :Keywords: n : integer The modulus. e : integer The public exponent. d : integer The private exponent. Only required for private keys. p : integer The first factor of the modulus. Only required for private keys. q : integer The second factor of the modulus. Only required for private keys. u : integer The CRT coefficient (inverse of p modulo q). Only required for private keys. ne)pqduzSome RSA components are missing_N) setkeys ValueErroritemssetattr_d_p_dp_q_dq_invq)selfkwargs input_set public_set private_set componentvalues v/builddir/build/BUILD/imunify360-venv-2.3.5/opt/imunify360/venv/lib64/python3.11/site-packages/Crypto/PublicKey/RSA.py__init__zRsaKey.__init__Ss& && __  3';#<#<< [*5 5 5>?? ? &  2 2 Iu D# /5 1 1 1 1  # #w$'A+.DHw$'A+.DHDJJJ $ #c*t|jSN)int_nr+s r2rzRsaKey.nr47||r4c*t|jSr6)r7_er9s r2rzRsaKey.evr:r4cp|stdt|jS)Nz-No private exponent available for public keys) has_privateAttributeErrorr7r%r9s r2rzRsaKey.dzs4!! R !PQQ Q47||r4cp|stdt|jS)Nz.No CRT component 'p' available for public keys)r>r?r7r&r9s r2rzRsaKey.p4!! S !QRR R47||r4cp|stdt|jS)Nz.No CRT component 'q' available for public keys)r>r?r7r(r9s r2rzRsaKey.qrAr4cp|stdt|jS)Nz/No CRT component 'dp' available for public keys)r>r?r7r'r9s r2dpz RsaKey.dp4!! T !RSS S48}}r4cp|stdt|jS)Nz/No CRT component 'dq' available for public keys)r>r?r7r)r9s r2dqz RsaKey.dqrEr4c|std|j$|j|j|_t |jS)Nz1No CRT component 'invq' available for public keys)r>r?r*r(inverser&r7r9s r2invqz RsaKey.invqsS!! V !TUU U : 11DJ4:r4c|jSr6)rr9s r2invpz RsaKey.invps v r4cp|stdt|jS)Nz.No CRT component 'u' available for public keys)r>r?r7_ur9s r2rzRsaKey.urAr4c4|jS)zSize of the RSA modulus in bitsr8 size_in_bitsr9s r2rQzRsaKey.size_in_bitssw##%%%r4cF|jdz dzdzS)z9The minimal amount of bytes that can hold the RSA modulusrrPr9s r2 size_in_byteszRsaKey.size_in_bytess%$$&&*q0144r4cd|cxkr |jksntdttt ||j|jS)NrzPlaintext too large)r8r"r7powrr<)r+ plaintexts r2_encryptzRsaKey._encryptsXI''''''''233 33wy))47DG<<===r4cd|cxkr |jksntd|stdt jd|j}t |t ||j|jz|jz}t ||j|j }t ||j |j }||z |j z|j z}||j z|z}| |j|z|jz}|t ||j|jkrtd|S)NrzCiphertext too largezThis is not a private keyr) min_inclusive max_exclusivez Fault detected in RSA decryption)r8r"r> TypeErrorr random_rangerVr<r'r&r)r(rNrI) r+ ciphertextrcpm1m2hmpresults r2_decryptzRsaKey._decrypts6J((((((((344 4!! 9788 8  q H H H Z 3q$'47#;#; ;dg E TXtw ' ' TXtw ' '2g DG + [2 ))DG$$r)TW4 VTWdg66 6 6?@@ @ r4c"t|dS)z"Whether this is an RSA private keyr%)hasattrr9s r2r>zRsaKey.has_privatestT"""r4cdSNTr9s r2 can_encryptzRsaKey.can_encrypttr4cdSrjrkr9s r2can_signzRsaKey.can_signrmr4c8t|j|jS)z^A matching RSA public key. Returns: a new :class:`RsaKey` object r)rr8r<r9s r2 public_keyzRsaKey.public_keys 47++++r4c||krdS|j|jks|j|jkrdS|sdS|j|jkS)NFT)r>rrrr+others r2__eq__z RsaKey.__eq__st     !2!2!4!4 4 45 6UW  %' 1 15!! 4%'!"r4c||k Sr6rkrss r2__ne__z RsaKey.__ne__sEM""r4cddlm}|)Nr) PicklingError)picklery)r+rys r2 __getstate__zRsaKey.__getstate__s((((((r4c*|rRdt|jt|jt|jt|jfz}nd}dt|jt|j|fzS)Nz, d=%d, p=%d, q=%d, u=%dzRsaKey(n=%d, e=%d%s))r>r7r%r&r(rNr8r<)r+extras r2__repr__zRsaKey.__repr__s{      .#dg,,DG 25dg,,DG 2NNEEE%TWs47||U(KKKr4c\|rd}nd}d|t|fzS)NPrivatePublicz%s RSA key at 0x%X)r>id)r+key_types r2__str__zRsaKey.__str__s8       HHH#xD&:::r4PEMNrc |t|}| tj}|dkrd|j|jfD\}}t |ddzrd|z}t |ddzrd|z}d||g}dd |D} d tj| dd zS| rtd|j |j |j |j|j|j |jd z z|j |jd z zt!|j|jg } |d krd } |dkr|rt'dnddlm} |dkr/|-d} | | t.dt1} nqd} |sd}| | t.||t1} d}n=d} t3t.t|j |j gt1} |dkr| S|dkr-ddlm} | | | ||}t|St'd|z)a% Export this RSA key. Args: format (string): The format to use for wrapping the key: - *'PEM'*. (*Default*) Text encoding, done according to `RFC1421`_/`RFC1423`_. - *'DER'*. Binary encoding. - *'OpenSSH'*. Textual encoding, done according to OpenSSH specification. Only suitable for public keys (not private keys). passphrase (string): (*For private keys only*) The pass phrase used for protecting the output. pkcs (integer): (*For private keys only*) The ASN.1 structure to use for serializing the key. Note that even in case of PEM encoding, there is an inner ASN.1 DER structure. With ``pkcs=1`` (*default*), the private key is encoded in a simple `PKCS#1`_ structure (``RSAPrivateKey``). With ``pkcs=8``, the private key is encoded in a `PKCS#8`_ structure (``PrivateKeyInfo``). .. note:: This parameter is ignored for a public key. For DER and PEM, an ASN.1 DER ``SubjectPublicKeyInfo`` structure is always used. protection (string): (*For private keys only*) The encryption scheme to use for protecting the private key. If ``None`` (default), the behavior depends on :attr:`format`: - For *'DER'*, the *PBKDF2WithHMAC-SHA1AndDES-EDE3-CBC* scheme is used. The following operations are performed: 1. A 16 byte Triple DES key is derived from the passphrase using :func:`Crypto.Protocol.KDF.PBKDF2` with 8 bytes salt, and 1 000 iterations of :mod:`Crypto.Hash.HMAC`. 2. The private key is encrypted using CBC. 3. The encrypted key is encoded according to PKCS#8. - For *'PEM'*, the obsolete PEM encryption scheme is used. It is based on MD5 for key derivation, and Triple DES for encryption. Specifying a value for :attr:`protection` is only meaningful for PKCS#8 (that is, ``pkcs=8``) and only if a pass phrase is present too. The supported schemes for PKCS#8 are listed in the :mod:`Crypto.IO.PKCS8` module (see :attr:`wrap_algo` parameter). randfunc (callable): A function that provides random bytes. Only used for PEM encoding. The default is :func:`Crypto.Random.get_random_bytes`. Returns: byte string: the encoded key Raises: ValueError:when the format is unknown or when you try to encrypt a private key with *DER* format and PKCS#1. .. warning:: If you don't provide a pass phrase, the private key will be exported in the clear! .. _RFC1421: http://www.ietf.org/rfc/rfc1421.txt .. _RFC1423: http://www.ietf.org/rfc/rfc1423.txt .. _`PKCS#1`: http://www.ietf.org/rfc/rfc3447.txt .. _`PKCS#8`: http://www.ietf.org/rfc/rfc5208.txt NOpenSSHc6g|]}|Srk)to_bytes.0xs r2 z%RsaKey.export_key..Vs III IIIr4rsssh-rsar4cXg|]'}tjdt||z(S)>I)structpacklen)rkps r2rz%RsaKey.export_key..\s/!U!U!Ub&+dCGG"<"r rrrrrrrIencoder" Crypto.IOrwraprr rr)r+format passphrasepkcs protectionrandfunce_bytesn_byteskeyparts keystring binary_keyrrrpem_strs r2 export_keyzRsaKey.export_keysZ  ! ,,J  .H Y  IItw6HIII GWGAJ$& ,!G+GAJ$& ,!G+"GW5H!U!UH!U!U!UVVI!4Y!?!?!DD D     $ ;$a&*f&*f&*f&*f&*f&*fq&9&*fq&9&-dfoo&=&=df&E&E &( ) )*0 qyy,U??z?$%MNNN++++++U??z'9,H!&JT7>yy","B"BJJ 7H%J%I !&J,6 7>yy","B"BJ"&JJ#H89DdfFJfFN:O:O9@;;J U??  U?? % % % % % %jjXz8LLG7## #NQWWXXXr4c tdNz,Use module Crypto.Signature.pkcs1_15 insteadNotImplementedError)r+MKs r2signz RsaKey.sign!"PQQQr4c tdrr)r+r signatures r2verifyz RsaKey.verifyrr4c tdNz+Use module Crypto.Cipher.PKCS1_OAEP insteadr)r+rWrs r2encryptzRsaKey.encrypt!"OPPPr4c tdrr)r+r^s r2decryptzRsaKey.decryptrr4ctr6rr+rBs r2blindz RsaKey.blind!!r4ctr6rrs r2unblindzRsaKey.unblindrr4ctr6rr9s r2sizez RsaKey.sizerr4)rNrNN)'__name__ __module__ __qualname____doc__r3propertyrrrrrrDrGrJrLrrQrTrXrfr>rlrorqrurwr{rrr exportKey publickeyrrrrrrrrkr4r2rr3s>>XXX X X X X XXX &&&555>>> 0### ,,,###### LLL;;;>?-1MYMYMYMY`IIRRRRRRQQQQQQ"""""""""""r4rc |dkrtddzdksdkrtd| tj}tdx}}t||kr|d|dzzkr |dz}||z }tdd|zdz zx ||kr*tdd|zdz z  fd }t ||| td|dzd z z  fd }t ||| } | z}dz | dz } | }||kr |d|dzzk | kr| c} | } t||| | S)a0Create a new RSA key pair. The algorithm closely follows NIST `FIPS 186-4`_ in its sections B.3.1 and B.3.3. The modulus is the product of two non-strong probable primes. Each prime passes a suitable number of Miller-Rabin tests with random bases and a single Lucas test. Args: bits (integer): Key length, or size (in bits) of the RSA modulus. It must be at least 1024, but **2048 is recommended.** The FIPS standard only defines 1024, 2048 and 3072. randfunc (callable): Function that returns random bytes. The default is :func:`Crypto.Random.get_random_bytes`. e (integer): Public RSA exponent. It must be an odd positive integer. It is typically a small number with very few ones in its binary representation. The FIPS standard requires the public exponent to be at least 65537 (the default). Returns: an RSA key object (:class:`RsaKey`, with private key). .. _FIPS 186-4: http://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf iz"RSA modulus length must be >= 1024rzBRSA public exponent must be a positive, odd integer larger than 2.NrcH|ko|dz dkSNr)gcd) candidatermin_ps r2filter_pzgenerate..filter_ps*u$D)a-)<).filter_qsH%6]''**a/6 A &&5 7r4rrrrrr) r"rrrrQsqrtrlcmrIr)bitsrrrrsize_qsize_prrrrrrrrrs ` @@@@r2rrsB: d{{=>>>1uzzQUU]^^^* AJJA A ..  d " "qA$!),<'='= F Q7==??? V  QZZAJN399;;E E E E E E E $v-519 ; ; ;qzzdai#o6  7 7 7 7 7 7 7 7 $v-519 ; ; ; E1ukk!a%   IIcNN? ..  d " "qA$!),<'='=B 1uu!1 ! A Aa1Q / / //r4Tc6Gddt}|}td|D]#\}}t||t|$|j}|j}t |dst||}nM|j} t |dr|j } |j } n| |zdz } | } | dzd kr| dz} | dzd kd }td}|s|d krt| }|| krht|||}|dkrF||dz kr=t|d|dkr(t| |dz} d }n |dz}|| kh|dz }|s|d k|std || zd ksJ|| z} t |dr|j}n| | }t||| | | |}|r|dks||krtdt| |dkrtd|dzstd|rM| dks| |krtdt| | dkrtd| | z|krtdt#| t$krtdt#| t$krtd| dz | dz z}|| dz | dz z}|| zt'|zdkrtdt |dr6|dks|| krtd| |z| zdkrtd|S)a!Construct an RSA key from a tuple of valid RSA components. The modulus **n** must be the product of two primes. The public exponent **e** must be odd and larger than 1. In case of a private key, the following equations must apply: .. math:: \begin{align} p*q &= n \\ e*d &\equiv 1 ( \text{mod lcm} [(p-1)(q-1)]) \\ p*u &\equiv 1 ( \text{mod } q) \end{align} Args: rsa_components (tuple): A tuple of integers, with at least 2 and no more than 6 items. The items come in the following order: 1. RSA modulus *n*. 2. Public exponent *e*. 3. Private exponent *d*. Only required if the key is private. 4. First factor of *n* (*p*). Optional, but the other factor *q* must also be present. 5. Second factor of *n* (*q*). Optional. 6. CRT coefficient *q*, that is :math:`p^{-1} \text{mod }q`. Optional. consistency_check (boolean): If ``True``, the library will verify that the provided components fulfil the main RSA properties. Raises: ValueError: when the key being imported fails the most basic RSA validity checks. Returns: An RSA key object (:class:`RsaKey`). ceZdZdS)construct..InputCompsN)rrrrkr4r2 InputCompsr%s r4rrrrrrrrFrTz2Unable to compute factors p and q from exponent d.rzInvalid RSA public exponentz-RSA public exponent is not coprime to moduluszRSA modulus is not oddzInvalid RSA private exponentz.RSA private exponent is not coprime to modulusz RSA factors do not match moduluszRSA factor p is compositezRSA factor q is compositezInvalid RSA conditionzInvalid RSA component uzInvalid RSA component u with p)objectzipr$rrrrhrrrrrVrr"rrIr>rrr7)rsa_componentsconsistency_checkr input_compscompr1rrkeyrrrktottspottedakcandrphirs r2rrs1P     V   *,,K;^LL33 u T75>>2222 A A ; $ $33qA M ; $ $'  A AA q519DAa%1**aa%1**G A !c''AJJ$hhq!Q<>!   ! !LMM M1u 7566 6 ??   GAvva !?@@@qzz~~a  A%% !QRRR1uzz !CDDD"1%%22 !<==="1%%22 !<===q5QU#C!a%QU+++CAC Q&& !8999sC   G66Q!VV$%>???EAI!##$%EFFF Jr4ct|dd}|ddkrtdt|ddt |d|d gzS) N T nr_elementsonly_ints_expectedrz(No PKCS#1 encoding of an RSA private keyr)r decoder"rrrIencodedr,ders r2_import_pkcs1_privatersx --  wA$  O OC 1v{{CDDD S1XQ!8!8Q!@!@ AA B BBr4cht|dd}t|S)NrTr)r rrrs r2_import_pkcs1_publicr s. --  wA$  O OC S>>r4c~t|\}}}|tks|tdt|S)NzNo RSA subjectPublicKeyInfo)rrr"r )rr,algoid encoded_keyparamss r2_import_subjectPublicKeyInforsA"A'"J"JFK }}*6777  , ,,r4c>t|}t|Sr6)rr)rr,sp_infos r2_import_x509_certrs.w77G ' 0 00r4cddlm}|||}|dtkrt dt |d|S)NrrzNo PKCS#8 encoded RSA keyr)rrunwraprr"_import_keyDER)rrrrs r2 _import_pkcs8rsW Wj))Ats{{4555 !A$ + ++r4ctttttf}|D] } |||cS#t $rYwxYwt d)z@Import an RSA key (public or private half), encoded in DER form.RSA key format is not supported)rr rrrr") extern_keyr decodingsdecodings r2rrsy'%-"  I  8J 33 3 3 3    D  6 7 77s 4 AAc~ddlm}m}m}m}|||\}}|dkrt d||\}}||\} }||\} }||\} }||\} }||\} }||\}}||d|| | | | | fD}t |S)Nr)import_openssh_private_generic read_bytes read_string check_paddingzssh-rsazThis SSH key is not RSAc6g|]}tj|Srk)r from_bytesrs r2rz/_import_openssh_private_rsa..s# B B BqW  " " B B Br4)_opensshrrrr r"r)datapasswordrrrr ssh_name decryptedrrriqmprrrpaddedbuilds r2_import_openssh_private_rsar+s@CCCCCCCCCCCC98xHHHi92333:i((LAy:i((LAy:i((LAy j++OD):i((LAy:i((LAy I&&IAvM& B BQ1aD,A B B BE U  r4c"ddlm}t|}|t|}|dr;t |}|||\}}}t ||}|S|dr;|t ||\}}}|rd}t||S|drtj | dd} g} t| d krctj d | dd d} | | d d | z| d | zd} t| d kctj| d} tj| d } t#| | gSt|dkr)t%|dd krt||St'd )aImport an RSA key (public or private). Args: extern_key (string or byte string): The RSA key to import. The following formats are supported for an RSA **public key**: - X.509 certificate (binary or PEM format) - X.509 ``subjectPublicKeyInfo`` DER SEQUENCE (binary or PEM encoding) - `PKCS#1`_ ``RSAPublicKey`` DER SEQUENCE (binary or PEM encoding) - An OpenSSH line (e.g. the content of ``~/.ssh/id_ecdsa``, ASCII) The following formats are supported for an RSA **private key**: - PKCS#1 ``RSAPrivateKey`` DER SEQUENCE (binary or PEM encoding) - `PKCS#8`_ ``PrivateKeyInfo`` or ``EncryptedPrivateKeyInfo`` DER SEQUENCE (binary or PEM encoding) - OpenSSH (text format, introduced in `OpenSSH 6.5`_) For details about the PEM encoding, see `RFC1421`_/`RFC1423`_. passphrase (string or byte string): For private keys only, the pass phrase that encrypts the key. Returns: An RSA key object (:class:`RsaKey`). Raises: ValueError/IndexError/TypeError: When the given key cannot be parsed (possibly because the pass phrase is wrong). .. _RFC1421: http://www.ietf.org/rfc/rfc1421.txt .. _RFC1423: http://www.ietf.org/rfc/rfc1423.txt .. _`PKCS#1`: http://www.ietf.org/rfc/rfc3447.txt .. _`PKCS#8`: http://www.ietf.org/rfc/rfc5208.txt .. _`OpenSSH 6.5`: https://flak.tedunangst.com/post/new-openssh-key-format-and-bcrypt-pbkdf rrNs-----BEGIN OPENSSH PRIVATE KEYs-----r rrrr0r)rrr startswithr rr+rr a2b_base64splitrrunpackappendrr"rr r")rrr text_encodedopenssh_encodedmarkerenc_flagrerrrlengthrrs r2rrsR$$JZ(( >??Z(( ,/JJ|Z,P,P),_jII X&&/"%**U:->-> "K"Kfh  Jc:...[)) !' (8(8(>(>q(ABB )nnq  ]42A277:F OOIaF l3 4 4 4!!f*++.I)nnq    x{ + +  x{ + +!Q    :tJqM22d::j*555 6 7 77r4z1.2.840.113549.1.1.1)Nr)Tr6)$__all__rrCryptorCrypto.Util.py3compatr r r Crypto.Util.asn1r r Crypto.Math.NumbersrCrypto.Math.PrimalityrrrCrypto.PublicKeyrrrrrrrrr rrrrr+r importKeyrrkr4r2rAs@    666666666611111111''''''GGGGGGGGGG@@@@@@@@@@ v"v"v"v"v"Vv"v"v"r N0N0N0N0bLLLL^CCC(---111 ,,,888$0L8L8L8L8`  r4