Last active
July 8, 2024 01:41
-
-
Save sachadee/11d0486ddf854b1a58807e128e303895 to your computer and use it in GitHub Desktop.
Decrypt AES-GCM from python in Javascript (128 bits)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Function to get to convert to bytes the base64 values from python | |
function base64ToUint8Array(base64) { | |
var binaryString = atob(base64); | |
var len = binaryString.length; | |
var bytes = new Uint8Array(len); | |
for (var i = 0; i < len; i++) { | |
bytes[i] = binaryString.charCodeAt(i); | |
} | |
return bytes; | |
} | |
//Base 64 values from python (needed to decode again the message) | |
const key_from_python_base64 = 'ESp/VIgEgyKm1vr/0fZqKacJx1jqWolLoL1VSlGSNgQ='; | |
const cipherText_from_python_base64 = 'AX155UlOs78q1lf0PA=='; | |
const nonce_from_python_base64 = 'es3G3LmMtLLwffuCl8aUlw=='; | |
const tag_from_python_base64 = '9PrESaYl5QpvOVLpzlUrpA=='; | |
const key = base64ToUint8Array(key_from_python_base64); | |
const ciphertext = base64ToUint8Array(cipherText_from_python_base64); | |
const nonce = base64ToUint8Array(nonce_from_python_base64); | |
const tag = base64ToUint8Array(tag_from_python_base64); | |
async function decryptAESGCM(ciphertext, key, nonce, tag) { | |
const algo = { name: "AES-GCM", iv: nonce, tagLength: 128 }; | |
const cryptoKey = await crypto.subtle.importKey( | |
"raw", | |
key, | |
algo, | |
false, | |
["decrypt"] | |
); | |
try { | |
const decrypted = await crypto.subtle.decrypt( | |
{ | |
name: "AES-GCM", | |
iv: nonce, | |
additionalData: new Uint8Array(), | |
tagLength: 128, | |
}, | |
cryptoKey, | |
new Uint8Array([...ciphertext, ...tag]) // Concatenate ciphertext and tag | |
); | |
return new TextDecoder().decode(decrypted); | |
} catch (e) { | |
console.error("Decryption failed:", e); | |
return null; | |
} | |
} | |
//Usage | |
decryptAESGCM(ciphertext, key, nonce, tag).then((decryptedMessage) => { | |
console.log("Decrypted message:", decryptedMessage); | |
}); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment