z-hao-wang / react-native-rsa

React native rsa crypto
MIT License
68 stars 19 forks source link

can not decrypt with ursa #6

Open moshebeeri opened 7 years ago

moshebeeri commented 7 years ago

I am using this code on the react-native side:

` const rsa = new RSAKey();

rsa.setPublicString(JSON.stringify(public_key));

const encrypted = rsa.encrypt(data); `

and on node.js:

let key = ursa.createPrivateKey(user.privateKey); let msg = key.decrypt(encrypted, 'hex', 'utf-8', ursa.RSA_PKCS1_PADDING);

And I get an exception with no message.

What am I doing wrong? Do you have code demonstrating decryption in node.js node-rsa or ursa?

haowang-usc commented 7 years ago

Try this https://gist.github.com/z-hao-wang/da3fe5e4c22b9f80040d702a261b406e

haowang-usc commented 7 years ago

ursa.createPrivateKey() only takes a .pem format as far as I understand. So you would need to convert your private key components to a pem file. (I forget how to)

moshebeeri commented 7 years ago

The link is showing encryption on node.js side and decryption on react native side, I need the other way around. as for ursa.createPrivateKey() I provide .pem format already. I notice your code returns 'hex' string, hence I try to decrypt using this command key.decrypt(encrypted, 'hex', 'utf-8', ursa.RSA_PKCS1_PADDING). From documentation it looks like it should work, but its not. I also tried to use node-rsa let key = new NodeRSA(user.privateKey, 'private', {encryptionScheme: 'pkcs1'}); let res_qrcode = key.decrypt(new Buffer(req.body.data, 'hex'), 'utf-8'); But the encryption string length % key is not 0 any idea?

z-hao-wang commented 7 years ago

I provide my working code Make sure the string encrypting is smaller than your rsa key size

var key = ursa.createPrivateKey(fs.readFileSync(__dirname + '/key.pem'), process.env.APN_KEY_SECRET);

var decryptRSA = function (encrypted, format) {
    format = format || 'base64';
    return key.decrypt(new Buffer(encrypted, format), format, 'utf8', ursa.RSA_PKCS1_PADDING);
  }
var decryptedText = decryptRSA('[some encrypted string with public key]');
z-hao-wang commented 7 years ago

I have no luck with using NodeRSA either. I was able to use ursa to decrypt.