ó õùPc@s¾dZdZddddddgZdd lZejd d koSejd d krcdd lTndd lTddlmZm Z m Z ddl m Z m Z mZddlmZddlmZmZmZdd lZdd lZddlmZddlmZyddl mZWnek r6eZnXdejfd„ƒYZdefd„ƒYZeedƒeƒjƒgƒjƒZ eƒZ!e!j"Z"e!j#Z#e!j$Z$e!j%Z%d S(s†RSA public-key cryptography algorithm (signature and encryption). RSA_ is the most widespread and used public key algorithm. Its security is based on the difficulty of factoring large integers. The algorithm has withstood attacks for 30 years, and it is therefore considered reasonably secure for new designs. The algorithm can be used for both confidentiality (encryption) and authentication (digital signature). It is worth noting that signing and decryption are significantly slower than verification and encryption. The cryptograhic strength is primarily linked to the length of the modulus *n*. In 2012, a sufficient length is deemed to be 2048 bits. For more information, see the most recent ECRYPT_ report. Both RSA ciphertext and RSA signature are as big as the modulus *n* (256 bytes if *n* is 2048 bit long). This module provides facilities for generating fresh, new RSA keys, constructing them from known components, exporting them, and importing them. >>> from Crypto.PublicKey import RSA >>> >>> key = RSA.generate(2048) >>> f = open('mykey.pem','w') >>> f.write(RSA.exportKey('PEM')) >>> f.close() ... >>> f = open('mykey.pem','r') >>> key = RSA.importKey(f.read()) Even though you may choose to directly use the methods of an RSA key object to perform the primitive cryptographic operations (e.g. `_RSAobj.encrypt`), it is recommended to use one of the standardized schemes instead (like `Crypto.Cipher.PKCS1_v1_5` or `Crypto.Signature.PKCS1_v1_5`). .. _RSA: http://en.wikipedia.org/wiki/RSA_%28algorithm%29 .. _ECRYPT: http://www.ecrypt.eu.org/documents/D.SPA.17.pdf :sort: generate,construct,importKey,error s$Id$tgeneratet constructterrort importKeytRSAImplementationt_RSAobjiÿÿÿÿNiii(t*(tgetRandomRanget bytes_to_longt long_to_bytes(t_RSAt _slowmathtpubkey(tRandom(t DerObjectt DerSequencetDerNull(tinverse(t _fastmathcBsûeZdZddddddgZdd„Zd„Zd „Zd „Zd „Z d „Z d „Z d„Z d„Z d„Zdd„Zd„Zd„Zd„Zd„Zd„Zd„Zd„Zd„Zd„Zd„Zdddd„ZRS( slClass defining an actual RSA key. :undocumented: __getstate__, __setstate__, __repr__, __getattr__ tntetdtptqtucCs=||_||_|dkr0tjƒj}n||_dS(N(timplementationtkeytNoneR tnewtreadt _randfunc(tselfRRtrandfunc((s/..\python\site-packages\Crypto\PublicKey\RSA.pyt__init__qs    cCs?||jkrt|j|ƒStd|jj|fƒ‚dS(Ns%s object has no %r attribute(tkeydatatgetattrRtAttributeErrort __class__t__name__(Rtattrname((s/..\python\site-packages\Crypto\PublicKey\RSA.pyt __getattr__xscCstjj|||ƒS(sÏEncrypt a piece of data with RSA. :Parameter plaintext: The piece of data to encrypt with RSA. It may not be numerically larger than the RSA module (**n**). :Type plaintext: byte string or long :Parameter K: A random parameter (*for compatibility only. This value will be ignored*) :Type K: byte string or long :attention: this function performs the plain, primitive RSA encryption (*textbook*). In real applications, you always need to use proper cryptographic padding, and you should not directly encrypt data with this method. Failure to do so may lead to security vulnerabilities. It is recommended to use modules `Crypto.Cipher.PKCS1_OAEP` or `Crypto.Cipher.PKCS1_v1_5` instead. :Return: A tuple with two items. The first item is the ciphertext of the same type as the plaintext (string or long). The second item is always None. (R tencrypt(Rt plaintexttK((s/..\python\site-packages\Crypto\PublicKey\RSA.pyR)€scCstjj||ƒS(sËDecrypt a piece of data with RSA. Decryption always takes place with blinding. :attention: this function performs the plain, primitive RSA decryption (*textbook*). In real applications, you always need to use proper cryptographic padding, and you should not directly decrypt data with this method. Failure to do so may lead to security vulnerabilities. It is recommended to use modules `Crypto.Cipher.PKCS1_OAEP` or `Crypto.Cipher.PKCS1_v1_5` instead. :Parameter ciphertext: The piece of data to decrypt with RSA. It may not be numerically larger than the RSA module (**n**). If a tuple, the first item is the actual ciphertext; the second item is ignored. :Type ciphertext: byte string, long or a 2-item tuple as returned by `encrypt` :Return: A byte string if ciphertext was a byte string or a tuple of byte strings. A long otherwise. (R tdecrypt(Rt ciphertext((s/..\python\site-packages\Crypto\PublicKey\RSA.pyR,˜scCstjj|||ƒS(s¹Sign a piece of data with RSA. Signing always takes place with blinding. :attention: this function performs the plain, primitive RSA decryption (*textbook*). In real applications, you always need to use proper cryptographic padding, and you should not directly sign data with this method. Failure to do so may lead to security vulnerabilities. It is recommended to use modules `Crypto.Signature.PKCS1_PSS` or `Crypto.Signature.PKCS1_v1_5` instead. :Parameter M: The piece of data to sign with RSA. It may not be numerically larger than the RSA module (**n**). :Type M: byte string or long :Parameter K: A random parameter (*for compatibility only. This value will be ignored*) :Type K: byte string or long :Return: A 2-item tuple. The first item is the actual signature (a long). The second item is always None. (R tsign(RtMR+((s/..\python\site-packages\Crypto\PublicKey\RSA.pyR.°scCstjj|||ƒS(sVerify the validity of an RSA signature. :attention: this function performs the plain, primitive RSA encryption (*textbook*). In real applications, you always need to use proper cryptographic padding, and you should not directly verify data with this method. Failure to do so may lead to security vulnerabilities. It is recommended to use modules `Crypto.Signature.PKCS1_PSS` or `Crypto.Signature.PKCS1_v1_5` instead. :Parameter M: The expected message. :Type M: byte string or long :Parameter signature: The RSA signature to verify. The first item of the tuple is the actual signature (a long not larger than the modulus **n**), whereas the second item is always ignored. :Type signature: A 2-item tuple as return by `sign` :Return: True if the signature is correct, False otherwise. (R tverify(RR/t signature((s/..\python\site-packages\Crypto\PublicKey\RSA.pyR0ÉscCs|jj|ƒfS(N(Rt_encrypt(RtcR+((s/..\python\site-packages\Crypto\PublicKey\RSA.pyR2ßscCsi|d \}td|jjdd|jƒ}|jj||ƒ}|jj|ƒ}|jj||ƒS(NiR (RRRRt_blindt_decryptt_unblind(RR3R-trtcptmp((s/..\python\site-packages\Crypto\PublicKey\RSA.pyR5âs  "cCs|jj||ƒS(N(RR4(RtmR7((s/..\python\site-packages\Crypto\PublicKey\RSA.pyR4óscCs|jj||ƒS(N(RR6(RR:R7((s/..\python\site-packages\Crypto\PublicKey\RSA.pyR6öscCs|jj|ƒfS(N(Rt_sign(RR:R+((s/..\python\site-packages\Crypto\PublicKey\RSA.pyR;ùscCs |d \}|jj||ƒS(Ni(Rt_verify(RR:tsigts((s/..\python\site-packages\Crypto\PublicKey\RSA.pyR<üs cCs |jjƒS(N(Rt has_private(R((s/..\python\site-packages\Crypto\PublicKey\RSA.pyR?scCs |jjƒS(N(Rtsize(R((s/..\python\site-packages\Crypto\PublicKey\RSA.pyR@scCstS(N(tTrue(R((s/..\python\site-packages\Crypto\PublicKey\RSA.pyt can_blind scCstS(N(RA(R((s/..\python\site-packages\Crypto\PublicKey\RSA.pyt can_encrypt scCstS(N(RA(R((s/..\python\site-packages\Crypto\PublicKey\RSA.pytcan_signscCs"|jj|jj|jjfƒS(N(RRRRR(R((s/..\python\site-packages\Crypto\PublicKey\RSA.pyt publickeyscCsLi}x?|jD]4}yt|j|ƒ||t,( R"RJR@RHRR?R%R&tidtjoin(RtattrsRF((s/..\python\site-packages\Crypto\PublicKey\RSA.pyt__repr__(s ! tPEMic Cs-|dk rt|ƒ}n|dkrït|jƒ}t|jƒ}t|dƒd@rltdƒ|}nt|dƒd@r“tdƒ|}nd||g}djg|D]"}tj dt |ƒƒ|^q¯ƒ}dt j |ƒd St ƒ} |jƒrÎid d 6d d 6|} d|j|j|j|j|j|j|jd |j|jd t|j|jƒg | (|d kr1| jƒ} t dgƒ} | jtƒ| jtd | ƒjƒƒq1ncd} | jtƒtdƒ} t |j|jgƒ} tdƒ| jƒ| _| j| jƒƒ|dkrG| jƒS|dkrtd| dƒ}d}|r_| jd ƒr_ddl}ddlm}ddlm}|jd ƒ}|||dd |j j!ƒ}|||||d d |j j!ƒ7}|j"||j#jj$|ƒ}|tdƒ7}|tdƒt j%|ƒj&ƒtdƒ7}n| jƒ}|r«|j't |ƒ|j'}|j(|t|ƒ|ƒ}ngt)dt |ƒdƒD] }t j |||d!ƒ^qÄ}|tdƒj|ƒ7}|td| dƒ7}|St*d|ƒS(s$Export this RSA key. :Parameter format: The format to use for wrapping the key. - *'DER'*. Binary encoding, always unencrypted. - *'PEM'*. Textual encoding, done according to `RFC1421`_/`RFC1423`_. Unencrypted (default) or encrypted. - *'OpenSSH'*. Textual encoding, done according to OpenSSH specification. Only suitable for public keys (not private keys). :Type format: string :Parameter passphrase: In case of PEM, the pass phrase to derive the encryption key from. :Type passphrase: string :Parameter pkcs: The PKCS standard to follow for assembling the key. You have two choices: - with **1**, the public key is embedded into an X.509 `SubjectPublicKeyInfo` DER SEQUENCE. The private key is embedded into a `PKCS#1`_ `RSAPrivateKey` DER SEQUENCE. This mode is the default. - with **8**, the private key is embedded into a `PKCS#8`_ `PrivateKeyInfo` DER SEQUENCE. This mode is not available for public keys. PKCS standards are not relevant for the *OpenSSH* format. :Type pkcs: integer :Return: A byte string with the encoded public or private half. :Raise ValueError: When the format is unknown. .. _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 tOpenSSHii€sssh-rsats>Isssh-rsa iÿÿÿÿs RSA PRIVATEitPRIVATEis OCTET STRINGtPUBLICs BIT STRINGtDERRVs -----BEGIN s KEY----- N(tDES3(tPBKDF1isProc-Type: 4,ENCRYPTED sDEK-Info: DES-EDE3-CBC,s i0s -----END s KEY-----s3Unknown key format '%s'. Cannot export the RSA key.(+RttobytesR RRtbordtbchrRStstructtpacktlentbinasciit b2a_base64RR?RRRRtencodeRJtalgorithmIdentifierRtpayloadtbtendswithtCrypto.Hash.MD5t Crypto.CipherR\tCrypto.Protocol.KDFR]RtHashtMD5RtCiphertMODE_CBCtb2a_hextuppert block_sizeR)tranget ValueError(Rtformatt passphrasetpkcstebtnbtkeypartstkpt keystringtdertkeyTypetderkeytbitmaptderPKtpemtobjenctCryptoR\R]tsaltRt binaryKeytpaddingtitchunks((s/..\python\site-packages\Crypto\PublicKey\RSA.pyt exportKey4sj$  8  !"   "      &0  ?N(R&t __module__t__doc__R"RR!R(R)R,R.R0R2R5R4R6R;R<R?R@RBRCRDRERGRORURŒ(((s/..\python\site-packages\Crypto\PublicKey\RSA.pyR]s0                   cBsPeZdZd„Zd„Zdddd„Zd„Zd„Zdd„Z RS( sÒ An RSA key factory. This class is only internally used to implement the methods of the `Crypto.PublicKey.RSA` module. :sort: __init__,generate,construct,importKey :undocumented: _g*, _i* cKs©|jddƒ}|dkrBtdk r6t|_qxt|_n6|rotdk r`t|_qxtdƒ‚n t|_|jj|_|jddƒ|_d|_dS(sØCreate a new RSA key factory. :Keywords: use_fast_math : bool Specify which mathematic library to use: - *None* (default). Use fastest math available. - *True* . Use fast math. - *False* . Use slow math. default_randfunc : callable Specify how to collect random data: - *None* (default). Use Random.new().read(). - not *None* . Use the specified function directly. :Raise RuntimeError: When **use_fast_math** =True but fast math is not available. t use_fast_mathsfast math module not availabletdefault_randfuncN( tgetRRRKR t RuntimeErrorRt_default_randfunct_current_randfunc(RtkwargsR((s/..\python\site-packages\Crypto\PublicKey\RSA.pyR!Ÿs       cCs;|dk r|S|jdkr4tjƒj|_n|jS(N(RR”R RR(RR ((s/..\python\site-packages\Crypto\PublicKey\RSA.pyt _get_randfuncÆs  ic Cs½|dks|d@dkr+tdƒ‚n|ddksG|dkrVtdƒ‚n|j|ƒ}tj||||ƒ}|jj|j|j|j|j |j |j ƒ}t ||ƒS(s”Randomly generate a fresh, new RSA key. :Parameters: bits : int Key length, or size (in bits) of the RSA modulus. It must be a multiple of 256, and no smaller than 1024. randfunc : callable Random number generation function; it should accept a single integer N and return a string of random data N bytes long. If not specified, a new one will be instantiated from ``Crypto.Random``. progress_func : callable Optional function that will be called with a short string containing the key parameter currently being generated; it's useful for interactive applications where a user is waiting for a key to be generated. e : int 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 default value 65537 (= ``0b10000000000000001`` ) is a safe choice: other common values are 5, 7, 17, and 257. :attention: You should always use a cryptographically secure random number generator, such as the one defined in the ``Crypto.Random`` module; **don't** just use the current time and the ``random`` module. :attention: Exponent 3 is also widely used, but it requires very special care when padding the message. :Return: An RSA key object (`_RSAobj`). :Raise ValueError: When **bits** is too little or not a multiple of 256, or when **e** is not odd or smaller than 2. iiÿis8RSA modulus length must be a multiple of 256 and >= 1024iisBRSA public exponent must be a positive, odd integer larger than 2.( RvR–R t generate_pyRKRLRRRRRRR(RtbitsR t progress_funcRtrftobjR((s/..\python\site-packages\Crypto\PublicKey\RSA.pyRÍs)3cCs|jj|Œ}t||ƒS(s¸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: - e != 1 - p*q = n - e*d = 1 mod (p-1)(q-1) - p*u = 1 mod q :Parameters: tup : tuple A tuple of long 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. 5. Second factor of n (q). Optional. 6. CRT coefficient, (1/p) mod q (u). Optional. :Return: An RSA key object (`_RSAobj`). (RKRLR(RttupR((s/..\python\site-packages\Crypto\PublicKey\RSA.pyRscCsÚy´tƒ}|j|tƒt|ƒdkr„|jƒr„|ddkr„|d3|jt|d|dƒƒ|d=|j|ƒSt|ƒdkrQ|jƒr°|j|ƒS|dtkrQt ƒ}|j|dtƒ|j dƒrNt |j dƒdkrN|j|j dtƒt|ƒdkrK|jƒrK|j|ƒSqNqQn|ddkr³|dtkr³t ƒ}|j|dtƒ|j d ƒr°|j |j ƒSq³nWntk rÉ}nXtd ƒ‚d S( s@Import an RSA key (public or private half), encoded in DER form.i iiiiiis BIT STRINGs OCTET STRINGsRSA key format is not supportedN(RtdecodeRARct hasOnlyIntsRJRRRgRtisTypeR_Rht _importKeyDERRv(Rt externKeyRR‚t privateKeyt IndexError((s/..\python\site-packages\Crypto\PublicKey\RSA.pyR s6 .  ( c Csxt|ƒ}|d k r't|ƒ}n|jtdƒƒr||jtdƒtdƒƒjƒ}d }|djtdƒƒr|djtdƒƒ}t|ƒdksÇ|dtd ƒksÇ| rÖtd ƒ‚n|djtd ƒƒ\}}tj |ƒ}d d l }d dl m } m } d dlm} |tdƒkr‡| ||dd|jjƒ} | j| |jj j|ƒ}nƒ|tdƒkrþ| ||dd|jjƒ} | | | ||dd|jjƒ7} | j| |jj j|ƒ}n tdƒ‚|d}ntjtdƒj|dd !ƒƒ} |ro|j| ƒ} t| d ƒ}| | } n|j| ƒS|jtdƒƒrEtj|jtdƒƒdƒ}g}xVt|ƒdkrtjd|d ƒd}|j|dd|!ƒ|d|}q¼Wt|dƒ}t|dƒ}|j||gƒSt|dƒdkrh|j|ƒStdƒ‚d S(seImport an RSA key (public or private half), encoded in standard form. :Parameter externKey: The RSA key to import, encoded as a string. An RSA public key can be in any of the following formats: - X.509 `subjectPublicKeyInfo` DER SEQUENCE (binary or PEM encoding) - `PKCS#1`_ `RSAPublicKey` DER SEQUENCE (binary or PEM encoding) - OpenSSH (textual public key only) An RSA private key can be in any of the following formats: - PKCS#1 `RSAPrivateKey` DER SEQUENCE (binary or PEM encoding) - `PKCS#8`_ `PrivateKeyInfo` DER SEQUENCE (binary or PEM encoding) - OpenSSH (textual public key only) For details about the PEM encoding, see `RFC1421`_/`RFC1423`_. In case of PEM encoding, the private key can be encrypted with DES or 3TDES according to a certain ``pass phrase``. Only OpenSSL-compatible pass phrases are supported. :Type externKey: string :Parameter passphrase: In case of an encrypted PEM key, this is the pass phrase from which the encryption key is derived. :Type passphrase: string :Return: An RSA key object (`_RSAobj`). :Raise 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 s-----t RXisProc-Type:4,ENCRYPTEDit:isDEK-Infos$PEM encryption format not supported.RQiÿÿÿÿN(tDESR\(R]sDES-CBCis DES-EDE3-CBCis#Unsupport PEM encryption algorithm.sssh-rsa is>Ii0sRSA key format is not supported(R^Rt startswithRitreplacetsplitRcRvRdta2b_hexRkRlR¦R\RmR]RnRoRRpRqt a2b_base64RSR,R_R RatunpackRJRR(RR¡RxtlinestkeyobjtDEKtalgoR‡R†R¦R\R]RRR‰R~R|tlRR((s/..\python\site-packages\Crypto\PublicKey\RSA.pyRNsV&  $/ !&!  % " N( R&RRŽR!R–RRRR R(((s/..\python\site-packages\Crypto\PublicKey\RSA.pyR•s ' 3  0s  *†H†÷ (&RŽt __revision__t__all__tsyst version_infotCrypto.Util.py21compattCrypto.Util.py3compattCrypto.Util.numberRRR tCrypto.PublicKeyR R R R†R tCrypto.Util.asn1RRRRdRaRRt ImportErrorRRtobjectRRiRfRgt_implRRRR(((s/..\python\site-packages\Crypto\PublicKey\RSA.pyt@s< &      ÿ9ÿ