I can't use identity from

Calling decodeFile(process.env.HOME+"/.config/dfx/identity/default/identity.pem") prints a different identity than dfx identity get-principal.

What’s wrong in my TypeScript code?

import fs from 'fs';
import { Secp256k1KeyIdentity } from '@dfinity/identity-secp256k1';
import sha256 from "sha256";

export function decodeFile(fileName) {
    const rawKey = fs.readFileSync(fileName);
    const rawBuffer = Uint8Array.from(rawKey).buffer;
    const p = sha256(rawBuffer, { asBytes: true }) as Array<number>;
    const privKey = Uint8Array.from(p);
    const identity = Secp256k1KeyIdentity.fromSecretKey(privKey);
    console.log('====================', identity.getPrincipal().toText());
    return identity
}

Also,

$ dfx identity list
anonymous
default *

Not sure what’s wrong but I use the solution of @ZenVoich which works great.

Solution was originally shared in this thread but it seems the current code has been migrated to TS so here’s the direct link: https://github.com/ZenVoich/mops/blob/e4e3b51df1c561b5b00a8e6eef25dcb85b531964/cli/pem.ts#L15

I should really add that as a fromPem method

1 Like

Yes, it works. It creates a working private key the same as my DFX default key, as it should.

It works…So all good now?

I should really add that as a fromPem method

Done!

1 Like