Created
November 12, 2020 10:11
-
-
Save falcon11/514015d1c285cdcabec05da84d04adca to your computer and use it in GitHub Desktop.
AES_GCM crypto
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
const base64Key = 'your key base64 encode'; | |
let secretKey; | |
function getKeyArray(key) { | |
const bkey = atob(key); | |
const keyArray = []; | |
for (let i = 0; i < bkey.length; i += 1) { | |
keyArray.push(bkey.charCodeAt(i)); | |
} | |
return keyArray; | |
} | |
/* | |
Import an AES secret key from an ArrayBuffer containing the raw bytes. | |
Takes an ArrayBuffer string containing the bytes, and returns a Promise | |
that will resolve to a CryptoKey representing the secret key. | |
*/ | |
function importSecretKey() { | |
const rawKey = new Uint8Array(getKeyArray(base64Key)); | |
return window.crypto.subtle.importKey( | |
"raw", | |
rawKey, | |
"AES-GCM", | |
true, | |
["encrypt", "decrypt"], | |
); | |
} | |
async function encrypt(text) { | |
if (!secretKey) { | |
secretKey = await importSecretKey(); | |
} | |
const iv = window.crypto.getRandomValues(new Uint8Array(12)); | |
const algorithm = { | |
name: 'AES-GCM', | |
iv: iv, | |
}; | |
const enc = new TextEncoder(); | |
const ciphertext = await window.crypto.subtle.encrypt(algorithm, secretKey, enc.encode(text)); | |
const ciphertextUint8Array = new Uint8Array(ciphertext); | |
const resultUint8Array = new Uint8Array(iv.byteLength + ciphertextUint8Array.byteLength); | |
resultUint8Array.set(iv); | |
resultUint8Array.set(ciphertextUint8Array, iv.byteLength); | |
return btoa(String.fromCharCode.apply(null, resultUint8Array)); | |
} | |
async function decrypt(encryptedText) { | |
if (!secretKey) { | |
secretKey = await importSecretKey(); | |
} | |
const btext = new Uint8Array(getKeyArray(encryptedText)); | |
const iv = btext.slice(0, 12); | |
const ciphertext = btext.slice(12, btext.length); | |
const algorithm = { | |
name: 'AES-GCM', | |
iv: iv, | |
}; | |
const result = await window.crypto.subtle.decrypt( | |
algorithm, | |
secretKey, | |
ciphertext, | |
); | |
const dec = new TextDecoder(); | |
return dec.decode(result); | |
} | |
if (typeof window !== 'undefined') { | |
encrypt('123').then(result => { | |
console.log('encrypted', result); | |
decrypt(result).then(decryptedText => { | |
console.log('decrypted', decryptedText); | |
}) | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment