gpt4 book ai didi

javascript - 如何在 python 中加密/签名数据并使用 RSA 在 Reactjs 中解密?

转载 作者:行者123 更新时间:2023-12-01 01:25:09 25 4
gpt4 key购买 nike

我在服务器中有一个数据,我需要对其进行加密或签名,并将其发送到使用API​​​​的 react 应用程序,并且在 react 中我需要使用公钥解密或验证签名。下面给出的是我正在使用的 python 代码:

import json
from Crypto import Random
from Crypto.PublicKey import RSA
import base64
def generate_keys():
modulus_length = 256 * 10
privatekey = RSA.generate(modulus_length, Random.new().read)
publickey = privatekey.publickey()
return privatekey, publickey
def encrypt_message(a_message, publickey, privatekey):
encrypted_msg = publickey.encrypt(a_message.encode("utf-8"), 32)[0]
sign = privatekey.sign(a_message.encode("utf-8"), 32)
encoded_encrypted_msg = base64.b64encode(encrypted_msg)
return encoded_encrypted_msg.decode("utf-8"), sign;
a_message = 'Hello'
privatekey, publickey = generate_keys()
encrypted_msg, sign = encrypt_message(a_message, publickey, privatekey)

我需要解密此加密消息或验证 react 应用程序中的签名数据,有什么方法可以做到吗?

最佳答案

经过一番研究,我找到了一种在 python 中对数据进行签名并在 React 应用程序中验证它的方法。

python :

from Crypto.PublicKey import RSA
from Crypto.Hash import SHA256
from Crypto.Signature import PKCS1_v1_5
import base64

def sign_message(a_message, privatekey):
digest = SHA256.new()
digest.update(a_message.encode("utf-8"))
privatekey = PKCS1_v1_5.new(privatekey)
sign = base64.b64encode(privatekey.sign(digest))
return sign

def generate_keys():
modulus_length = 256 * 10
privatekey = RSA.generate(modulus_length, Random.new().read)
publickey = privatekey.publickey()
return privatekey, publickey

privatekey, publickey = generate_keys()
a_message = "Hello" # message that we need to sign
sign = sign_message(a_message, privatekey)

javascript/reactjs:

import JSEncrypt from 'jsencrypt';
import CryptoJS from 'crypto-js';
var public_key = new JSEncrypt();
public_key.setPublicKey(publicKey); // publicKey that we get from python
data_to_verify = "Hello" // message you signed in python
signature = Signature_that_you_get_after_signing_in_python
var verified = public_key.verify(data_to_verify, signature, CryptoJS.SHA256);
console.log(verified) // we should get true if we have correct public key, signature and data

关于javascript - 如何在 python 中加密/签名数据并使用 RSA 在 Reactjs 中解密?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53872977/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com