How can I create the kesytore property using tronWeb

40 Views Asked by At
const tronWeb = require('tronWeb')
const account = tronWeb.createAccount();
const { privateKey, address } = await account;
const password = generateRandomPassword(16);
console.log('password', password);
console.log(`Dirección: ${address.base58}`);
console.log(`Clave privada: ${privateKey}`);

Anyone knows how can I create the keytore ,using tronWeb?

I want to know what is the keystore of this. Thanks a lot

1

There are 1 best solutions below

0
On

I just figured out how to solve this. I left the answer if anyone has the same issue.

const { v4 } = require('uuid');
const CryptoJS = require('crypto-js');
const ethers = require('ethers');
const fs = require('fs');
const bs58check = require('bs58check');

function sliceWordArray(wordArray, start, end) {
  const newArray = wordArray.clone();
  newArray.words = newArray.words.slice(start, end);
  newArray.sigBytes = (end - start) * 4;
  return newArray;
}

function generateKeystore(address, privateKey, password) {
  console.log({ address, privateKey, password });
  privateKey = Buffer.from(privateKey, 'hex');
  return {
    address,
    crypto: encryptPrivateKey(privateKey, password),
    id: v4(),
    version: 3,
  };
}

function encryptPrivateKey(privateKey, password) {
  const iv = CryptoJS.lib.WordArray.random(16);
  const salt = CryptoJS.lib.WordArray.random(32);
  const key = CryptoJS.PBKDF2(password, salt, {
    keySize: 8,
    hasher: CryptoJS.algo.SHA256,
    iterations: 262144,
  });
  const cipher = CryptoJS.AES.encrypt(
    CryptoJS.enc.Hex.parse(privateKey.toString('hex')),
    sliceWordArray(key, 0, 4),
    {
      iv: iv,
      mode: CryptoJS.mode.CTR,
      padding: CryptoJS.pad.NoPadding,
    },
  );

  const mac = CryptoJS.SHA3(
    sliceWordArray(key, 4, 8).concat(cipher.ciphertext),
    {
      outputLength: 256,
    },
  );

  console.log({ ciphertext: cipher.ciphertext.toString() });

  return {
    kdf: 'pbkdf2',
    kdfparams: {
      c: 262144,
      dklen: 32,
      prf: 'hmac-sha256',
      salt: salt.toString(),
    },
    cipher: 'aes-128-ctr',
    ciphertext: cipher.ciphertext.toString(),
    cipherparams: { iv: iv.toString() },
    mac: mac.toString(),
  };
}

function save() {
  const account = this.tronWeb.createAccount();
const { privateKey, address } = await account;
const password = generateRandomPassword(16);
 const keystore = generateKeystore(address.hex, privateKey, password);
  return keystore;
}

save();