Compare commits

...

6 Commits

Author SHA1 Message Date
Vasco Santos
99a405d331 chore: update travis 2021-04-07 11:58:30 +02:00
Vasco Santos
3061d4751e chore: remove protons 2021-04-07 11:39:25 +02:00
Vasco Santos
3041ef7ba7 chore: update deps 2021-04-07 11:15:26 +02:00
Jacob Heun
a05e870c45 chore: release version v0.19.2 2021-03-17 19:03:03 +01:00
Jacob Heun
bc681c76f4 chore: update contributors 2021-03-17 19:03:02 +01:00
Nadim Kobeissi
1c16dd3dec fix: ed25519 PeerID generation (#186)
* Fix Ed25519 PeerID generation

This commit pushes further fixes to the generation of Ed25519 peer IDs,
building upon the discussion in ipfs/js-ipfs#3591 and the subsequent
pull request libp2p/js-libp2p-crypto#185.

The purpose of this new pull request is to harmonize the encoding of
PeerIDs for Ed25519 keys such that the same new format is used
everywhere: peer IDs when assigned upon key generation, peer IDs when
shown via key listing, as well as the peer IDs displayed as IPNS names
when the key is used as the basis for an IPNS record.

Concretely, this changes the peer ID representation of Ed25519 keys from
the `Qm...` format to the newer `1...` format.

The accompanying test has been modified accordingly.

* Satisfy linter
2021-03-17 19:01:53 +01:00
17 changed files with 482 additions and 85 deletions

View File

@@ -1,3 +0,0 @@
module.exports = {
bundlesize: { maxSize: '124kB' }
}

View File

@@ -1,15 +1,19 @@
language: node_js
cache: npm
branches:
only:
- master
- /^release\/.*$/
stages:
- check
- test
- cov
node_js:
- '10'
- '12'
- 'lts/*'
- 'node'
os:
- linux
@@ -23,7 +27,7 @@ jobs:
include:
- stage: check
script:
- npx aegir build --bundlesize
- npx aegir build --no-types
- npx aegir dep-check
- npm run lint

View File

@@ -1,3 +1,13 @@
<a name="0.19.2"></a>
## [0.19.2](https://github.com/libp2p/js-libp2p-crypto/compare/v0.19.1...v0.19.2) (2021-03-17)
### Bug Fixes
* ed25519 PeerID generation ([#186](https://github.com/libp2p/js-libp2p-crypto/issues/186)) ([1c16dd3](https://github.com/libp2p/js-libp2p-crypto/commit/1c16dd3)), closes [ipfs/js-ipfs#3591](https://github.com/ipfs/js-ipfs/issues/3591) [libp2p/js-libp2p-crypto#185](https://github.com/libp2p/js-libp2p-crypto/issues/185)
<a name="0.19.1"></a>
## [0.19.1](https://github.com/libp2p/js-libp2p-crypto/compare/v0.19.0...v0.19.1) (2021-03-15)

View File

@@ -1,6 +1,6 @@
{
"name": "libp2p-crypto",
"version": "0.19.1",
"version": "0.19.2",
"description": "Crypto primitives for libp2p",
"main": "src/index.js",
"types": "src/index.d.ts",
@@ -18,8 +18,8 @@
],
"scripts": {
"lint": "aegir lint",
"build": "aegir build",
"build-proto": "pbjs --wrap commonjs --target static-module src/keys/keys.proto > src/keys/keys.proto.js",
"build": "npm run build:proto && aegir build --no-types",
"build:proto": "pbjs -t static-module -w commonjs --force-number --no-verify --no-delimited --no-create --no-beautify --no-defaults --lint eslint-disable -o src/keys/keys.js ./src/keys/keys.proto",
"test": "aegir test",
"test:node": "aegir test -t node",
"test:browser": "aegir test -t browser -t webworker",
@@ -39,18 +39,19 @@
],
"license": "MIT",
"dependencies": {
"err-code": "^2.0.0",
"err-code": "^3.0.1",
"is-typedarray": "^1.0.0",
"iso-random-stream": "^1.1.0",
"iso-random-stream": "^2.0.0",
"keypair": "^1.0.1",
"multibase": "^3.0.0",
"multicodec": "^2.0.0",
"multihashing-async": "^2.0.1",
"multibase": "^4.0.3",
"multicodec": "^3.0.1",
"multihashes": "^4.0.2",
"multihashing-async": "^2.1.2",
"node-forge": "^0.10.0",
"pem-jwk": "^2.0.0",
"protons": "^2.0.0",
"protobufjs": "^6.10.2",
"secp256k1": "^4.0.0",
"uint8arrays": "^1.1.0",
"uint8arrays": "^2.1.4",
"ursa-optional": "^0.10.1"
},
"devDependencies": {
@@ -58,16 +59,21 @@
"@types/chai-string": "^1.4.2",
"@types/dirty-chai": "^2.0.2",
"@types/mocha": "^8.0.1",
"aegir": "^25.0.0",
"aegir": "^33.0.0",
"benchmark": "^2.1.4",
"chai": "^4.2.0",
"chai-string": "^1.5.0",
"dirty-chai": "^2.0.1",
"sinon": "^9.0.0"
"sinon": "^10.0.0",
"util": "^0.12.3"
},
"aegir": {
"build": {
"bundlesizeMax": "118kB"
}
},
"engines": {
"node": ">=10.0.0",
"npm": ">=6.0.0"
"node": ">=12.0.0"
},
"repository": {
"type": "git",
@@ -88,18 +94,18 @@
"Cayman <caymannava@gmail.com>",
"Yusef Napora <yusef@napora.org>",
"ᴠɪᴄᴛᴏʀ ʙᴊᴇʟᴋʜᴏʟᴍ <victorbjelkholm@gmail.com>",
"Arve Knudsen <arve.knudsen@gmail.com>",
"Alex Potsides <alex@achingbrain.net>",
"Vasco Santos <vasco.santos@ua.pt>",
"Arve Knudsen <arve.knudsen@gmail.com>",
"Alberto Elias <hi@albertoelias.me>",
"Jack Kleeman <jackkleeman@gmail.com>",
"Nadim Kobeissi <nadim@symbolic.software>",
"Richard Littauer <richard.littauer@gmail.com>",
"Richard Schneider <makaretu@gmail.com>",
"dirkmc <dirkmdev@gmail.com>",
"nikuda <nikuda@gmail.com>",
"Joao Santos <jrmsantos15@gmail.com>",
"Carson Farmer <carson.farmer@gmail.com>",
"Tom Swindell <t.swindell@rubyx.co.uk>",
"Nadim Kobeissi <nadim@symbolic.software>"
"Tom Swindell <t.swindell@rubyx.co.uk>"
]
}

View File

@@ -11,11 +11,11 @@ const webcrypto = require('../webcrypto')
*
* @param {object} [options]
* @param {string} [options.algorithm=AES-GCM]
* @param {Number} [options.nonceLength=12]
* @param {Number} [options.keyLength=16]
* @param {number} [options.nonceLength=12]
* @param {number} [options.keyLength=16]
* @param {string} [options.digest=sha256]
* @param {Number} [options.saltLength=16]
* @param {Number} [options.iterations=32767]
* @param {number} [options.saltLength=16]
* @param {number} [options.iterations=32767]
* @returns {*}
*/
function create ({
@@ -33,8 +33,8 @@ function create ({
* Uses the provided password to derive a pbkdf2 key. The key
* will then be used to encrypt the data.
*
* @param {Uint8Array} data The data to decrypt
* @param {string} password A plain password
* @param {Uint8Array} data - The data to decrypt
* @param {string} password - A plain password
* @returns {Promise<Uint8Array>}
*/
async function encrypt (data, password) { // eslint-disable-line require-await
@@ -58,8 +58,8 @@ function create ({
* this decryption cipher must be the same as those used to create
* the encryption cipher.
*
* @param {Uint8Array} data The data to decrypt
* @param {string} password A plain password
* @param {Uint8Array} data - The data to decrypt
* @param {string} password - A plain password
* @returns {Promise<Uint8Array>}
*/
async function decrypt (data, password) {

View File

@@ -9,12 +9,12 @@ const uint8ArrayFromString = require('uint8arrays/from-string')
/**
*
* @param {object} [options]
* @param {Number} [options.algorithmTagLength=16]
* @param {Number} [options.nonceLength=12]
* @param {Number} [options.keyLength=16]
* @param {number} [options.algorithmTagLength=16]
* @param {number} [options.nonceLength=12]
* @param {number} [options.keyLength=16]
* @param {string} [options.digest=sha256]
* @param {Number} [options.saltLength=16]
* @param {Number} [options.iterations=32767]
* @param {number} [options.saltLength=16]
* @param {number} [options.iterations=32767]
* @returns {*}
*/
function create ({
@@ -49,8 +49,8 @@ function create ({
* Uses the provided password to derive a pbkdf2 key. The key
* will then be used to encrypt the data.
*
* @param {Uint8Array} data The data to decrypt
* @param {string|Uint8Array} password A plain password
* @param {Uint8Array} data - The data to decrypt
* @param {string|Uint8Array} password - A plain password
* @returns {Promise<Uint8Array>}
*/
async function encrypt (data, password) { // eslint-disable-line require-await
@@ -76,7 +76,7 @@ function create ({
* the encryption cipher.
*
* @private
* @param {Uint8Array} ciphertextAndNonce The data to decrypt
* @param {Uint8Array} ciphertextAndNonce - The data to decrypt
* @param {Uint8Array} key
* @returns {Promise<Uint8Array>}
*/
@@ -100,8 +100,8 @@ function create ({
* this decryption cipher must be the same as those used to create
* the encryption cipher.
*
* @param {Uint8Array} data The data to decrypt
* @param {string|Uint8Array} password A plain password
* @param {Uint8Array} data - The data to decrypt
* @param {string|Uint8Array} password - A plain password
*/
async function decrypt (data, password) { // eslint-disable-line require-await
// Create Uint8Arrays of salt and ciphertextAndNonce.

View File

@@ -1,13 +1,11 @@
'use strict'
const sha = require('multihashing-async/src/sha')
const protobuf = require('protons')
const errcode = require('err-code')
const uint8ArrayEquals = require('uint8arrays/equals')
const uint8ArrayToString = require('uint8arrays/to-string')
const mh = require('multihashes')
const crypto = require('./ed25519')
const pbm = protobuf(require('./keys.proto'))
const pbm = require('./keys')
const exporter = require('./exporter')
class Ed25519PublicKey {
@@ -27,7 +25,7 @@ class Ed25519PublicKey {
return pbm.PublicKey.encode({
Type: pbm.KeyType.Ed25519,
Data: this.marshal()
})
}).finish()
}
equals (key) {
@@ -63,7 +61,7 @@ class Ed25519PrivateKey {
return pbm.PrivateKey.encode({
Type: pbm.KeyType.Ed25519,
Data: this.marshal()
})
}).finish()
}
equals (key) {
@@ -81,11 +79,11 @@ class Ed25519PrivateKey {
* The public key is a protobuf encoding containing a type and the DER encoding
* of the PKCS SubjectPublicKeyInfo.
*
* @returns {Promise<String>}
* @returns {Promise<string>}
*/
async id () {
const hash = await this.public.hash()
return uint8ArrayToString(hash, 'base58btc')
const encoding = mh.encode(this.public.bytes, 'identity')
return await mh.toB58String(encoding)
}
/**

View File

@@ -9,7 +9,7 @@ module.exports = {
* The PrivateKey is encrypted via a password derived PBKDF2 key
* leveraging the aes-gcm cipher algorithm.
*
* @param {Uint8Array} privateKey The PrivateKey protobuf
* @param {Uint8Array} privateKey - The PrivateKey protobuf
* @param {string} password
* @returns {Promise<string>} A base64 encoded string
*/

View File

@@ -9,7 +9,7 @@ module.exports = {
* with the given password. The privateKey must have been exported
* using the same password and underlying cipher (aes-gcm)
*
* @param {string} privateKey A base64 encoded encrypted key
* @param {string} privateKey - A base64 encoded encrypted key
* @param {string} password
* @returns {Promise<Uint8Array>} The private key protobuf
*/

View File

@@ -1,7 +1,6 @@
'use strict'
const protobuf = require('protons')
const keysPBM = protobuf(require('./keys.proto'))
const keysPBM = require('./keys')
require('node-forge/lib/asn1')
require('node-forge/lib/pbe')
const forge = require('node-forge/lib/forge')
@@ -10,17 +9,12 @@ const uint8ArrayFromString = require('uint8arrays/from-string')
const importer = require('./importer')
exports = module.exports
const supportedKeys = {
rsa: require('./rsa-class'),
ed25519: require('./ed25519-class'),
secp256k1: require('./secp256k1-class')(keysPBM, require('../random-bytes'))
}
exports.supportedKeys = supportedKeys
exports.keysPBM = keysPBM
const ErrMissingSecp256K1 = {
message: 'secp256k1 support requires libp2p-crypto-secp256k1 package',
code: 'ERR_MISSING_PACKAGE'
@@ -35,17 +29,14 @@ function typeToKey (type) {
return key
}
exports.keyStretcher = require('./key-stretcher')
exports.generateEphemeralKeyPair = require('./ephemeral-keys')
// Generates a keypair of the given type and bitsize
exports.generateKeyPair = async (type, bits) => { // eslint-disable-line require-await
const generateKeyPair = async (type, bits) => { // eslint-disable-line require-await
return typeToKey(type).generateKeyPair(bits)
}
// Generates a keypair of the given type and bitsize
// seed is a 32 byte uint8array
exports.generateKeyPairFromSeed = async (type, seed, bits) => { // eslint-disable-line require-await
const generateKeyPairFromSeed = async (type, seed, bits) => { // eslint-disable-line require-await
const key = typeToKey(type)
if (type.toLowerCase() !== 'ed25519') {
throw errcode(new Error('Seed key derivation is unimplemented for RSA or secp256k1'), 'ERR_UNSUPPORTED_KEY_DERIVATION_TYPE')
@@ -55,7 +46,7 @@ exports.generateKeyPairFromSeed = async (type, seed, bits) => { // eslint-disabl
// Converts a protobuf serialized public key into its
// representative object
exports.unmarshalPublicKey = (buf) => {
const unmarshalPublicKey = (buf) => {
const decoded = keysPBM.PublicKey.decode(buf)
const data = decoded.Data
@@ -76,7 +67,7 @@ exports.unmarshalPublicKey = (buf) => {
}
// Converts a public key object into a protobuf serialized public key
exports.marshalPublicKey = (key, type) => {
const marshalPublicKey = (key, type) => {
type = (type || 'rsa').toLowerCase()
typeToKey(type) // check type
return key.bytes
@@ -84,7 +75,7 @@ exports.marshalPublicKey = (key, type) => {
// Converts a protobuf serialized private key into its
// representative object
exports.unmarshalPrivateKey = async (buf) => { // eslint-disable-line require-await
const unmarshalPrivateKey = async (buf) => { // eslint-disable-line require-await
const decoded = keysPBM.PrivateKey.decode(buf)
const data = decoded.Data
@@ -105,7 +96,7 @@ exports.unmarshalPrivateKey = async (buf) => { // eslint-disable-line require-aw
}
// Converts a private key object into a protobuf serialized private key
exports.marshalPrivateKey = (key, type) => {
const marshalPrivateKey = (key, type) => {
type = (type || 'rsa').toLowerCase()
typeToKey(type) // check type
return key.bytes
@@ -116,10 +107,10 @@ exports.marshalPrivateKey = (key, type) => {
* @param {string} encryptedKey
* @param {string} password
*/
exports.import = async (encryptedKey, password) => { // eslint-disable-line require-await
const importKey = async (encryptedKey, password) => { // eslint-disable-line require-await
try {
const key = await importer.import(encryptedKey, password)
return exports.unmarshalPrivateKey(key)
return unmarshalPrivateKey(key)
} catch (_) {
// Ignore and try the old pem decrypt
}
@@ -133,3 +124,17 @@ exports.import = async (encryptedKey, password) => { // eslint-disable-line requ
der = uint8ArrayFromString(der.getBytes(), 'ascii')
return supportedKeys.rsa.unmarshalRsaPrivateKey(der)
}
module.exports = {
supportedKeys,
keysPBM,
keyStretcher: require('./key-stretcher'),
generateEphemeralKeyPair: require('./ephemeral-keys'),
generateKeyPair,
generateKeyPairFromSeed,
unmarshalPublicKey,
marshalPublicKey,
unmarshalPrivateKey,
marshalPrivateKey,
import: importKey
}

378
src/keys/keys.js Normal file
View File

@@ -0,0 +1,378 @@
/*eslint-disable*/
"use strict";
var $protobuf = require("protobufjs/minimal");
// Common aliases
var $Reader = $protobuf.Reader, $Writer = $protobuf.Writer, $util = $protobuf.util;
// Exported root namespace
var $root = $protobuf.roots["default"] || ($protobuf.roots["default"] = {});
/**
* KeyType enum.
* @exports KeyType
* @enum {number}
* @property {number} RSA=0 RSA value
* @property {number} Ed25519=1 Ed25519 value
* @property {number} Secp256k1=2 Secp256k1 value
*/
$root.KeyType = (function() {
var valuesById = {}, values = Object.create(valuesById);
values[valuesById[0] = "RSA"] = 0;
values[valuesById[1] = "Ed25519"] = 1;
values[valuesById[2] = "Secp256k1"] = 2;
return values;
})();
$root.PublicKey = (function() {
/**
* Properties of a PublicKey.
* @exports IPublicKey
* @interface IPublicKey
* @property {KeyType} Type PublicKey Type
* @property {Uint8Array} Data PublicKey Data
*/
/**
* Constructs a new PublicKey.
* @exports PublicKey
* @classdesc Represents a PublicKey.
* @implements IPublicKey
* @constructor
* @param {IPublicKey=} [p] Properties to set
*/
function PublicKey(p) {
if (p)
for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)
if (p[ks[i]] != null)
this[ks[i]] = p[ks[i]];
}
/**
* PublicKey Type.
* @member {KeyType} Type
* @memberof PublicKey
* @instance
*/
PublicKey.prototype.Type = 0;
/**
* PublicKey Data.
* @member {Uint8Array} Data
* @memberof PublicKey
* @instance
*/
PublicKey.prototype.Data = $util.newBuffer([]);
/**
* Encodes the specified PublicKey message. Does not implicitly {@link PublicKey.verify|verify} messages.
* @function encode
* @memberof PublicKey
* @static
* @param {IPublicKey} m PublicKey message or plain object to encode
* @param {$protobuf.Writer} [w] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/
PublicKey.encode = function encode(m, w) {
if (!w)
w = $Writer.create();
w.uint32(8).int32(m.Type);
w.uint32(18).bytes(m.Data);
return w;
};
/**
* Decodes a PublicKey message from the specified reader or buffer.
* @function decode
* @memberof PublicKey
* @static
* @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from
* @param {number} [l] Message length if known beforehand
* @returns {PublicKey} PublicKey
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
PublicKey.decode = function decode(r, l) {
if (!(r instanceof $Reader))
r = $Reader.create(r);
var c = l === undefined ? r.len : r.pos + l, m = new $root.PublicKey();
while (r.pos < c) {
var t = r.uint32();
switch (t >>> 3) {
case 1:
m.Type = r.int32();
break;
case 2:
m.Data = r.bytes();
break;
default:
r.skipType(t & 7);
break;
}
}
if (!m.hasOwnProperty("Type"))
throw $util.ProtocolError("missing required 'Type'", { instance: m });
if (!m.hasOwnProperty("Data"))
throw $util.ProtocolError("missing required 'Data'", { instance: m });
return m;
};
/**
* Creates a PublicKey message from a plain object. Also converts values to their respective internal types.
* @function fromObject
* @memberof PublicKey
* @static
* @param {Object.<string,*>} d Plain object
* @returns {PublicKey} PublicKey
*/
PublicKey.fromObject = function fromObject(d) {
if (d instanceof $root.PublicKey)
return d;
var m = new $root.PublicKey();
switch (d.Type) {
case "RSA":
case 0:
m.Type = 0;
break;
case "Ed25519":
case 1:
m.Type = 1;
break;
case "Secp256k1":
case 2:
m.Type = 2;
break;
}
if (d.Data != null) {
if (typeof d.Data === "string")
$util.base64.decode(d.Data, m.Data = $util.newBuffer($util.base64.length(d.Data)), 0);
else if (d.Data.length)
m.Data = d.Data;
}
return m;
};
/**
* Creates a plain object from a PublicKey message. Also converts values to other types if specified.
* @function toObject
* @memberof PublicKey
* @static
* @param {PublicKey} m PublicKey
* @param {$protobuf.IConversionOptions} [o] Conversion options
* @returns {Object.<string,*>} Plain object
*/
PublicKey.toObject = function toObject(m, o) {
if (!o)
o = {};
var d = {};
if (o.defaults) {
d.Type = o.enums === String ? "RSA" : 0;
if (o.bytes === String)
d.Data = "";
else {
d.Data = [];
if (o.bytes !== Array)
d.Data = $util.newBuffer(d.Data);
}
}
if (m.Type != null && m.hasOwnProperty("Type")) {
d.Type = o.enums === String ? $root.KeyType[m.Type] : m.Type;
}
if (m.Data != null && m.hasOwnProperty("Data")) {
d.Data = o.bytes === String ? $util.base64.encode(m.Data, 0, m.Data.length) : o.bytes === Array ? Array.prototype.slice.call(m.Data) : m.Data;
}
return d;
};
/**
* Converts this PublicKey to JSON.
* @function toJSON
* @memberof PublicKey
* @instance
* @returns {Object.<string,*>} JSON object
*/
PublicKey.prototype.toJSON = function toJSON() {
return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
};
return PublicKey;
})();
$root.PrivateKey = (function() {
/**
* Properties of a PrivateKey.
* @exports IPrivateKey
* @interface IPrivateKey
* @property {KeyType} Type PrivateKey Type
* @property {Uint8Array} Data PrivateKey Data
*/
/**
* Constructs a new PrivateKey.
* @exports PrivateKey
* @classdesc Represents a PrivateKey.
* @implements IPrivateKey
* @constructor
* @param {IPrivateKey=} [p] Properties to set
*/
function PrivateKey(p) {
if (p)
for (var ks = Object.keys(p), i = 0; i < ks.length; ++i)
if (p[ks[i]] != null)
this[ks[i]] = p[ks[i]];
}
/**
* PrivateKey Type.
* @member {KeyType} Type
* @memberof PrivateKey
* @instance
*/
PrivateKey.prototype.Type = 0;
/**
* PrivateKey Data.
* @member {Uint8Array} Data
* @memberof PrivateKey
* @instance
*/
PrivateKey.prototype.Data = $util.newBuffer([]);
/**
* Encodes the specified PrivateKey message. Does not implicitly {@link PrivateKey.verify|verify} messages.
* @function encode
* @memberof PrivateKey
* @static
* @param {IPrivateKey} m PrivateKey message or plain object to encode
* @param {$protobuf.Writer} [w] Writer to encode to
* @returns {$protobuf.Writer} Writer
*/
PrivateKey.encode = function encode(m, w) {
if (!w)
w = $Writer.create();
w.uint32(8).int32(m.Type);
w.uint32(18).bytes(m.Data);
return w;
};
/**
* Decodes a PrivateKey message from the specified reader or buffer.
* @function decode
* @memberof PrivateKey
* @static
* @param {$protobuf.Reader|Uint8Array} r Reader or buffer to decode from
* @param {number} [l] Message length if known beforehand
* @returns {PrivateKey} PrivateKey
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
PrivateKey.decode = function decode(r, l) {
if (!(r instanceof $Reader))
r = $Reader.create(r);
var c = l === undefined ? r.len : r.pos + l, m = new $root.PrivateKey();
while (r.pos < c) {
var t = r.uint32();
switch (t >>> 3) {
case 1:
m.Type = r.int32();
break;
case 2:
m.Data = r.bytes();
break;
default:
r.skipType(t & 7);
break;
}
}
if (!m.hasOwnProperty("Type"))
throw $util.ProtocolError("missing required 'Type'", { instance: m });
if (!m.hasOwnProperty("Data"))
throw $util.ProtocolError("missing required 'Data'", { instance: m });
return m;
};
/**
* Creates a PrivateKey message from a plain object. Also converts values to their respective internal types.
* @function fromObject
* @memberof PrivateKey
* @static
* @param {Object.<string,*>} d Plain object
* @returns {PrivateKey} PrivateKey
*/
PrivateKey.fromObject = function fromObject(d) {
if (d instanceof $root.PrivateKey)
return d;
var m = new $root.PrivateKey();
switch (d.Type) {
case "RSA":
case 0:
m.Type = 0;
break;
case "Ed25519":
case 1:
m.Type = 1;
break;
case "Secp256k1":
case 2:
m.Type = 2;
break;
}
if (d.Data != null) {
if (typeof d.Data === "string")
$util.base64.decode(d.Data, m.Data = $util.newBuffer($util.base64.length(d.Data)), 0);
else if (d.Data.length)
m.Data = d.Data;
}
return m;
};
/**
* Creates a plain object from a PrivateKey message. Also converts values to other types if specified.
* @function toObject
* @memberof PrivateKey
* @static
* @param {PrivateKey} m PrivateKey
* @param {$protobuf.IConversionOptions} [o] Conversion options
* @returns {Object.<string,*>} Plain object
*/
PrivateKey.toObject = function toObject(m, o) {
if (!o)
o = {};
var d = {};
if (o.defaults) {
d.Type = o.enums === String ? "RSA" : 0;
if (o.bytes === String)
d.Data = "";
else {
d.Data = [];
if (o.bytes !== Array)
d.Data = $util.newBuffer(d.Data);
}
}
if (m.Type != null && m.hasOwnProperty("Type")) {
d.Type = o.enums === String ? $root.KeyType[m.Type] : m.Type;
}
if (m.Data != null && m.hasOwnProperty("Data")) {
d.Data = o.bytes === String ? $util.base64.encode(m.Data, 0, m.Data.length) : o.bytes === Array ? Array.prototype.slice.call(m.Data) : m.Data;
}
return d;
};
/**
* Converts this PrivateKey to JSON.
* @function toJSON
* @memberof PrivateKey
* @instance
* @returns {Object.<string,*>} JSON object
*/
PrivateKey.prototype.toJSON = function toJSON() {
return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
};
return PrivateKey;
})();
module.exports = $root;

View File

@@ -1,6 +1,6 @@
'use strict'
syntax = "proto3";
module.exports = `enum KeyType {
enum KeyType {
RSA = 0;
Ed25519 = 1;
Secp256k1 = 2;
@@ -12,4 +12,4 @@ message PublicKey {
message PrivateKey {
required KeyType Type = 1;
required bytes Data = 2;
}`
}

View File

@@ -1,7 +1,6 @@
'use strict'
const sha = require('multihashing-async/src/sha')
const protobuf = require('protons')
const errcode = require('err-code')
const uint8ArrayEquals = require('uint8arrays/equals')
const uint8ArrayToString = require('uint8arrays/to-string')
@@ -11,7 +10,7 @@ require('node-forge/lib/ed25519')
const forge = require('node-forge/lib/forge')
const crypto = require('./rsa')
const pbm = protobuf(require('./keys.proto'))
const pbm = require('./keys')
const exporter = require('./exporter')
class RsaPublicKey {
@@ -31,7 +30,7 @@ class RsaPublicKey {
return pbm.PublicKey.encode({
Type: pbm.KeyType.RSA,
Data: this.marshal()
})
}).finish()
}
encrypt (bytes) {
@@ -83,7 +82,7 @@ class RsaPrivateKey {
return pbm.PrivateKey.encode({
Type: pbm.KeyType.RSA,
Data: this.marshal()
})
}).finish()
}
equals (key) {
@@ -101,7 +100,7 @@ class RsaPrivateKey {
* The public key is a protobuf encoding containing a type and the DER encoding
* of the PKCS SubjectPublicKeyInfo.
*
* @returns {Promise<String>}
* @returns {Promise<string>}
*/
async id () {
const hash = await this.public.hash()

View File

@@ -28,7 +28,7 @@ module.exports = (keysProtobuf, randomBytes, crypto) => {
return keysProtobuf.PublicKey.encode({
Type: keysProtobuf.KeyType.Secp256k1,
Data: this.marshal()
})
}).finish()
}
equals (key) {
@@ -64,7 +64,7 @@ module.exports = (keysProtobuf, randomBytes, crypto) => {
return keysProtobuf.PrivateKey.encode({
Type: keysProtobuf.KeyType.Secp256k1,
Data: this.marshal()
})
}).finish()
}
equals (key) {

View File

@@ -23,7 +23,7 @@ const hashName = {
* @param {string} password
* @param {string} salt
* @param {number} iterations
* @param {number} keySize (in bytes)
* @param {number} keySize - (in bytes)
* @param {string} hash - The hash name ('sha1', 'sha2-512, ...)
* @returns {string} - A new password
*/

View File

@@ -51,7 +51,7 @@ describe('libp2p-crypto', function () {
})
it('generateKeyPairFromSeed', () => {
var seed = crypto.randomBytes(32)
const seed = crypto.randomBytes(32)
return expectErrCode(crypto.keys.generateKeyPairFromSeed('invalid-key-type', seed, 512), 'ERR_UNSUPPORTED_KEY_TYPE')
})

View File

@@ -33,7 +33,7 @@ describe('ed25519', function () {
})
it('generates a valid key from seed', async () => {
var seed = crypto.randomBytes(32)
const seed = crypto.randomBytes(32)
const seededkey = await crypto.keys.generateKeyPairFromSeed('Ed25519', seed, 512)
expect(seededkey).to.be.an.instanceof(ed25519.Ed25519PrivateKey)
const digest = await seededkey.hash()
@@ -82,7 +82,7 @@ describe('ed25519', function () {
it('key id', async () => {
const key = await crypto.keys.unmarshalPrivateKey(fixtures.verify.privateKey)
const id = await key.id()
expect(id).to.eql('QmUawW9qzMrBBiMrWQQMvoatadKZ9F4EwZCAMKnt3STLtz')
expect(id).to.eql('12D3KooWLqLxEfJ9nDdEe8Kh8PFvNPQRYDQBwyL7CMM7HhVd5LsX')
})
it('should export a password encrypted libp2p-key', async () => {