python use rsa library to do public key decryption method tutorial

  • 2020-06-15 09:37:57
  • OfStack

preface

For the decryption of RSA, that is, mod N can be obtained by raising the number of ciphertext to the D power, that is, ciphertext can be multiplied by D itself, and then the result can be divided by N to obtain plaintext. The combination of D and N is the private key (private key).

The encryption and decryption of the algorithm is very simple, but the public key and private key generation algorithm is not arbitrary. Using RSA public key decryption, using openssl command is openssl ES18en-ES19en-ES20en cipher_ES22en-ES24en. pem-pubin-out clear_text, but its python actually did not find a blog to write, only hash's rsa unsigned.

USES rsa library here, and if there is no can go to the official website https: / / pypi python. org/pypi/rsa/download 3.1.4.

Specific installation method you can reference here: https: / / www ofstack. com article / 70331. htm

Think about the principle, and then to rsa library python code looked for, extracted from the verify code, and test the test, 1 cut OK.

The code is as follows:


#! /usr/bin/env python
# -*- coding: utf-8 -*-
import sys
#rsa
from rsa import PublicKey, common, transform, core
def f(cipher, PUBLIC_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 
fn = sys.stdin.readline()[:-1]
public_key = sys.stdin.readline()[:-1]
x = f(open(fn).read(), open(public_key).read())
print x

shell was used to verify as follows:


$ openssl genrsa -out pri2048.pem 2048
Generating RSA private key, 2048 bit long modulus
..+++
..............................................+++
e is 65537 (0x10001)
 $ openssl rsa -in pri2048.pem -out pub2048.pem -RSAPublicKey_out
writing 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.py
Just a test

OK, note that the public key pem must be separated from the private key with -RSAPublicKey_ES68en, so that the pem file has the following behavior on line 1 and the last 1, so that rsa.PublicKey.load_pkcs1 can be recognized.

conclusion


Related articles: