0

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?

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.