I am encrypting an object
in the frontend and sending an HTTP POST request with the encrypted data. In the backend I am trying to decrypt this object but it fails.
The tests are passing but when integrated to the actual project this decrypt
method fails with error:
Error: error:06065064:digital envelope routines:EVP_DecryptFinal_ex:bad decrypt at Error (native) at Decipher.final (crypto.js:158:26) at Object.exports.decrypt.error [as decrypt]
Here is the relevant code:
export const decrypt = text => {
if (!text)
throw Error('Decrypt: Text may not be blank');
const decipher = crypto.createDecipher(encryptAlgorithm,
encryptionKey)
let decrypted = decipher.update(text, textEncodingHex,
textEncodingUtf8)
decrypted += decipher.final(textEncodingUtf8)
return decrypted
}
And this is how I am using it
authSignInWeb(): any {
return async (request: any, reply: any) => {
try {
let decrytedRequestPayload = request.payload;
if (process.env.REACT_APP_ENCRYPT) {
decrytedRequestPayload = JSON.parse(cryptoHelper.decrypt(request.payload))
}
...
} catch (error) {
reply(error);
...
}
};
};
After going through the Documentation and other online resources I managed to solve this problem. What made this fail is that HapiJs takes the incoming payload, parses it, and pass it down to the authSignInWeb()
as a Javascript object with the actual payload as the key in that object it makes on my behalf.
To solve this I had to, in the frontend, encrypt the data, manually create an object and assign the encrypted information. And then in the backend access the payload's key of the object.
In code:
The frontend is like so:
let encryptedData = {};
if (process.env.REACT_APP_ENCRYPT) {
encryptedData.data = Crypt.encrypt(JSON.stringify(requestBody))
}
and then on the backend (inside authSignInWeb()
) do:
let userAuthData = request.payload;
if (process.env.REACT_APP_ENCRYPT) {
userAuthData = JSON.parse(cryptoHelper.decrypt(userAuthData.data))
}