Rsa шифрование python реализация
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 more than 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 cryptographic strength is primarily linked to the length of the RSA modulus n. In 2017, a sufficient length is deemed to be 2048 bits. For more information, see the most recent ECRYPT report.
Both RSA ciphertexts and RSA signatures are as large as the RSA modulus n (256 bytes if n is 2048 bit long).
The module Crypto.PublicKey.RSA provides facilities for generating new RSA keys, reconstructing them from known components, exporting them, and importing them.
As an example, this is how you generate a new RSA key pair, save it in a file called mykey.pem , and then read it back:
>>> from Crypto.PublicKey import RSA >>> >>> key = RSA.generate(2048) >>> f = open('mykey.pem','wb') >>> f.write(key.export_key('PEM')) >>> f.close() . >>> f = open('mykey.pem','r') >>> key = RSA.import_key(f.read())
Create 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.
- 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 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 ( RsaKey , with private key).
Crypto.PublicKey.RSA. construct ( rsa_components, consistency_check=True ) ¶
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:
- rsa_components (tuple) – A tuple of integers, with at least 2 and no more than 6 items. The items come in the following order:
- RSA modulus n.
- Public exponent e.
- Private exponent d. Only required if the key is private.
- First factor of n (p). Optional, but the other factor q must also be present.
- Second factor of n (q). Optional.
- CRT coefficient q, that is \(p^ \textq\) . Optional.
- consistency_check (boolean) – If True , the library will verify that the provided components fulfil the main RSA properties.
ValueError – when the key being imported fails the most basic RSA validity checks.
Returns: An RSA key object ( RsaKey ).
Crypto.PublicKey.RSA. import_key ( extern_key, passphrase=None ) ¶
Import an RSA key (public or private).
- extern_key (stringorbyte 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.
Returns: An RSA key object ( RsaKey ).
Raises: ValueError/IndexError/TypeError – When the given key cannot be parsed (possibly because the pass phrase is wrong). class Crypto.PublicKey.RSA. RsaKey ( **kwargs ) ¶
Class defining an actual RSA key. Do not instantiate directly. Use generate() , construct() or import_key() instead.
- 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).
Note This parameter is ignored for a public key. For DER and PEM, an ASN.1 DER SubjectPublicKeyInfo structure is always used.
- A 16 byte Triple DES key is derived from the passphrase using Crypto.Protocol.KDF.PBKDF2() with 8 bytes salt, and 1 000 iterations of Crypto.Hash.HMAC .
- The private key is encrypted using CBC.
- The encrypted key is encoded according to PKCS#8.
Specifying a value for 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 Crypto.IO.PKCS8 module (see wrap_algo parameter).
ValueError – when the format is unknown or when you try to encrypt a private key with DER format and PKCS#1.
If you don’t provide a pass phrase, the private key will be exported in the clear!
- 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).
Note This parameter is ignored for a public key. For DER and PEM, an ASN.1 DER SubjectPublicKeyInfo structure is always used.
- A 16 byte Triple DES key is derived from the passphrase using Crypto.Protocol.KDF.PBKDF2() with 8 bytes salt, and 1 000 iterations of Crypto.Hash.HMAC .
- The private key is encrypted using CBC.
- The encrypted key is encoded according to PKCS#8.
Specifying a value for 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 Crypto.IO.PKCS8 module (see wrap_algo parameter).
ValueError – when the format is unknown or when you try to encrypt a private key with DER format and PKCS#1.
If you don’t provide a pass phrase, the private key will be exported in the clear!
Whether this is an RSA private key
A matching RSA public key.
Returns: a new RsaKey object publickey ( ) ¶
A matching RSA public key.
Returns: a new RsaKey object size_in_bits ( ) ¶
Size of the RSA modulus in bits
The minimal amount of bytes that can hold the RSA modulus
Crypto.PublicKey.RSA. oid = ‘1.2.840.113549.1.1.1’¶
Object ID for the RSA encryption algorithm. This OID often indicates a generic RSA key, even when such key will be actually used for digital signatures.
djego / rsa.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
»’ 620031587 Net-Centric Computing Assignment Part A — RSA Encryption »’ import random »’ Euclid’s algorithm for determining the greatest common divisor Use iteration to make it faster for larger integers »’ def gcd ( a , b ): while b != 0 : a , b = b , a % b return a »’ Euclid’s extended algorithm for finding the multiplicative inverse of two numbers »’ def multiplicative_inverse ( e , phi ): d = 0 x1 = 0 x2 = 1 y1 = 1 temp_phi = phi while e > 0 : temp1 = temp_phi / e temp2 = temp_phi — temp1 * e temp_phi = e e = temp2 x = x2 — temp1 * x1 y = d — temp1 * y1 x2 = x1 x1 = x d = y1 y1 = y if temp_phi == 1 : return d + phi »’ Tests to see if a number is prime. »’ def is_prime ( num ): if num == 2 : return True if num < 2 or num % 2 == 0 : return False for n in xrange ( 3 , int ( num ** 0.5 ) + 2 , 2 ): if num % n == 0 : return False return True def generate_keypair ( p , q ): if not ( is_prime ( p ) and is_prime ( q )): raise ValueError ( ‘Both numbers must be prime.’ ) elif p == q : raise ValueError ( ‘p and q cannot be equal’ ) #n = pq n = p * q #Phi is the totient of n phi = ( p — 1 ) * ( q — 1 ) #Choose an integer e such that e and phi(n) are coprime e = random . randrange ( 1 , phi ) #Use Euclid’s Algorithm to verify that e and phi(n) are comprime g = gcd ( e , phi ) while g != 1 : e = random . randrange ( 1 , phi ) g = gcd ( e , phi ) #Use Extended Euclid’s Algorithm to generate the private key d = multiplicative_inverse ( e , phi ) #Return public and private keypair #Public key is (e, n) and private key is (d, n) return (( e , n ), ( d , n )) def encrypt ( pk , plaintext ): #Unpack the key into it’s components key , n = pk #Convert each letter in the plaintext to numbers based on the character using a^b mod m cipher = [( ord ( char ) ** key ) % n for char in plaintext ] #Return the array of bytes return cipher def decrypt ( pk , ciphertext ): #Unpack the key into its components key , n = pk #Generate the plaintext based on the ciphertext and key using a^b mod m plain = [ chr (( char ** key ) % n ) for char in ciphertext ] #Return the array of bytes as a string return » . join ( plain ) if __name__ == ‘__main__’ : »’ Detect if the script is being run directly by the user »’ print «RSA Encrypter/ Decrypter» p = int ( raw_input ( «Enter a prime number (17, 19, 23, etc): » )) q = int ( raw_input ( «Enter another prime number (Not one you entered above): » )) print «Generating your public/private keypairs now . . .» public , private = generate_keypair ( p , q ) print «Your public key is » , public , » and your private key is » , private message = raw_input ( «Enter a message to encrypt with your private key: » ) encrypted_msg = encrypt ( private , message ) print «Your encrypted message is: « print » . join ( map ( lambda x : str ( x ), encrypted_msg )) print «Decrypting message with public key » , public , » . . .» print «Your message is:» print decrypt ( public , encrypted_msg )