Key generation

The minimal JavaScript code used to generate a private key from Passphrase and PIN inputs is shown below.

import { Buffer } from "buffer";
import { ethers } from "ethers";
import { scrypt } from "scrypt-js";

const HASH_OPTIONS = {
  N: 32768, // CPU/memory cost parameter, 2^15
  r: 8, // block size parameter
  p: 5, // parallelization parameter
  keyLen: 64,
};

async function generatePrivateKey(passphrase, pin) {
  const salt = passphrase.slice(-4) + pin

  const passwordBuffer = Buffer.from(passphrase);
  const saltBuffer = Buffer.from(salt);

  const hashBuffer = await scrypt(
    passwordBuffer,
    saltBuffer,
    HASH_OPTIONS.N,
    HASH_OPTIONS.r,
    HASH_OPTIONS.p,
    HASH_OPTIONS.keyLen,
    (p) => console.log(Math.floor(p * 100))
  );
  const hashHex = Buffer.from(hashBuffer).toString("hex");
  const privateKey = ethers.keccak256(abi.encode(["string"], [hashHex]));

  return privateKey;
}

You can find the code herearrow-up-right on Github. You can download the repository and execute it on your local machine as a confirmation and backup for account generation.

And the same codebase is encapsulated in the @mybucks.online/core npm package, facilitating developers in integrating wallet generation into third-party platforms or services.

Run in Sandbox

You can also execute this key-generation process in CodeSandbox without setting up a local environment. Please find the interactive CodeSandbox link herearrow-up-right.

Last updated