I am trying to encrypt a string from Laravel side then decrypt this back in VueJS.
Laravel
$key = hash_pbkdf2('sha256', request()->cookie('api-auth-token'), '', 100000, 32, true);
$encrypter = new Encrypter($key, 'aes-256-gcm');
return $encrypter->encrypt($chatSymmetricKey);
VueJS
const processChatSymmetricKey = async (encryptedSymmetricKey: string) => {
const token = getCookieValue("token");
if (!token) {
throw new Error("Token not found in cookies.");
}
const apiAuthToken = "api-auth-token";
const payload = window.atob(encryptedSymmetricKey);
const decodedPayload = JSON.parse(payload);
const { iv, value, mac, tag } = decodedPayload;
const ivArray = Uint8Array.from(atob(iv), c => c.charCodeAt(0));
const encryptedValueArray = Uint8Array.from(atob(value), c => c.charCodeAt(0));
const tagArray = Uint8Array.from(atob(tag), c => c.charCodeAt(0));
const encoder = new TextEncoder();
const keyMaterial = await window.crypto.subtle.importKey(
"raw",
encoder.encode(apiAuthToken),
{ name: "PBKDF2" },
false,
["deriveKey"]
);
const key = await window.crypto.subtle.deriveKey(
{
name: "PBKDF2",
salt: new Uint8Array(0),
iterations: 100000,
hash: "SHA-256",
},
keyMaterial,
{ name: "AES-GCM", length: 256 },
false,
["decrypt"]
);
try {
const decrypted = await window.crypto.subtle.decrypt(
{
name: "AES-GCM",
iv: ivArray,
length: 256,
},
key,
encryptedValueArray,
);
const decryptedChatSymmetricKey = new TextDecoder().decode(decrypted);
console.log(decryptedChatSymmetricKey);
return decrypted;
} catch (error) {
console.error('Decryption failed');
console.error('Error name:', error.name);
console.error('Error message:', error.message);
console.error('Error stack:', error.stack);
console.error('Error code:', error.code);
console.error('Error cause:', error.cause);
return null;
}
};
If I console.log the keyMaterial
, key
, ivArray
, encryptedValueArray
, they all seems to have proper value. Until I get error at the decrypt, but the try catch block doesn’t out any proper error message, and now I am stuck here. Any help is appriecated!
New contributor
jcyin is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.