Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use Python to realize RSA encryption and decryption

2025-02-22 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces the relevant knowledge of "how to use Python to achieve RSA encryption and decryption". The editor shows you the operation process through an actual case. The operation method is simple, fast and practical. I hope this article "how to use Python to achieve RSA encryption and decryption" can help you solve the problem.

The basic procedure of RSA encryption experiment:

First, select two large primes p and Q, and calculate n and phi_n

Second, select the commonly used e = 0x10001 to facilitate the optimization of power operation to the left and speed up the operation.

Third, calculate d, using the extended Euclid algorithm

Enter the plaintext a to convert the plaintext into a digital form that can be used for calculation

Fifth, use fast power module for a to get ciphertext b, which is displayed in hexadecimal

RSA decryption process:

6. use the fast power module for b to get the plaintext a, which is displayed in character form.

First, install the module pip install pycryptodome II. Generate key pairs.

Key pair file generation and reading

Code:

From Crypto.PublicKey import RSAdef create_rsa_pair (is_save=False):''create rsa public key private key pair: param is_save: default:False: return: public_key Private_key''f = RSA.generate (2048) private_key = f.exportKey ("PEM") # generate private key public_key = f.publickey () .exportKey () # generate public key if is_save: with open ("crypto_private_key.pem", "wb") as f: f.write (private_key) with open ("crypto_public_key.pem") "wb") as f: f.write (public_key) return public_key, private_keydef read_public_key (file_path= "crypto_public_key.pem")-> bytes: with open (file_path, "rb") as x: B = x.read () return bdef read_private_key (file_path= "crypto_private_key.pem")-> bytes: with open (file_path "rb") as x: B = x.read () return b III. Encryption

Process: input text (str) → string encoding (default utf-8) (bytes) → rsa encryption (bytes) → base64 encoding (bytes) → decoding to string (str)

Code:

Import base64from Crypto.Cipher import PKCS1_v1_5from Crypto.PublicKey import RSAdef encryption (text: str Public_key: bytes): # string specified encoding (converted to bytes) text = text.encode ('utf-8') # build public key object cipher_public = PKCS1_v1_5.new (RSA.importKey (public_key)) # encryption (bytes) text_encrypted = cipher_public.encrypt (text) # base64 encoding And convert it to the string text_encrypted_base64 = base64.b64encode (text_encrypted). Decode () return text_encrypted_base64 if _ _ name__ = ='_ _ main__': public_key = read_public_key () text = '123456' text_encrypted_base64 = encryption (text, public_key) print (' ciphertext:', text_encrypted_base64) 4. Decryption

Note: the decryption process is opposite to the encryption process (decrypted in reverse order according to the encryption process)

Process: input text (str) → string Encoding (default utf-8) (bytes) → base64 Decoding (bytes) → rsa decryption (bytes) → Decoding to string (str)

Code:

Import base64from Crypto.Cipher import PKCS1_v1_5from Crypto import Randomfrom Crypto.PublicKey import RSAdef decryption (text_encrypted_base64: str Private_key: bytes): # string specified encoding (converted to bytes) text_encrypted_base64 = text_encrypted_base64.encode ('utf-8') # base64 decoding text_encrypted = base64.b64decode (text_encrypted_base64) # build private key object cipher_private = PKCS1_v1_5.new (RSA.importKey (private_key)) # decryption (bytes) text_decrypted = cipher_private.decrypt (text_encrypted Random.new () .read) # decoded into the string text_decrypted = text_decrypted.decode () return text_decrypted if _ _ name__ = ='_ _ main__': # generate ciphertext public_key = read_public_key () text = '123456' text_encrypted_base64 = encryption (text, public_key) print (' ciphertext:' Text_encrypted_base64) # decrypt private_key = read_private_key () text_decrypted = decryption (text_encrypted_base64, private_key) print ('plaintext:' Text_decrypted) 5. Complete code import base64from Crypto.Cipher import PKCS1_v1_5from Crypto import Randomfrom Crypto.PublicKey import RSA#-generate key pair-def create_rsa_pair (is_save=False):''create rsa public key private key pair: param is_save: default:False: return: public_key Private_key''f = RSA.generate (2048) private_key = f.exportKey ("PEM") # generate private key public_key = f.publickey () .exportKey () # generate public key if is_save: with open ("crypto_private_key.pem", "wb") as f: f.write (private_key) with open ("crypto_public_key.pem") "wb") as f: f.write (public_key) return public_key, private_keydef read_public_key (file_path= "crypto_public_key.pem")-> bytes: with open (file_path, "rb") as x: B = x.read () return bdef read_private_key (file_path= "crypto_private_key.pem")-> bytes: with open (file_path "rb") as x: B = x.read () return b #-encryption-def encryption (text: str Public_key: bytes): # string specified encoding (converted to bytes) text = text.encode ('utf-8') # build public key object cipher_public = PKCS1_v1_5.new (RSA.importKey (public_key)) # encryption (bytes) text_encrypted = cipher_public.encrypt (text) # base64 encoding And convert it to the string text_encrypted_base64 = base64.b64encode (text_encrypted) .decode () return text_encrypted_base64#-decryption-def decryption (text_encrypted_base64: str Private_key: bytes): # string specified encoding (converted to bytes) text_encrypted_base64 = text_encrypted_base64.encode ('utf-8') # base64 decoding text_encrypted = base64.b64decode (text_encrypted_base64) # build private key object cipher_private = PKCS1_v1_5.new (RSA.importKey (private_key)) # decryption (bytes) text_decrypted = cipher_private.decrypt (text_encrypted Random.new () .read) # decoded into the string text_decrypted = text_decrypted.decode () return text_decryptedif _ _ name__ = ='_ _ main__': # generate key pair # create_rsa_pair (is_save=True) # public_key = read_public_key () # private_key = read_private_key () public_key Private_key = create_rsa_pair (is_save=False) # encryption text = '123456' text_encrypted_base64 = encryption (text, public_key) print ('ciphertext:', text_encrypted_base64) # decryption text_decrypted = decryption (text_encrypted_base64, private_key) print ('plaintext:', text_decrypted)

This is the end of the content about "how to use Python to achieve RSA encryption and decryption". Thank you for reading. If you want to know more about the industry, you can follow the industry information channel. The editor will update different knowledge points for you every day.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report