js-peer-id/src/index.js

91 lines
1.8 KiB
JavaScript
Raw Normal View History

2015-07-08 14:51:49 -07:00
/*
* Id is an object representation of a peer Id. a peer Id is a multihash
*/
var multihashing = require('multihashing')
var base58 = require('bs58')
var keypair = require('keypair')
2015-11-05 18:51:53 +00:00
var forge = require('node-forge')
2015-07-08 14:51:49 -07:00
exports = module.exports = Id
2015-11-05 17:47:44 +00:00
exports.Buffer = Buffer
2015-07-17 08:14:44 -07:00
function Id (id, privKey, pubKey) {
2015-07-08 14:51:49 -07:00
var self = this
if (!(self instanceof Id)) {
throw new Error('Id must be called with new')
}
self.privKey = privKey
self.pubKey = pubKey
self.id = id // multihash - sha256 - buffer
// pretty print
self.toPrint = function () {
return {
2015-11-05 18:46:02 +00:00
id: self.toHexString(),
2015-07-08 14:51:49 -07:00
privKey: privKey.toString('hex'),
pubKey: pubKey.toString('hex')
}
}
// encode/decode functions
self.toHexString = function () {
return self.id.toString('hex')
}
self.toBytes = function () {
return self.id
}
self.toB58String = function () {
return base58.encode(self.id)
}
}
2015-11-05 18:51:53 +00:00
function fix (str) {
return str.replace(/\r/g, '') + '\n'
}
2015-07-08 14:51:49 -07:00
// generation
exports.create = function () {
var pair = keypair()
2015-07-08 14:51:49 -07:00
var mhId = multihashing(pair.public, 'sha2-256')
2015-07-08 14:51:49 -07:00
return new Id(mhId, pair.private, pair.public)
2015-07-08 14:51:49 -07:00
}
exports.createFromHexString = function (str) {
return new Id(new Buffer(str), 'hex')
}
exports.createFromBytes = function (buf) {
return new Id(buf)
}
exports.createFromB58String = function (str) {
return new Id(new Buffer(base58.decode(str)))
}
exports.createFromPubKey = function (pubKey) {
var mhId = multihashing(pubKey, 'sha2-256')
return new Id(mhId, null, pubKey)
}
2015-11-05 18:51:53 +00:00
exports.createFromPrivKey = function (privKey) {
var privateKey = forge.pki.privateKeyFromPem(privKey)
var publicKey = {
n: privateKey.n,
e: privateKey.e
}
var pubKey = fix(forge.pki.publicKeyToRSAPublicKeyPem(publicKey, 72))
var mhId = multihashing(pubKey, 'sha2-256')
return new Id(mhId, privKey, pubKey)
2015-07-08 14:51:49 -07:00
}