How to use my local private keys in agent-js?


How to generate an identity using my local private keys and use it in agent-js to match the one generated by dfx?

I am trying to use my local private keys to generate my identity to interact with an asset canister.
Link to the code here

I am deploying my local canister with my default local identity and want to call that canister from a nodejs script with the same identity.
I am initializing the agent-js identity like this:

const initIdentity = () => {
  const buffer = readFileSync(process.env.PATH_TO_PRIVATE_KEY!);
  const key = buffer.toString("utf-8");
  const privateKey = createHash("sha256").update(key).digest("base64");

  const secp = Secp256k1KeyIdentity.fromSecretKey(
    Buffer.from(privateKey, "base64"),
  return secp;

const identity = initIdentity();
const principal = identity.getPrincipal();
async function upload() {
  const agent = new HttpAgent({

But when I run my script to store an asset I get this error

Reject code: 4
Reject text: Caller is not authorized

And when logging the caller principal in my canister it’s indeed a different one than my default principal.

I just noticed that Secp256k1KeyIdentity is not the right algorithm maybe Ed25519KeyIdentity,?
But I don’t know which one dfx is using and I can’t find an example.

References to other projects that trying to do the same

I have tried both but none is working for me so far.


Thanks for the detailed post. Same to me (related thread), it’s also one of my blocking issue.


Thanks that’s exactly the same topic,
I searched for any related topic before creating this one but nothing showed up.
Your repo is a great source for inspiration :slight_smile:

1 Like


Cool to notice in the other post that things are now moving, thanks for updating the subject!


This issue have been resolved in another thread