Skip to content

Instantly share code, notes, and snippets.

@fend25
Created October 11, 2023 08:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fend25/9868145aa5b7dc5d6884bb91b7269c87 to your computer and use it in GitHub Desktop.
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
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