Created
October 11, 2023 08:39
-
-
Save fend25/9868145aa5b7dc5d6884bb91b7269c87 to your computer and use it in GitHub Desktop.
Example of safely save some secret info (polkadot mnemonic) in the local storage
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
import {Sr25519Account} from '@unique-nft/sr25519' | |
import {algorithms} from '@unique-nft/utils/address' | |
import {getRandomValues} from 'node:crypto' // remove for browser code | |
import {secretbox, secretbox_open} from 'tweetnacl-ts' | |
const textEncoder = new TextEncoder() | |
const textDecoder = new TextDecoder() | |
const mnemonic = Sr25519Account.generateMnemonic() | |
const mnemonicByteArray = textEncoder.encode(mnemonic) | |
const password = 'Pa$$w0rd' | |
const passwordHash = algorithms.keccak_256(textEncoder.encode(password)) | |
const nonce = getRandomValues(new Uint8Array(24)) | |
const boxed = secretbox(mnemonicByteArray, nonce, passwordHash) | |
const SAVE_TO_LOCALSTORAGE = { | |
address: Sr25519Account.fromUri(mnemonic).address, | |
nonce: nonce, | |
boxed: boxed, | |
} | |
console.dir(SAVE_TO_LOCALSTORAGE) | |
console.log(`source mnemonic: ${mnemonic}`) | |
const unboxed = secretbox_open(boxed, nonce, passwordHash) | |
if (!unboxed) { | |
throw new Error('Cannot unbox') | |
} | |
const decodedMnemonic = textDecoder.decode(unboxed) | |
console.log(`decoded mnemonic: ${decodedMnemonic}`) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment