The most popular on the whole network, Python interface automated testing – interface data RSA encryption and signature implementation (super detailed)

Table of Contents: Guide

    • foreword
    • 1. From entry to mastery of Python programming
    • 2. Interface automation project actual combat
    • 3. Actual Combat of Web Automation Project
    • 4. Actual Combat of App Automation Project
    • 5. Resume of first-tier manufacturers
    • 6. Test and develop DevOps system
    • 7. Commonly used automated testing tools
    • Eight, JMeter performance test
    • 9. Summary (little surprise at the end)

Foreword

At work, we always encounter request parameters that some interfaces use RSA encryption and signature to process, so when encountering this problem, of course, the first thing to do is to find a method for encryption and decryption, but for the development of encryption and decryption code, Most of the cases are implemented in languages such as java, c++, js, etc. Although there are encryption and decryption codes, as a test, we use python to automate, not all languages.

Python interface automated testing: https://www.bilibili.com/video/BV16G411x76E/

At this time, it will be more embarrassing. Looking at this bunch of encryption and decryption codes, I don’t know where to start, and then go to the development to write a python version. The development may not necessarily respond to you, and even if it does, the development may not necessarily Know python, so today we will talk about how to implement RSA encryption, decryption and signature through python

Introduction to RSA Algorithm

The RSA encryption algorithm is an asymmetric encryption algorithm. The encrypted secret key is composed of a public key and a private key. The public key is used to encrypt the message, and the private key is used to decrypt the message. The public key is public , the private key is reserved by the user. Since the public key is public, anyone who obtains the public key can use the public key to encrypt and send forged content.

For security reasons, we can use RSA to sign before sending the message, use the private key to sign the signature, and use the public key to verify the signature. By signing, we can ensure the uniqueness of the user’s identity, thereby improving security.

Difference between encryption and signature

Encryption:
For example, there are two people, A and B, and A wants to pass confidential information to B. In order to avoid information leakage, B generates a pair of secret keys through the RSA encryption algorithm in advance, and gives the public key to A in advance, and keeps the private key for himself. , When A sends a message to B, first use the public key given by B to encrypt the message, and then pass the message to B, B gets the encrypted message, and can decrypt the message with the private key. It doesn’t matter even if it is obtained by others, there is no way to decrypt the message without the private key.

But there is still a problem at this time. The public key is generally public and will be given to multiple people at the same time. If there is still a person C who obtains the public key at this time, he encrypts the message with the public key and wants to impersonate A. To send a message to B, after receiving the message, B can decrypt the message with the private key, but it is impossible to confirm whether the message was sent by A (it may be encrypted with a different public key), in order to distinguish The identity of the sender, then we will use the signature at this time.

Signature:
Although we can ensure that the sent message is not leaked through encryption, we cannot distinguish the identity of the sender. In order to distinguish his own identity, user A also generates a pair of secret keys, and gives the public key to B in advance. At this time, first use the public key given by B to encrypt the message, then use A’s own private key to generate a signature, and finally send the encrypted message and signature to B, after B receives the data sent by A, first use A user The public key to verify the signature information and confirm the identity information. If it is confirmed that it is user A, then use its own private key to decrypt the encrypted message.

After A’s message is encrypted and signed, it is sent to B. Even if it is intercepted, it doesn’t matter. Without B’s private key, the message cannot be decrypted. Signing cannot be done without the private key of A. Similarly, when B replies to A, it can encrypt it with B’s public key, and then use its own private key to generate a signature. A receives the data and uses the same method to decrypt and verify its identity. In this way, nothing will go wrong.

Python implements RSA encryption and decryption and signature addition and decryption

Use python to implement RSA encryption and signature, and the third-party library used is Crypto:

1. Generate a key pair
For the convenience of demonstration here, we first manually generate a key pair (the key pair in the project is generated by the development and will be given to us directly)

When generating a secret key pair, you can specify the length of the generated secret key. Generally, it is recommended to use 1024bit, 1024bit rsa public key. When encrypting data, you can only encrypt data up to 117bytes). If the amount of data exceeds this number, you need to encrypt the data. Segmented encryption, but the current key length of 1024bit has been proven not safe enough, try to use a key length of 2048bit. 2048bit long secret key, up to 245byte long data

Calculated as follows:
Secret key length/8-11 = maximum encryption amount (unit: byte)
Generate a pair of 1024bit secret keys below

from Crypto import Random
from Crypto.PublicKey import RSA

# Pseudorandom number generator
random_gen = Random.new().read

# Generate a key pair instance object: 1024 is the length of the key
rsa = RSA. generate(1024, random_gen)

# Get the public key and save it to a file
private_pem = rsa. exportKey()
with open('private. pem', 'wb') as f:
    f.write(private_pem)

# Get the private key and save it to a file
public_pem = rsa.publickey().exportKey()
with open('public.pem', 'wb') as f:
    f.write(public_pem)

Please add a picture description
Please add picture description

2. Encryption and decryption

Public key encryption:

import base64
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5


msg = "Plaintext content to be encrypted"

# read the public key in the file
key = open('public.pem').read()
publickey = RSA.importKey(key)
# encrypt
pk = PKCS1_v1_5.new(publickey)
encrypt_text = pk.encrypt(msg.encode())
# Encryption is encoded via base64
result = base64.b64encode(encrypt_text)
print(result)

Private key decryption:

