Skip to content

Instantly share code, notes, and snippets.

@simcap
Created May 27, 2015 20:53
Show Gist options
  • Select an option

  • Save simcap/baf4597758495bbce355 to your computer and use it in GitHub Desktop.

Select an option

Save simcap/baf4597758495bbce355 to your computer and use it in GitHub Desktop.
Generate DER encoding from known ECDSA private key in JS
"use strict";
var ECKey = require('eckey')
var fs = require('fs')
var seed = process.argv[2]
var bytes = new Uint8Array(32);
for (var i = 0; i < seed.length; i += 2) {
var b = parseInt(seed.substr(i, 2), 16)
bytes[i/2] = b
}
var ck = new ECKey(bytes, false)
var pubkeyhex = ck.publicKey.toString('hex')
console.log("privkey export: " + ck.privateExportKey.toString('hex'))
console.log("pubkey: " + ck.publicKey.toString('hex'))
console.log("pubpoint: " + ck.publicPoint.toString('hex'))
var sequence = [];
// id-ecPublicKey OBJECT IDENTIFIER
// 1, 2, 840, 10045, 2, 1 (06072a8648ce3d0201)
sequence.push(0x06)
sequence.push(0x07)
sequence.push(0x2a)
sequence.push(0x86)
sequence.push(0x48)
sequence.push(0xce)
sequence.push(0x3d)
sequence.push(0x02)
sequence.push(0x01)
// secp256r1 OBJECT IDENTIFIER
// 1, 2, 840, 10045, 3, 1, 7 (06082a8648ce3d030107)
sequence.push(0x06)
sequence.push(0x08)
sequence.push(0x2a)
sequence.push(0x86)
sequence.push(0x48)
sequence.push(0xce)
sequence.push(0x3d)
sequence.push(0x03)
sequence.push(0x01)
sequence.push(0x07)
sequence.unshift(sequence.length);
sequence.unshift(0x30);
sequence.push(0x03);
sequence.push(0x42); // size for rest of content
sequence.push(0x00); // no padding necessary
for (var i = 0; i < pubkeyhex.length; i += 2) {
var b = "0x" + pubkeyhex.substr(i, 2)
sequence.push(b)
}
sequence.unshift(sequence.length);
sequence.unshift(0x30);
var pubkeyder = new Buffer(sequence);
fs.writeFile("node.der", pubkeyder, function(err) {
if(err) {
return console.log(err);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment