Created
June 21, 2023 15:50
-
-
Save hyunbinseo/5ba10da66fce325261269df4bd75cff4 to your computer and use it in GitHub Desktop.
Web Crypto - Key Generation, Export, and Import
This file contains hidden or 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
import { webcrypto as crypto } from 'node:crypto'; // Node.js only | |
/* Generate */ | |
const key = await crypto.subtle.generateKey( | |
{ | |
name: 'AES-GCM', | |
length: 256 | |
}, | |
true, | |
['encrypt', 'decrypt'] | |
); | |
/* Export */ | |
const exportedKeyBuffer = await crypto.subtle.exportKey('raw', key); | |
const exportedKeyArray = new Uint32Array(exportedKeyBuffer); // 256 bit / 32 bit = 8 | |
const OTP_SECRET = exportedKeyArray.toString(); | |
// e.g. '42750835,1826404814,1276682799,609486549,910848504,1236505811,2679575580,955180990' | |
/* Import */ | |
const array = OTP_SECRET.split(',').map((string) => Number(string)); | |
// e.g. [42750835,1826404814,1276682799,609486549,910848504,1236505811,2679575580,955180990] | |
export const otpKey = await crypto.subtle.importKey( | |
'raw', | |
new Uint32Array(array), | |
'AES-GCM', | |
true, | |
['encrypt', 'decrypt'] | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment