Created
October 19, 2016 17:45
-
-
Save z-hao-wang/da3fe5e4c22b9f80040d702a261b406e to your computer and use it in GitHub Desktop.
react-native-rsa work with ursa
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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; | |
} | |
function decryptRSA(encrypted, format) { | |
format = format || 'base64'; | |
if (format == 'base64') { | |
encrypted = b64tohex(encrypted); | |
} | |
this.rsa = this.rsa || new ReactNativeRSA(); | |
return this.rsa.decrypt(encrypted); | |
} | |
decryptRSA(encryptedCipher); | |
//Make sure the text length is smaller than the size of your RSA key size. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment