SoFunction
Updated on 2025-04-13

The use of RSA encryption and decryption and digital signature technology in Python

Detailed explanation of RSA encryption and decryption and digital signature technology

  • In Internet communication, the security of data is crucial.
  • In order to prevent data from being tampered with or forged during transmission, digital signature technology came into being.
  • RSA is a widely used asymmetric encryption algorithm that can be used not only for data encryption and decryption, but also for digital signatures and authentication.

1. Overview of RSA digital signatures

1. What is digital signature?

  • Digital signature is a technology used to verify data integrity and source.
  • It is similar to real-life signatures, but has higher security and non-repudiation.
  • With digital signatures, the receiver can confirm that the data has not been tampered with during transmission and that it does come from the claimed sender.

2. The principle of RSA digital signature

RSA digital signatures are based on asymmetric encryption algorithms, using a pair of keys: public and private keys.

  • Private key: Used to sign data, only those who own the private key can generate a valid signature.
  • Public Key: Used to verify the signature, anyone can use the public key to verify the validity of the signature.

Signing process:

  1. The sender uses the private key to encrypt the hash value of the data and generates a signature.
  2. The sender sends the data and signature to the receiver.

Verification process:

  1. The receiver decrypts the signature using the public key to obtain the hash value of the data.
  2. The receiver recalculates the hash value of the data and compares it with the decrypted hash value.
  3. If the two hashes are the same, the signature is valid and the data has not been tampered with.

2. Install the rsa library

  • In Python, we can usersaLibrary to implement RSA encryption and decryption and digital signature.
  • First, you need to install the library:
pip install rsa

3. Generate RSA public and private keys

  • Before using RSA digital signatures, a pair of public and private keys need to be generated.
  • Here is the example code for generating public and private keys:
import rsa
from pathlib import Path

# Define storage pathBASE_DIR = Path(__file__).parent

# Generate public and private key objectspublic_key, private_key = (2048)

# Get the stream data corresponding to the public keybpub_key = public_key.save_pkcs1()

# Get the stream data corresponding to the private keybpri_key = private_key.save_pkcs1()

#Save the public key in a filewith open(BASE_DIR / 'rsa/', "wb") as f:
    (bpub_key)

#Save the private key in a filewith open(BASE_DIR / 'rsa/', "wb") as f:
    (bpri_key)

Code description

Generate a key pair

  • (2048): Generate 2048-bit public and private keys.

Save the key

  • save_pkcs1(): Converts the key object to a byte stream in PKCS#1 format.
  • Save the public and private keys toandin the file.

4. Use RSA private key to digitally sign

  • After generating a key pair, the data can be signed using the private key.
  • Here is the example code for the signature:
import rsa
from pathlib import Path

# Define storage pathBASE_DIR = Path(__file__).parent

# Load the private keywith open(BASE_DIR / 'rsa/', 'rb') as f:
    private_key = .load_pkcs1(())

# Define the string to signmessage = "pwd=123&pk=1"

# Sign and get signed streaming datasign_bytes = ((), private_key, "SHA-1")

# Get the signature string representationsign_text = sign_bytes.hex()

print(f"sign: {sign_text}")

Code description

Load the private key

  • .load_pkcs1(): Load the private key from the file.

Signature data

  • (): Sign data using a private key.
  • The signature algorithm isSHA-1, you can choose other hashing algorithms as needed.

Get the signature string

  • sign_bytes.hex(): Convert the signature bypass to a hexadecimal string representation.

5. Use RSA public key for digital authentication

  • After receiving the data and signature, the receiver can use the public key to verify the validity of the signature.
  • Here is the sample code for authentication:
import rsa
from pathlib import Path

# Define storage pathBASE_DIR = Path(__file__).parent

# Load the public keywith open(BASE_DIR / 'rsa/', 'rb') as f:
    public_key = .load_pkcs1(())

# Define the string to be authenticatedmessage = "pwd=123&pk=1"

# Get the digital signature (result returned in the previous step)sign_text = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"  # Replace with the actual signature
# Authentication with a public keytry:
    hasher = ((), (sign_text), public_key)
    
    if hasher == "SHA-1":
        print("Certification is successful")
except :
    print("Certification failed")

Code description

Loading the public key

  • .load_pkcs1(): Load the public key from the file.

Verify signature

  • (): Use public key to verify the validity of the signature.
  • If the signature is valid, return the hashing algorithm used (e.g.SHA-1)。
  • If the signature is invalid, throwabnormal.

6. Application scenarios of digital signatures

Digital signatures play an important role in the following scenarios:

  1. Data Integrity Verification: Ensure that the data has not been tampered with during transmission.
  2. Identity Authentication: Verify the source of the data to prevent forgery.
  3. Undeniable: The sender cannot deny the data it sends.

7. Things to note

Key Management

  • The private key must be kept properly to avoid leakage.
  • Public keys can be distributed publicly.

Hash algorithm selection

  • Used in the exampleSHA-1Algorithm, but in practical applications, it is recommended to use a safer hashing algorithm, such asSHA-256

Exception handling

  • When verifying the signature, it should be capturedException to handle authentication failure.

Summarize

This article introduces the principles, implementation steps of RSA digital signature, and how to use PythonrsaThe library completes public key private key generation, digital signature and authentication.

RSA digital signature is a powerful security tool that can effectively protect the integrity of data and the authenticity of its source.

In practical applications, we should select the appropriate key length and hashing algorithm based on specific needs, and properly manage the keys to ensure the security of the system.

The above is personal experience. I hope you can give you a reference and I hope you can support me more.