import base64
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5
# ciphertext
msg='bAlnUNEJeDLnWikQs1ejwqPTo4qZ7RWxgFwoO4Bfg3C7EY + 1HN5UvJYJ2h6047K6vNjG + TiIxc0udTR7a12MivSA + DwoGjwFIb25u3zc + M8KTCaCT5GdSumDOto2tsKYaVDKCPZpdwYdzYwlVijr6cPcchQTlD1yfKk2khhNchU='

# base64 decoding
msg = base64.b64decode(msg)
# get private key
privatekey = open('private.pem').read()
rsakey = RSA.importKey(privatekey)
# to decrypt
cipher = PKCS1_v1_5.new(rsakey)
text = cipher.decrypt(msg, 'DecryptError')
# Decrypted is in bytecode format, and decodee is converted to a string
print(text. decode())

Segmented encryption and decryption:

When we generated the secret key above, we mentioned that when we encrypt, if the data length exceeds the maximum length that the current secret key can handle, segmental encryption is required.

Segmented encryption: To put it simply, it is to divide the original long series of data into multiple segments. The size of each segment is controlled within the maximum encryption number of the secret key. After the encryption is completed, the data is spliced.

Segmented decryption: After segmented encrypted data, we also need to divide it into multiple segments when decrypting, and then splicing after decryption to get the original data content.

The code for segmentation encryption and decryption is as follows:

import base64
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5


def cipher(msg):
    """
    public key encryption
    :param msg: To encrypt content
    :return: encrypted ciphertext
    """
    # Get the public key
key = open('public.pem').read()
publickey = RSA.importKey(key)
    # Sectional encryption
    pk = PKCS1_v1_5.new(publickey)
    encrypt_text = []
    for i in range(0,len(msg),100):
        cont = msg[i:i+100]
        encrypt_text.append(pk.encrypt(cont.encode()))
    # Encrypted and spliced
    cipher_text = b''.join(encrypt_text)
# base64 for encoding
 result = base64.b64encode(cipher_text)
    return result. decode()


def decrypt(msg):
    """
    private key to decrypt
    :param msg: ciphertext: string type
    :return: the decrypted content
    """
    # base64 decoding
    msg = base64.b64decode(msg)
    # get private key
    privatekey = open('private.pem').read()
    rsakey = RSA.importKey(privatekey)
    cipher = PKCS1_v1_5.new(rsakey)
    # to decrypt
    text = []
    for i in range(0,len(msg),128):
        cont = msg[i:i+128]
        text.append(cipher.decrypt(cont,1))
    text = b''.join(text)
    return text. decode()

Signature and verification

Private key signature:

from Crypto.Hash import SHA
from Crypto.Signature import PKCS1_v1_5 as Sig_pk
from Crypto.PublicKey import RSA
import base64

# Content to be signed
name = "musen"
# get private key
key = open('private.pem', 'r').read()
rsakey = RSA.importKey(key)
# Process the signature content according to the sha algorithm (the hash algorithm here is not necessarily sha, see development)
data = SHA.new(name.encode())
# private key to sign
sig_pk = Sig_pk.new(rsakey)
sign = sig_pk.sign(data)
# Convert the signed content to base64 encoding
result = base64.b64encode(sign)
# Convert the signature result to a string
data = result. decode()
print(data)

Public key signature verification:

from Crypto.Hash import SHA
from Crypto.Signature import PKCS1_v1_5 as Sig_pk
from Crypto.PublicKey import RSA
import base64


# before the signature
name = "musen"

# signature data
data="X3Gg + wd7UDh4X8ra + PGCyZFUrG + 6jDeQt6ajMA0EjwoDwxlddLzYoS4dtjQ2q5WCcRhxcp8fjEyoPXBmJE9rMKDjEIeE/VO0sskbJiO65fU8hgcqdWdgbVqRryhOw + Kih + I6RIeNRYnOB8GkGD8Qca + n9JlOELcxLRdLo3vx6dw="
# base64 decoding
data = base64.b64decode(data)
# Get the public key
key = open('public.pem').read()
rsakey = RSA.importKey(key)
# Hash the content before the signature
sha_name = SHA.new(name.encode())
# verify signature
signer = Sig_pk.new(rsakey)
result = signer. verify(sha_name, data)
# If the verification passes, return True, if not, return False
print(result)
The following is the most complete learning knowledge architecture diagram for software testing engineers in 2023

1. Python programming introduction to proficiency

Please add picture description

2. Interface automation project actual combat

Please add picture description

3. Web automation project actual combat

Please add a picture description

4. App automation project actual combat

Please add picture description

5. Resume of first-tier manufacturers

Please add picture description

6. Test and develop DevOps system

Please add picture description

7. Common automated testing tools

Please add a picture description

8. JMeter performance test

Please add picture description

9. Summary (little surprise at the end)

With strength, you will have the courage to overcome everything, and you will have the fighting power of life, and this is the reason for you to live. Live strong, your ideals, your pursuits, have the desire to finally become a reality.

You can never climb a mountain in your life, but you must have a mountain in your heart, it will make you always climb to a higher place, it will make you always have a direction to struggle, it will make you look up at any moment, and you can see yourself hope.

Bowing your head is not admitting defeat, it is to see the road under your feet clearly, and raising your head is not to be proud, it is to see a bigger sky! If you choose to be comfortable at an age when you should be working hard, you will fail miserably.