杰瑞科技汇

Python如何用rsa模块实现加密解密?

Of course! The rsa library in Python is a fantastic tool for performing public-key cryptography. It allows you to generate public and private keys, and then use them to encrypt, decrypt, sign, and verify data.

Python如何用rsa模块实现加密解密?-图1
(图片来源网络,侵删)

Here's a comprehensive guide covering everything from installation to practical examples.

Installation

First, you need to install the library. It's available on PyPI.

pip install rsa

Core Concepts: Public and Private Keys

Public-key cryptography uses a pair of keys:

  • Private Key: This is your secret key. You must never share it with anyone. It is used for decrypting messages that were encrypted with your public key and for signing data to prove it came from you.
  • Public Key: This key can be shared with anyone. It is used for encrypting messages that only you can read with your private key and for verifying that a signature was created with your private key.

Generating Keys

The most common use case is to generate a new key pair. You can specify the key size in bits. A key size of 2048 bits is a good standard for security today, while 4096 bits is even stronger.

Python如何用rsa模块实现加密解密?-图2
(图片来源网络,侵删)
import rsa
# Generate a new 2048-bit key pair
(public_key, private_key) = rsa.newkeys(2048)
# You can print them to see their format
print("Public Key:")
print(public_key.save_pkcs1().decode('utf-8'))
print("\nPrivate Key:")
print(private_key.save_pkcs1().decode('utf-8'))

Important: In a real application, you would save these keys to files to use them later, not generate them every time.

Encrypting and Decrypting

This is the classic use case for public-key cryptography. Alice wants to send a secret message to Bob.

  1. Bob generates a key pair and keeps his private key secret. He gives his public key to Alice.
  2. Alice uses Bob's public key to encrypt her message.
  3. Alice sends the encrypted message to Bob.
  4. Bob uses his private key to decrypt the message.

Example:

import rsa
# 1. Bob generates his key pair
bob_public_key, bob_private_key = rsa.newkeys(2048)
# 2. Alice has a secret message to send to Bob
message = "Hello Bob, this is a secret message from Alice."
# IMPORTANT: The rsa library can only encrypt bytes, not strings.
message_bytes = message.encode('utf-8')
# 3. Alice encrypts the message using Bob's PUBLIC key
# The 'pkcs1' padding scheme is standard.
encrypted_message = rsa.encrypt(message_bytes, bob_public_key)
print(f"Original message: {message}")
print(f"Encrypted message (bytes): {encrypted_message}")
# 4. Alice sends the encrypted_message to Bob.
# Bob receives it and decrypts it using his PRIVATE key.
try:
    decrypted_message_bytes = rsa.decrypt(encrypted_message, bob_private_key)
    # Convert the decrypted bytes back to a string
    decrypted_message = decrypted_message_bytes.decode('utf-8')
    print(f"Decrypted message: {decrypted_message}")
except ValueError:
    print("Decryption failed! The message might be corrupted or the wrong key was used.")

Signing and Verifying

Signing is used to prove that a message came from a specific person and that it hasn't been tampered with.

  1. Alice wants to sign a message to prove it's from her.
  2. Alice creates a digital signature of the message using her private key.
  3. Alice sends the original message and the signature to Bob.
  4. Bob uses Alice's public key to verify the signature.

Example:

import rsa
# 1. Alice generates her key pair
alice_public_key, alice_private_key = rsa.newkeys(2048)
# 2. Alice has a message she wants to sign
message = "This message is from Alice. Trust me."
message_bytes = message.encode('utf-8')
# 3. Alice creates a signature using her PRIVATE key
# The 'hash' algorithm must be specified (e.g., 'SHA-256')
signature = rsa.sign(message_bytes, alice_private_key, 'SHA-256')
print(f"Original message: {message}")
print(f"Signature: {signature}")
# 4. Alice sends the message and signature to Bob.
# Bob receives them and verifies the signature using Alice's PUBLIC key.
try:
    # The 'verify' function will raise an exception if the signature is invalid
    rsa.verify(message_bytes, signature, alice_public_key)
    print("Signature is valid! The message is authentic and has not been tampered with.")
except rsa.VerificationError:
    print("Signature is invalid! The message may have been tampered with or is not from Alice.")

Saving and Loading Keys from Files

It's impractical to generate keys every time. You should save them to files and load them when needed.

Python如何用rsa模块实现加密解密?-图3
(图片来源网络,侵删)

Saving Keys

import rsa
# Generate keys
public_key, private_key = rsa.newkeys(2048)
# Save public key to a file
with open('public_key.pem', 'wb') as p:
    p.write(public_key.save_pkcs1('PEM'))
# Save private key to a file
with open('private_key.pem', 'wb') as p:
    p.write(private_key.save_pkcs1('PEM'))
print("Keys have been saved to 'public_key.pem' and 'private_key.pem'")

Loading Keys

import rsa
# Load public key from file
with open('public_key.pem', 'rb') as p:
    public_key = rsa.PublicKey.load_pkcs1(p.read())
# Load private key from file
with open('private_key.pem', 'rb') as p:
    private_key = rsa.PrivateKey.load_pkcs1(p.read())
print("Keys have been loaded from files.")
print(f"Public key loaded: {public_key}")
print(f"Private key loaded: {private_key}")

Important Considerations

  • Performance: Public-key cryptography (like RSA) is computationally expensive and slow. It is not suitable for encrypting large amounts of data (e.g., multi-gigabyte files).
  • Hybrid Encryption: The standard solution is to use RSA for encrypting a small, random symmetric key (like an AES key). Then, you use that fast symmetric key to encrypt the large data itself. This is how protocols like TLS/SSL work.
  • Key Size: As computing power increases, smaller key sizes become insecure. 1024-bit keys are now considered insecure. 2048 bits is the recommended minimum, and 4096 bits is recommended for high-security applications.
  • Padding: The rsa library uses PKCS#1 padding by default. This is crucial for security. Do not attempt to implement your own padding schemes.
分享:
扫描分享到社交APP
上一篇
下一篇