I have a data in the server that I need to encrypt or sign and send it to react application using API and in react I need to decrypt or verify the signature using the public key. Given below is python code that I'm using:
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)
I Need to decrypt this encrypted message or verify signed data in react application is there any way to do it?
After some research, I found a way to sign a data in python and verify it in react application.
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.