RSA is a public-key cryptography algorithm, RSA cipher is the code of the text of the number of the E-time to find the result of MoD N. The following article mainly introduces you to the Python use of RSA Library to do public key decryption method tutorial, the text through the sample code introduced in very detailed, the need for friends can refer to, hope to help everyone.
Objective
For the decryption of RSA, that is, the number of cipher D to find the MoD N, that is, ciphertext and do the D multiplication, and then divide the result by N to find the remainder can be clear. The combination of D and N is the private key.
Algorithm encryption and decryption is still very simple, but the public key and private key generation algorithm is not arbitrary. Using the RSA public key decryption, with the OpenSSL command is the OpenSSL rsautl-verify-in cipher_text-inkey public.pem-pubin-out Clear_text, But its python online really did not find a blog to write, only the hash of the RSA signature.
Here use the RSA Library, if not available to the official website https://pypi.python.org/pypi/rsa/3.1.4 download.
Specific installation methods you can refer here: http://www.jb51.net/article/70331.htm
Think about the principle, and then to the RSA Library Python code to find, from the verify code extracted out, and tested the experiment, everything OK.
The code is as follows:
#! /usr/bin/env python#-*-coding:utf-8-*-import sys#rsafrom RSA Import PublicKey, Common, transform, coredef f (cipher, PU Blic_key): Public_key = PUBLICKEY.LOAD_PKCS1 (public_key) encrypted = Transform.bytes2int (cipher) decrypted = Core.decrypt_int (Encrypted, PUBLIC_KEY.E, PUBLIC_KEY.N) Text = transform.int2bytes (decrypted) if Len (text) > 0 and text[0] = = ' \x01 ': pos = text.find (' \x00 ') if pos > 0: return text[pos+1:] else: return None F n = Sys.stdin.readline () [: -1]public_key = Sys.stdin.readline () [: -1]x = f (Open (FN). Read (), open (Public_key). Read ()) Print X
Verify with Shell as follows:
$ OpenSSL genrsa-out Pri2048.pem 2048Generating RSA private key, 2048 bit long modulus. +++..............................................+++e is 65537 (0x10001) $ OpenSSL rsa-in pri2048.pem-out Pub2048.pem- Rsapublickey_outwriting RSA key $ Echo-n ' Just a test ' >1.txt $ openssl rsautl-sign-in 1.txt-inkey pri2048.pem-out 1.bin $ {echo 1.bin; echo Pub2048.pem;} |./test_rsa.pyjust a Test
Everything OK, note that the public key PEM precipitates from the private key must be used-rsapublickey_out, so that the first line of the Pem file and the last behavior below, so RSA. PUBLICKEY.LOAD_PKCS1 will know.