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.