polkadot-js / common

Utilities and base libraries for use across polkadot-js for Polkadot and Substrate. Includes base libraries, crypto helpers and cross-environment helpers.
Apache License 2.0
254 stars 147 forks source link

Question for how to get publickey and privatekey & how to verify those key? #1889

Open johnnyji-dev opened 1 year ago

johnnyji-dev commented 1 year ago

Hi, I'm using polkadotjs. When I create a wallet, I create a mnemonic first. After generating the mnemonic, I tried to get some information(address, publickey, privatekey) like below source code. Plz check these below source code and result, and give me some feedback which one is incorrect. If incorrect how can I modify that?

import { mnemonicGenerate, cryptoWaitReady, encodeAddress, mnemonicToMiniSecret, randomAsHex, ed25519PairFromSeed } from '@polkadot/util-crypto'; import { Keyring } from '@polkadot/keyring'; import { u8aToHex, stringToU8a, hexToU8a, u8aToString } from '@polkadot/util';

const create = async (limit) => { let walletList = []; const keyring = new Keyring({ type: 'sr25519', ss58Format: 5 });

for (let i = 0; i < limit; i++) {
    const mnemonic = mnemonicGenerate(); // Creates a valid mnemonic string using using [BIP39]
    await cryptoWaitReady();

    const krpair = keyring.addFromMnemonic(mnemonic, { astar: i }, 'sr25519');
    console.log('mnemonic : ${mnemonic}`);
    const address = krpair.address;
    console.log(`address : ${address}`);
    const publicKey = krpair.publicKey;
    console.log(`publicKey : ${u8aToHex(publicKey)}`);
    const privateKey = mnemonicToMiniSecret(mnemonic);
    console.log(`privateKey : ${u8aToHex(privateKey)}`);

    const edPair = ed25519PairFromSeed(privateKey);

    // console.log(`publicKey : ${u8aToHex(edPair.publicKey)}`);
    console.log(`secretKey : ${u8aToHex(edPair.secretKey)}`);
}

}

create(1);

Additionally, How can I get "mnemonic" from secretKey?