1
votes

I'm working on a react-native project and trying to encrypt and decrypt the photo by crypto and using aes-256-gcm algorithm. This code works well on simulator both android and ios, these is no issue on device when I'm debugging as well, but as soon as I stop Remote JS Debugging on android device, this error'll appear: unsupported state or unable to authenticate data. I'm completely confuse and I don't know how I can fix this issue. I should mention that this code'll work correctly for small data and string, only there is problem with large file. Here is my code:

key = crypto.randomBytes(32);

 static encryptFile = inData => {
  let iv = Buffer.from(crypto.randomBytes(16));
  let cipher = crypto.createCipheriv(algorithm, key, iv);
  let encrypted = cipher.update(inData, "binary", "hex");
  encrypted += cipher.final("hex");
  let cipherTag = cipher.getAuthTag();
  encrypted += "," + iv.toString("hex") + "," + cipherTag.toString("hex");
  return encrypted;

};

static decryptFile = inEncData => {
  let encParts = inEncData.split(",");
  let currentIV = Buffer.from(encParts[1], "hex");
  let currentTag = Buffer.from(encParts[2], "hex");
  let decipher = crypto.createDecipheriv(algorithm, key, currentIV);
  decipher.setAuthTag(currentTag);
  let decrypted = decipher.update(encParts[0], "hex");
  let decryptedFinal = decipher.final();
  Buffer.concat([decrypted, decryptedFinal]);
  return decrypted;

};

I read image file by rn-fetch-blob and pass it to encryptFile method:

let res = await RNFetchBlob.fs.readFile(filePath, "ascii");
let enc = convertor.encryptFile(res);
let dec = convertor.decryptFile(enc);

And the error occurs on decryptFile method.

1
Which crypto library you have been used for react native ? Even i need to implement AES GCM Encryption & Decryption algorithm for React native could you please help me for this. Thanks! - Twinkle

1 Answers

-1
votes

Just add utf-8 with hex encoding parameters shown below:

let encrypted = cipher.update(inData, "utf8", "hex");
encrypted += cipher.final("hex");

let decrypted = decipher.update(encParts[0], "hex","utf8");
let decryptedFinal = decipher.final('utf8');