z-hao-wang / react-native-rsa

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

Using .pem file or convert JSON to .pem file #4

Closed kevinvn1709 closed 7 years ago

kevinvn1709 commented 8 years ago

Hi @z-hao-wang, Thanks for your great library. But, I want to know how to use your lib with .pem file or how can I convert between .pem file to JSON format to use it.

I have no idea about that.

Thanks

z-hao-wang commented 8 years ago

There are tool can extract components from pen files. Try ursa lib

kevinvn1709 commented 8 years ago

Hi @z-hao-wang,

I had try use ursa. But it seems got a little problems.

I used your library to create publicKey. We have n and e component. Then I use ursa lib to create PublicKeyFromComponent after that I encrypt a message from this publicKey as hex string format

But when I try to decrypt that message with your lib, it does not works and return null.

Could you take time give me a testing your lib work with ursa (Encrypt/Decrypt)? I saw that you did it in READ.ME.

Thanks.

z-hao-wang commented 8 years ago

in URSA var crt = ursa.createPublicKeyFromComponents(new Buffer(publicKey.n, 'hex'), new Buffer(publicKey.e, 'hex')); var textToEncrypt = 'sampleText'; var encryptedCipher = crt.encrypt(textToEncrypt, 'utf8', 'base64', DEFAULT_RSA_PADDING);

In react-native // convert a base64 string to hex function b64tohex(s) { var ret = ""; var i; var k = 0; // b64 state, 0-3 var slop; for (i = 0; i < s.length; ++i) { if (s.charAt(i) == b64padchar) break; v = b64map.indexOf(s.charAt(i)); if (v < 0) continue; if (k == 0) { ret += int2char(v >> 2); slop = v & 3; k = 1; } else if (k == 1) { ret += int2char((slop << 2) | (v >> 4)); slop = v & 0xf; k = 2; } else if (k == 2) { ret += int2char(slop); ret += int2char(v >> 2); slop = v & 3; k = 3; } else { ret += int2char((slop << 2) | (v >> 4)); ret += int2char(v & 0xf); k = 0; } } if (k == 1) ret += int2char(slop << 2); return ret; } decryptRSA(encrypted, format) { format = format || 'base64'; if (format == 'base64') { encrypted = b64tohex(encrypted); } this.rsa = this.rsa || new ReactNativeRSA(); return this.rsa.decrypt(encrypted); }

Make sure the text length is smaller than the size of your RSA key size.

z-hao-wang commented 8 years ago

made a gist for it https://gist.github.com/z-hao-wang/da3fe5e4c22b9f80040d702a261b406e

tanapaydin commented 7 years ago

@kevinvn1709, did you figure this out? I also need to convert the json formattted private key into pem format. And vice versa later on (from pem to json). Did you able find another react-native library to do this?

kevinvn1709 commented 7 years ago

Thanks @z-hao-wang for your code. Sorry, I missed this message. I was busy in last 3 weeks. At the moment I am using this Repo https://github.com/mvayngrib/react-native-crypto to resolve my project that need to use RSA and AES