Create pem file from Ed25519

So I have an Ed25519KeyIdentity, I actually used a PEM file to import it, from dfx identity export default. And create it in Node JS.

const identity = X // << some magic to get it from PEM file: .config/dfx/identity/default/identity.pem >>

i.getPrincipal().toText() // is matching with dfx identity get-principal

But how I can get the PEM file from identity? I need some function which can save PEM file given the Ed25519KeyIdentity. But all the methods I tried failed, and the file don’t look the same as original PEM.

1 Like

You might check here: Using @dfinity/agent in node.js - #55 by ZenVoich

So I was able to figure it out:

const DFX_PEM_BEGIN = '-----BEGIN PRIVATE KEY-----';
const DFX_PEM_END = '-----END PRIVATE KEY-----';

export const createPem = (
  identity: Ed25519KeyIdentity
): string => {
  const [publicKey, privateKey] = identity.toJSON();

  // From Dfinity ic:
  // https://github.com/dfinity/ic/blob/master/rs/crypto/utils/basic_sig/src/conversions.rs#L117

  // prettier-ignore
  const der = Buffer.concat([
    Buffer.from([
      0x30, 83, // A sequence of 83 bytes follows.
      2, 1, // An integer denoting version
      1, // 0 if secret key only, 1 if public key is also present
      48, 5, // An element of 5 bytes follows
      6, 3, 43, 101, 112, // The OID
      4, 34, // An octet string of 34 bytes follows.
      4, 32, // An octet string
    ]),
    Buffer.from(privateKey.slice(0, 64), 'hex'),
    Buffer.from([
      161, 35, // An explicitly tagged with 35 bytes.
      3, 33, // A bitstring of 33 bytes follows.
      0,  // The bitstring (32 bytes) is divisible by 8
    ]),
    Buffer.from(privateKey.slice(64), 'hex')
  ]);

  return `${DFX_PEM_BEGIN}\n${der.toString('base64')}\n${DFX_PEM_END}`;
}
2 Likes