3

With the current version of @solana/web3.js, we can recreate a keypair from a saved secretkey:

const keypair = Keypair.fromSecretKey(secretKey)

The new version of @solana/web3.js has a generateKeyPair() function that returns a CryptoKeyPair.

const keypair = await generateKeyPair();
interface CryptoKeyPair {
    privateKey: CryptoKey;
    publicKey: CryptoKey;
}

How do you convert a secretkey to a CryptoKeyPair that can be used with the new version of @solana/web3.js?

2 Answers 2

4

Thanks Buffalo Joe for the help!

There is a fromLegacyKeypair helper function, which is part of a lib called @solana/compat.

Install the latest version with npm i @solana/compat@experimental

import { fromLegacyKeypair } from "@solana/compat";
import { Keypair } from "@solana/web3.js";

const sender = new Keypair();

const cryptoKeyPair = await fromLegacyKeypair(sender);
console.log(cryptoKeyPair);

As Serban mentioned in the previous comment, fromLegacyKeypair uses the importKey method

It doesn't seem there is currently a helper function to convert raw bytes directly to a CryptoKeypair, but the fromLegacyKeypair helper function can be used as a reference.

0
2

CryptoKeyPair is an object native to browsers that is part of the Web Crypto API.

Solana uses Ed25519, which is not supported on all browsers yet, but the Solana team have offered a polyfill for it. You can find it here along with an example.

To import an existing key, create an Uint8Array of your secret key and use the importKey method.

1
  • This is a link-only answer - answers on Stack Exchange are generally expected to include working code.
    – mikemaccana
    Commented Feb 1 at 2:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.