javascriptnode.jshedera-hashgraph

Convert ED25519 private key from hexadecimal encoded string to DER


Using JavaScript and Node.js, how can I reliably convert an ED25519 private key (used on Hedera Testnet) from hexadecimal encoded string format to DER encoded?

Example input value:

6c91776d90126ce548ac1a399cc174383483d54874297d0f8d083aaXXXXXXXX

The output should be something like this:

302e020100300506032b657004220420xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx


Solution

  • Create a script: convert.js

    #!/usr/bin/env node
    import {PrivateKey} from "@hashgraph/sdk";
    
    let hex = process.argv[2];
    console.log(hex);
    
    let x = PrivateKey.fromStringED25519(hex);
    let der = x.toBytesDer();
    
    let derhex = Buffer.from(der).toString('hex');
    console.log(derhex);
    

    Run:

    npm i
    

    Set "type": "module" in package.json

    Run:

    ./convert.js