Current File : //usr/lib64/python2.7/site-packages/Crypto/PublicKey/RSA.pyo
�
Bd\Rc@s�dZdZddddddgZdd	lZejd
dkoSejddkrcdd
lTndd
lTddlmZm	Z	m
Z
ddlmZm
Z
mZddlmZddlmZmZmZdd	lZdd	lZddlmZddlmZyddlmZWnek
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	DerObjecttDerSequencetDerNull(tinverse(t	_fastmathcBs�eZdZddddddgZdd�Zd�Zd	�Zd
�Zd�Z	d�Z
d
�Zd�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:/usr/lib64/python2.7/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:/usr/lib64/python2.7/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:/usr/lib64/python2.7/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:/usr/lib64/python2.7/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:/usr/lib64/python2.7/site-packages/Crypto/PublicKey/RSA.pyR.�scCstjj|||�S(s�Verify 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:/usr/lib64/python2.7/site-packages/Crypto/PublicKey/RSA.pyR0�scCs|jj|�fS(N(Rt_encrypt(RtcR+((s:/usr/lib64/python2.7/site-packages/Crypto/PublicKey/RSA.pyR2�scCsi|d \}td|jjdd|j�}|jj||�}|jj|�}|jj||�S(NiR (RRRRt_blindt_decryptt_unblind(RR3R-trtcptmp((s:/usr/lib64/python2.7/site-packages/Crypto/PublicKey/RSA.pyR5�s

"cCs|jj||�S(N(RR4(RtmR7((s:/usr/lib64/python2.7/site-packages/Crypto/PublicKey/RSA.pyR4�scCs|jj||�S(N(RR6(RR:R7((s:/usr/lib64/python2.7/site-packages/Crypto/PublicKey/RSA.pyR6�scCs|jj|�fS(N(Rt_sign(RR:R+((s:/usr/lib64/python2.7/site-packages/Crypto/PublicKey/RSA.pyR;�scCs |d \}|jj||�S(Ni(Rt_verify(RR:tsigts((s:/usr/lib64/python2.7/site-packages/Crypto/PublicKey/RSA.pyR<�s
cCs
|jj�S(N(Rthas_private(R((s:/usr/lib64/python2.7/site-packages/Crypto/PublicKey/RSA.pyR?scCs
|jj�S(N(Rtsize(R((s:/usr/lib64/python2.7/site-packages/Crypto/PublicKey/RSA.pyR@scCstS(N(tTrue(R((s:/usr/lib64/python2.7/site-packages/Crypto/PublicKey/RSA.pyt	can_blind	scCstS(N(RA(R((s:/usr/lib64/python2.7/site-packages/Crypto/PublicKey/RSA.pytcan_encryptscCstS(N(RA(R((s:/usr/lib64/python2.7/site-packages/Crypto/PublicKey/RSA.pytcan_signscCs"|jj|jj|jjf�S(N(RRRRR(R((s:/usr/lib64/python2.7/site-packages/Crypto/PublicKey/RSA.pyt	publickeyscCsLi}x?|jD]4}yt|j|�||<Wqtk
rCqXqW|S(N(R"R#RR$(RRtk((s:/usr/lib64/python2.7/site-packages/Crypto/PublicKey/RSA.pyt__getstate__s
cCs~t|d�st�|_ng}x5|jD]*}|j|�sGPn|j||�q.W|jjjt|��|_	dS(NR(
thasattrRRR"thas_keytappendt_matht
rsa_constructttupleR(RRttRF((s:/usr/lib64/python2.7/site-packages/Crypto/PublicKey/RSA.pyt__setstate__scCs�g}x`|jD]U}|dkrC|jd|j�df�qt|j|�r|j|�qqW|j�r�|jd�nd|jjt|�dj	|�fS(NRsn(%d)itprivates
<%s @0x%x %s>t,(
R"RJR@RHRR?R%R&tidtjoin(RtattrsRF((s:/usr/lib64/python2.7/site-packages/Crypto/PublicKey/RSA.pyt__repr__(s!tPEMicCs-|dk	rt|�}n|dkr�t|j�}t|j�}t|d�d@rltd�|}nt|d�d@r�td�|}nd||g}djg|D]"}tj	dt
|��|^q��}dtj|�d St
�}	|j�r�id	d
6dd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�tj%|�j&�td�7}n|	j�}|r�|j't
|�|j'}|j(|t|�|�}ngt)dt
|�d�D] }tj|||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����sRSA 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:/usr/lib64/python2.7/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:/usr/lib64/python2.7/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(	tgetRRRKRtRuntimeErrorRt_default_randfunct_current_randfunc(RtkwargsR�((s:/usr/lib64/python2.7/site-packages/Crypto/PublicKey/RSA.pyR!�s	cCs;|dk	r|S|jdkr4tj�j|_n|jS(N(RR�R
RR(RR ((s:/usr/lib64/python2.7/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
tgenerate_pyRKRLRRRRRRR(RtbitsR t
progress_funcRtrftobjR((s:/usr/lib64/python2.7/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:/usr/lib64/python2.7/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
��dS(s@Import an RSA key (public or private half), encoded in DER form.i	iiiiiis
BIT STRINGsOCTET STRINGsRSA key format is not supportedN(RtdecodeRARcthasOnlyIntsRJRRRgRtisTypeR_Rht
_importKeyDERRv(Rt	externKeyRR�t
privateKeyt
IndexError((s:/usr/lib64/python2.7/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dlm}	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:/usr/lib64/python2.7/site-packages/Crypto/PublicKey/RSA.pyRNsV&$/!&!
%
"
N(
R&R�R�R!R�RRRR�R(((s:/usr/lib64/python2.7/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
RRR�R
tCrypto.Util.asn1RRRRdRaRRtImportErrorRRtobjectRRiRfRgt_implRRRR(((s:/usr/lib64/python2.7/site-packages/Crypto/PublicKey/RSA.pyt<module>@s<&



�9