Skip to content
This repository has been archived by the owner on Apr 8, 2020. It is now read-only.

Adds key-composer to support import and export to pem #16

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
"dependencies": {
"async": "^2.6.2",
"bs58": "^4.0.1",
"crypto-key-composer": "~0.1.0",
"multihashing-async": "~0.6.0",
"nodeify": "^1.0.1",
"safe-buffer": "^5.1.2",
Expand All @@ -38,6 +39,7 @@
"aegir": "^18.2.2",
"benchmark": "^2.1.4",
"chai": "^4.2.0",
"chai-string": "^1.5.0",
"dirty-chai": "^2.0.1",
"libp2p-crypto": "~0.16.1"
},
Expand Down
2 changes: 1 addition & 1 deletion src/crypto.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ module.exports = (randomBytes) => {

let privateKey
do {
privateKey = randomBytes(32)
privateKey = randomBytes(privateKeyLength)
} while (!secp256k1.privateKeyVerify(privateKey))

done(null, privateKey)
Expand Down
75 changes: 74 additions & 1 deletion src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

const bs58 = require('bs58')
const multihashing = require('multihashing-async')
const { composePrivateKey, decomposePrivateKey } = require('crypto-key-composer')

module.exports = (keysProtobuf, randomBytes, crypto) => {
crypto = crypto || require('./crypto')(randomBytes)
Expand Down Expand Up @@ -93,6 +94,63 @@ module.exports = (keysProtobuf, randomBytes, crypto) => {
callback(null, bs58.encode(hash))
})
}

/**
* Exports the key into a password protected PEM format
*
* @param {string} [format] - Defaults to 'pkcs-8'.
* @param {string} password - The password to read the encrypted PEM
* @param {function(Error, KeyInfo)} callback
* @returns {undefined}
*/
export (format, password, callback) {
if (typeof password === 'function') {
callback = password
password = format
format = 'pkcs-8'
}

ensure(callback)

let err = null
let pem = null

const decompressedPublicKey = typedArrayToUint8Array(crypto.decompressPublicKey(this.public._key))
try {
if (format === 'pkcs-8') {
pem = composePrivateKey({
format: 'pkcs8-pem',
keyAlgorithm: {
id: 'ec-public-key',
namedCurve: 'secp256k1'
},
keyData: {
d: typedArrayToUint8Array(this.marshal()),
// The public key concatenates the x and y values and adds an initial byte
x: decompressedPublicKey.slice(1, 33),
y: decompressedPublicKey.slice(33, 65)
},
encryptionAlgorithm: {
keyDerivationFunc: {
id: 'pbkdf2',
iterationCount: 10000, // The number of iterations
keyLength: 32, // Automatic, based on the `encryptionScheme`
prf: 'hmac-with-sha512' // The pseudo-random function
},
encryptionScheme: {
id: 'aes256-cbc'
}
}
}, { password })
} else {
err = new Error(`Unknown export format '${format}'`)
}
} catch (_err) {
err = _err
}

callback(err, pem)
}
}

function unmarshalSecp256k1PrivateKey (bytes, callback) {
Expand Down Expand Up @@ -122,17 +180,32 @@ module.exports = (keysProtobuf, randomBytes, crypto) => {
})
}

function importPEM (pem, password, callback) {
let privkey
try {
const decomposedPrivateKey = decomposePrivateKey(pem, { password })
privkey = new Secp256k1PrivateKey(Buffer.from(decomposedPrivateKey.keyData.d))
} catch (err) { return callback(err) }

callback(null, privkey)
}

function ensure (callback) {
if (typeof callback !== 'function') {
throw new Error('callback is required')
}
}

function typedArrayToUint8Array (typedArray) {
return new Uint8Array(typedArray.buffer.slice(typedArray.byteOffset, typedArray.byteOffset + typedArray.byteLength))
}

return {
Secp256k1PublicKey,
Secp256k1PrivateKey,
unmarshalSecp256k1PrivateKey,
unmarshalSecp256k1PublicKey,
generateKeyPair
generateKeyPair,
import: importPEM
}
}
41 changes: 41 additions & 0 deletions test/secp256k1.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ const chai = require('chai')
const dirtyChai = require('dirty-chai')
const expect = chai.expect
chai.use(dirtyChai)
chai.use(require('chai-string'))

const Buffer = require('safe-buffer').Buffer

Expand Down Expand Up @@ -139,6 +140,46 @@ describe('secp256k1 keys', () => {
})
})
})

/* eslint-disable */
describe('import and export', () => {
it('password protected PKCS #8', (done) => {
key.export('pkcs-8', 'my secret', (err, pem) => {
expect(err).to.not.exist()
expect(pem).to.startsWith('-----BEGIN ENCRYPTED PRIVATE KEY-----')
secp256k1.import(pem, 'my secret', (err, clone) => {
expect(err).to.not.exist()
expect(clone).to.exist()
expect(key.equals(clone)).to.eql(true)
done()
})
})
})

it('defaults to PKCS #8', (done) => {
key.export('another secret', (err, pem) => {
expect(err).to.not.exist()
expect(pem).to.startsWith('-----BEGIN ENCRYPTED PRIVATE KEY-----')
secp256k1.import(pem, 'another secret', (err, clone) => {
expect(err).to.not.exist()
expect(clone).to.exist()
expect(key.equals(clone)).to.eql(true)
done()
})
})
})

it('needs correct password', (done) => {
key.export('another secret', (err, pem) => {
expect(err).to.not.exist()
secp256k1.import(pem, 'not the secret', (err, clone) => {
expect(err).to.exist()
done()
})
})
})
})
/* eslint-enable */
})

describe('key generation error', () => {
Expand Down