Aptos: Get address from privateKey

292 views Asked by At

I need a code for 'aptos' js npm module to get the address from a privatekey.

I have the next code to get the address from a PublicKey:

const { HexString, TxnBuilderTypes } = require("aptos")

let pubKey = "ee23b459bbc3619caa0b978bdfa89551b04c62cd9b7fdb669a398c93d68730e8"

let key = HexString.ensure(pubKey).toUint8Array();

pubKey = new TxnBuilderTypes.Ed25519PublicKey(key)

const authKey = TxnBuilderTypes.AuthenticationKey.fromEd25519PublicKey(pubKey)

console.log(authKey.derivedAddress())

I need one of this two codes.

a) A similar code to get the address from PrivateKey.

b) A code to get the PublicKey from PrivateKey.

Thanks.

2

There are 2 answers

0
Daniel Porteous On

The code from this answer should do the trick: https://stackoverflow.com/a/74517870/3846032.

In short:

import { AptosAccount, HexString } from "aptos";

const privateKeyHex = "0xdcaf65ead38f7cf0eb4f81961f8fc7f9b7f1e2f45e2d4a6da0dbef85f46f6057";
const privateKeyBytes = HexString.ensure(privateKeyHex).toUint8Array();
const account = new AptosAccount(privateKeyBytes);
0
agk On
import { HexString, AptosAccount } from "aptos";

const hexString = HexString.ensure("PRIVATE_KEY").toUint8Array();
const account = new AptosAccount(hexString);

console.log("Address : ", account.address().toString());
console.log("Public Key: ",Buffer.from(account.signingKey.publicKey).toString('hex'));