每天进步一点点-加密与解密

import config
from Utils.ParseXmlUtil import check_string, check_open_ability_sign
from Crypto import Random
from Crypto.Hash import SHA256
from Crypto.Cipher import PKCS1_v1_5 as Cipher_pkcs1_v1_5
from Crypto.Signature import PKCS1_v1_5 as Signature_pkcs1_v1_5
from Crypto.PublicKey import RSA
import base64

request_body = {'orderId': '836211012110000410412', 'orderStatus': '20102', 'operation': 'P205022601', 'originalCode': 'EC1029'}

# 平铺字符串及url编码按指定格式排列
ret = check_string(request_body, '/order/status/up')
print(ret)

# # 签名:私钥加密
# hash_obj = SHA256.new(ret.encode("utf-8"))
# PRIVATE_KEY = config.CURRENT_CONFIG["PRIVATE_KEY"]
# pri_rsa_key = RSA.importKey(PRIVATE_KEY)
# signer = Signature_pkcs1_v1_5.new(pri_rsa_key).sign(hash_obj)
# signature = base64.b64encode(signer)
# print(signature)
# signature_string = signature.decode()  # 请求带来的签名串
# print(signature)
# # 公钥延签
# PUBLIC_KEY = config.CURRENT_CONFIG["PUBLIC_KEY"]
# ssss = check_open_ability_sign(ret, signature)
# print(ssss)


# 加密解密:公钥加密,私钥解密
# 1. 生成 private key and pulic key
# 伪随机数生成器
random_generator = Random.new().read
# rsa算法生成实例
rsa = RSA.generate(1024, random_generator)
# 秘钥对的生成
private_pem = rsa.exportKey()
print(private_pem)
public_pem = rsa.publickey().exportKey()
print(public_pem)

# 2. 加密
PUBLIC_KEY = config.CURRENT_CONFIG["PUBLIC_KEY"]
rsakey = RSA.importKey(PUBLIC_KEY)
cipher = Cipher_pkcs1_v1_5.new(rsakey)
cipher_text = base64.b64encode(cipher.encrypt(ret))
print(cipher_text)

# 3. 解密还原加密字符串
PRIVATE_KEY = config.CURRENT_CONFIG["PRIVATE_KEY"]
cipher = Cipher_pkcs1_v1_5.new(PRIVATE_KEY)
text = cipher.decrypt(base64.b64decode(cipher_text), random_generator)

chatgpt写的

# Import necessary libraries for encryption and decryption
from cryptography.fernet import Fernet

# Define a function to generate a key for encryption and decryption
def generate_key():
    key = Fernet.generate_key()
    with open("secret.key", "wb") as key_file:
        key_file.write(key)

# Define a function to load the key for encryption and decryption
def load_key():
    return open("secret.key", "rb").read()

# Define a function to encrypt a message
def encrypt_message(message):
    key = load_key()
    encoded_message = message.encode()
    f = Fernet(key)
    encrypted_message = f.encrypt(encoded_message)
    return encrypted_message

# Define a function to decrypt a message
def decrypt_message(encrypted_message):
    key = load_key()
    f = Fernet(key)
    decrypted_message = f.decrypt(encrypted_message)
    return decrypted_message.decode()

# Call the generate_key() function to generate a key
generate_key()

# Test the encryption and decryption functions
message = "Hello, world!"
encrypted_message = encrypt_message(message)
decrypted_message = decrypt_message(encrypted_message)
print("Original message:", message)
print("Encrypted message:", encrypted_message)
print("Decrypted message:", decrypted_message)
posted @ 2023-04-04 16:23  Alive_2020  阅读(20)  评论(0编辑  收藏  举报