Last active
September 22, 2020 23:24
-
-
Save jonathanstiansen/47be24694610767fa6780ebb52aeb87e to your computer and use it in GitHub Desktop.
Encrypt in Node and Decrypt in React-Native (the reverse is almost identical)
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
// The purpose of this is that there was as cipher vulnerability found in the javascript implementation of the main | |
//. crypto-js library. | |
//. The native implementation they created made it unusable on react-native | |
// The reason we are using the node version of crypto is because the only supported AES from the react-native | |
//. implementation is aes-128-cbc | |
//. The node crypto library seems to be the only lib that supports that specific version. | |
// requires installing - https://www.npmjs.com/package/react-native-simple-crypto also linking | |
import RNSimpleCrypto from 'react-native-simple-crypto' | |
const toUtf8 = RNSimpleCrypto.utils.convertArrayBufferToUtf8 | |
function decrypt(hexString){ | |
const key = RNSimpleCrypto.utils.convertHexToArrayBuffer(SECRET) | |
const iv = RNSimpleCrypto.utils.convertHexToArrayBuffer(IV_HEX) | |
const token = RNSimpleCrypto.utils.convertHexToArrayBuffer(hexString) | |
return RNSimpleCrypto.AES.decrypt(token, key, iv) | |
} | |
// In node file, send the excrpytedToken 'over-the-wire' | |
function encrypt(aString) { | |
try { | |
const iv = new Buffer(IV_HEX, 'hex') | |
const key = new Buffer(SECRET, 'hex') | |
const encryptedBuffer = new Buffer(token) | |
// This is the only supported algorithm for AES for the react-native library | |
const cipher = crypto.createCipheriv('aes-128-cbc', key, iv) | |
const chunks = [cipher.update(encryptedBuffer, 'buffer', 'hex'), cipher.final('hex')] | |
const encryptedToken = chunks.join('') | |
return encryptedToken | |
} catch (e) { | |
// do something | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment