margelo / react-native-quick-crypto

⚡️ A fast implementation of Node's `crypto` module written in C/C++ JSI

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

"Invalid iv" error from `crypto.createDecipheriv()` with IV extracted by `Buffer.from()`

gupta-ji6 opened this issue · comments

Goal

To convert an IV created from Crypto.randomBytes(16) to string & then convert it back to array buffer (which Crypto.createDecipheriv() can consume). Basically, we are sending IV in string format from the frontend & the backend will consume it to decipher data.

Problem

When we convert this IV to string & then convert it back to ArrayBuffer, they aren't equal/same. This is causing issues in decrypting the encrypted data.

import Crypto from 'react-native-quick-crypto';
import {Buffer} from '@craftzdog/react-native-buffer';

const IV = Crypto.randomBytes(IV_LENGTH_IN_BYTES);

// convert IV to UTF-8 string
const stringIv = IV.toString(); // Buffer.from(IV).toString('utf8') can also be used, produces same result

// convert string back to buffer to consume it in Crypto.createDecipheriv
const ivBuffer = Buffer.from(iv, 'utf-8'); 

Expectation

IV & ivArrayBuffer above should be equal, but they aren't. The length & data both are different.

Sharing an example of values here:

IV: {"data": [222, 112, 138, 17, 67, 95, 56, 53, 205, 113, 76, 30, 193, 161, 78, 59], "type": "Buffer"}

stringIv: �p�C_85�qL��N;

ivBuffer: {"data": [239, 191, 189, 112, 239, 191, 189, 17, 67, 95, 56, 53, 239, 191, 189, 113, 76, 30, 239, 191, 189, 239, 191, 189, 78, 59], "type": "Buffer"}

Reproduction

You can run the minimal sample app here where this issue is reproduced - https://github.com/gupta-ji6/react-native-test-app/blob/issue/utf8/cipher.ts

P.S. Let me know if I'm converting them incorrectly, I'm not hands-on with Node APIs.

Environment

same issue on RN 0.72.5 as well.

	"@craftzdog/react-native-buffer": "6.0.5",
    "react": "18.2.0",
    "react-native": "0.73.0",
    "react-native-quick-base64": "2.0.8",
    "react-native-quick-crypto": "0.6.1"

Fixed by #264 i believe. make sure to pass the authTagLength you're going for