Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@transmute/did-key-secp256k1

Package Overview
Dependencies
Maintainers
3
Versions
58
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@transmute/did-key-secp256k1 - npm Package Compare versions

Comparing version 0.2.1-unstable.20 to 0.2.1-unstable.21

src/__fixtures__/README.md

8

CHANGELOG.md

@@ -6,2 +6,10 @@ # Change Log

## 0.2.1-unstable.21 (2020-09-28)
**Note:** Version bump only for package @transmute/did-key-secp256k1
## 0.2.1-unstable.20 (2020-09-15)

@@ -8,0 +16,0 @@

348

dist/did-key-secp256k1.cjs.development.js

@@ -13,19 +13,5 @@ 'use strict';

var canonicalize = _interopDefault(require('canonicalize'));
var tslib = require('tslib');
var common = require('@transmute/did-key-common');
function _defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
return Constructor;
}
function _extends() {

@@ -223,9 +209,5 @@ _extends = Object.assign || function (target) {

var privateKeyHexFromJwk = function privateKeyHexFromJwk(jwk) {
try {
return Promise.resolve(keyto.from(_extends({}, jwk, {
crv: 'K-256'
}), 'jwk').toString('blk', 'private'));
} catch (e) {
return Promise.reject(e);
}
return keyto.from(_extends({}, jwk, {
crv: 'K-256'
}), 'jwk').toString('blk', 'private');
};

@@ -235,11 +217,7 @@ /** convert jwk to hex encoded public key */

var publicKeyHexFromJwk = function publicKeyHexFromJwk(jwk) {
try {
var uncompressedPublicKey = keyto.from(_extends({}, jwk, {
crv: 'K-256'
}), 'jwk').toString('blk', 'public');
var compressed = secp256k1.publicKeyConvert(Buffer.from(uncompressedPublicKey, 'hex'), true);
return Promise.resolve(Buffer.from(compressed).toString('hex'));
} catch (e) {
return Promise.reject(e);
}
var uncompressedPublicKey = keyto.from(_extends({}, jwk, {
crv: 'K-256'
}), 'jwk').toString('blk', 'public');
var compressed = secp256k1.publicKeyConvert(Buffer.from(uncompressedPublicKey, 'hex'), true);
return Buffer.from(compressed).toString('hex');
};

@@ -249,9 +227,4 @@ /** convert jwk to binary encoded private key */

var privateKeyUInt8ArrayFromJwk = function privateKeyUInt8ArrayFromJwk(jwk) {
try {
return Promise.resolve(privateKeyHexFromJwk(jwk)).then(function (privateKeyHex) {
return Buffer.from(privateKeyHex, 'hex');
});
} catch (e) {
return Promise.reject(e);
}
var privateKeyHex = privateKeyHexFromJwk(jwk);
return Buffer.from(privateKeyHex, 'hex');
};

@@ -261,9 +234,4 @@ /** convert jwk to binary encoded public key */

var publicKeyUInt8ArrayFromJwk = function publicKeyUInt8ArrayFromJwk(jwk) {
try {
return Promise.resolve(publicKeyHexFromJwk(jwk)).then(function (publicKeyHex) {
return Buffer.from(publicKeyHex, 'hex');
});
} catch (e) {
return Promise.reject(e);
}
var publicKeyHex = publicKeyHexFromJwk(jwk);
return Buffer.from(publicKeyHex, 'hex');
};

@@ -281,22 +249,10 @@ /** convert publicKeyHex to base58 */

var privateKeyUInt8ArrayFromPrivateKeyBase58 = function privateKeyUInt8ArrayFromPrivateKeyBase58(privateKeyBase58) {
try {
return Promise.resolve(bs58.decode(privateKeyBase58));
} catch (e) {
return Promise.reject(e);
}
return bs58.decode(privateKeyBase58);
};
var publicKeyUInt8ArrayFromPublicKeyBase58 = function publicKeyUInt8ArrayFromPublicKeyBase58(publicKeyBase58) {
try {
return Promise.resolve(bs58.decode(publicKeyBase58));
} catch (e) {
return Promise.reject(e);
}
return bs58.decode(publicKeyBase58);
};
var publicKeyHexFromPrivateKeyHex = function publicKeyHexFromPrivateKeyHex(privateKeyHex) {
try {
var publicKey = secp256k1.publicKeyCreate(new Uint8Array(Buffer.from(privateKeyHex, 'hex')));
return Promise.resolve(Buffer.from(publicKey).toString('hex'));
} catch (e) {
return Promise.reject(e);
}
var publicKey = secp256k1.publicKeyCreate(new Uint8Array(Buffer.from(privateKeyHex, 'hex')));
return Buffer.from(publicKey).toString('hex');
};

@@ -501,2 +457,4 @@

var Secp256k1KeyPair_1;
var _generate = function _generate(secureRandom) {

@@ -516,3 +474,3 @@ var privateKey;

var Secp256k1KeyPair = /*#__PURE__*/function () {
exports.Secp256k1KeyPair = Secp256k1KeyPair_1 = /*#__PURE__*/function () {
function Secp256k1KeyPair(options) {

@@ -526,9 +484,35 @@ if (options === void 0) {

this.controller = options.controller;
this.privateKeyBase58 = options.privateKeyBase58;
this.publicKeyBase58 = options.publicKeyBase58;
if (options.publicKeyBase58) {
this.publicKeyBuffer = bs58.decode(options.publicKeyBase58);
} else if (options.publicKeyJwk) {
this.publicKeyBuffer = Buffer.from(publicKeyHexFromJwk(options.publicKeyJwk), 'hex');
} else {
throw new Error('Secp256k1KeyPair requires publicKeyBase58 or publicKeyJwk, recieved neither.');
}
if (options.privateKeyBase58) {
this.privateKeyBuffer = bs58.decode(options.privateKeyBase58);
}
if (options.privateKeyJwk) {
this.privateKeyBuffer = Buffer.from(privateKeyHexFromJwk(options.privateKeyJwk), 'hex');
}
if (this.controller && !this.id) {
this.id = this.controller + "#" + this.fingerprint();
}
}
Secp256k1KeyPair.fingerprintFromPublicKey = function fingerprintFromPublicKey(_ref) {
var publicKeyBase58 = _ref.publicKeyBase58;
var pubkeyBytes = bs58.decode(publicKeyBase58);
Secp256k1KeyPair.fingerprintFromPublicKey = function fingerprintFromPublicKey(keypair) {
var pubkeyBytes;
if (keypair.publicKeyBase58) {
pubkeyBytes = bs58.decode(keypair.publicKeyBase58);
}
if (keypair.publicKeyJwk) {
pubkeyBytes = new Uint8Array(Buffer.from(publicKeyHexFromJwk(keypair.publicKeyJwk)));
}
var buffer = new Uint8Array(2 + pubkeyBytes.length); // See https://github.com/multiformats/multicodec/blob/master/table.csv

@@ -561,11 +545,2 @@ // 0xe7 is Secp256k1 public key

if (options.seed) {
var _generate3 = _generate(function () {
return new Uint8Array(options.seed);
});
privateKey = _generate3.privateKey;
publicKey = _generate3.publicKey;
}
if (!privateKey) {

@@ -577,9 +552,9 @@ throw new Error('Cannot generate private key.');

var privateKeyBase58 = privateKeyBase58FromPrivateKeyHex(Buffer.from(privateKey).toString('hex'));
var did = "did:key:" + Secp256k1KeyPair.fingerprintFromPublicKey({
var did = "did:key:" + Secp256k1KeyPair_1.fingerprintFromPublicKey({
publicKeyBase58: publicKeyBase58
});
var keyId = "#" + Secp256k1KeyPair.fingerprintFromPublicKey({
var keyId = "#" + Secp256k1KeyPair_1.fingerprintFromPublicKey({
publicKeyBase58: publicKeyBase58
});
return Promise.resolve(new Secp256k1KeyPair({
return Promise.resolve(new Secp256k1KeyPair_1({
id: keyId,

@@ -601,3 +576,3 @@ controller: did,

function _temp2() {
return new Secp256k1KeyPair(_extends({}, options, {
return new Secp256k1KeyPair_1(_extends({}, options, {
privateKeyBase58: privateKeyBase58,

@@ -660,4 +635,4 @@ publicKeyBase58: publicKeyBase58

Secp256k1KeyPair.fromFingerprint = function fromFingerprint(_ref2) {
var fingerprint = _ref2.fingerprint;
Secp256k1KeyPair.fromFingerprint = function fromFingerprint(_ref) {
var fingerprint = _ref.fingerprint;
// skip leading `z` that indicates base58 encoding

@@ -668,9 +643,9 @@ var buffer = bs58.decode(fingerprint.substr(1)); // https://github.com/multiformats/multicodec/blob/master/table.csv#L77

var publicKeyBase58 = bs58.encode(buffer.slice(2));
var did = "did:key:" + Secp256k1KeyPair.fingerprintFromPublicKey({
var did = "did:key:" + Secp256k1KeyPair_1.fingerprintFromPublicKey({
publicKeyBase58: publicKeyBase58
});
var keyId = "#" + Secp256k1KeyPair.fingerprintFromPublicKey({
var keyId = "#" + Secp256k1KeyPair_1.fingerprintFromPublicKey({
publicKeyBase58: publicKeyBase58
});
return new Secp256k1KeyPair({
return new Secp256k1KeyPair_1({
id: keyId,

@@ -687,26 +662,20 @@ controller: did,

_proto.publicNode = function publicNode() {
return this.toKeyPair(false);
};
_proto.signer = function signer() {
if (!this.privateKeyBase58) {
return {
sign: function sign() {
try {
throw new Error('No private key to sign with.');
} catch (e) {
return Promise.reject(e);
}
}
};
if (!this.privateKeyBuffer) {
throw new Error('No private key to sign with.');
}
var privateKeyBase58 = this.privateKeyBase58;
var privateKeyBuffer = this.privateKeyBuffer;
return {
sign: function sign(_ref3) {
var data = _ref3.data;
sign: function sign(_ref2) {
var data = _ref2.data;
try {
var messageHashUInt8Array = crypto.createHash('sha256').update(data).digest();
return Promise.resolve(privateKeyUInt8ArrayFromPrivateKeyBase58(privateKeyBase58)).then(function (privateKeyUInt8Array) {
var sigObj = secp256k1.ecdsaSign(messageHashUInt8Array, privateKeyUInt8Array);
return sigObj.signature;
});
var sigObj = secp256k1.ecdsaSign(messageHashUInt8Array, new Uint8Array(privateKeyBuffer));
return Promise.resolve(sigObj.signature);
} catch (e) {

@@ -720,33 +689,23 @@ return Promise.reject(e);

_proto.verifier = function verifier() {
if (!this.publicKeyBase58) {
return {
sign: function sign() {
try {
throw new Error('No public key to verify with.');
} catch (e) {
return Promise.reject(e);
}
}
};
if (!this.publicKeyBuffer) {
throw new Error('No public key to verify with.');
}
var publicKeyBase58 = this.publicKeyBase58;
var publicKeyBuffer = this.publicKeyBuffer;
return {
verify: function verify(_ref4) {
var data = _ref4.data,
signature = _ref4.signature;
verify: function verify(_ref3) {
var data = _ref3.data,
signature = _ref3.signature;
try {
var messageHashUInt8Array = crypto.createHash('sha256').update(data).digest();
return Promise.resolve(publicKeyUInt8ArrayFromPublicKeyBase58(publicKeyBase58)).then(function (publicKeyUInt8Array) {
var verified = false;
var verified = false;
try {
verified = secp256k1.ecdsaVerify(signature, messageHashUInt8Array, publicKeyUInt8Array);
} catch (e) {
console.error('An error occurred when verifying signature: ', e);
}
try {
verified = secp256k1.ecdsaVerify(signature, messageHashUInt8Array, new Uint8Array(publicKeyBuffer));
} catch (e) {
console.error('An error occurred when verifying signature: ', e);
}
return verified;
});
return Promise.resolve(verified);
} catch (e) {

@@ -759,11 +718,5 @@ return Promise.reject(e);

_proto.addEncodedPublicKey = function addEncodedPublicKey(publicKeyNode) {
publicKeyNode.publicKeyBase58 = this.publicKeyBase58;
return publicKeyNode;
};
_proto.fingerprint = function fingerprint() {
var publicKeyBase58 = this.publicKeyBase58;
return Secp256k1KeyPair.fingerprintFromPublicKey({
publicKeyBase58: publicKeyBase58
return Secp256k1KeyPair_1.fingerprintFromPublicKey({
publicKeyBase58: bs58.encode(this.publicKeyBuffer)
});

@@ -793,14 +746,4 @@ };

var publicKeyBuffer;
var publicKeyBuffer = this.publicKeyBuffer; // validate the first two multicodec bytes 0xe701
try {
publicKeyBuffer = bs58.decode(this.publicKeyBase58);
} catch (e) {
return {
error: e,
valid: false
};
} // validate the first two multicodec bytes 0xe701
var valid = fingerprintBuffer.slice(0, 2).toString('hex') === 'e701' && publicKeyBuffer.equals(fingerprintBuffer.slice(2));

@@ -820,21 +763,2 @@

_proto.publicNode = function publicNode(_temp11) {
var _ref5 = _temp11 === void 0 ? {} : _temp11,
_ref5$controller = _ref5.controller,
controller = _ref5$controller === void 0 ? this.controller : _ref5$controller;
var publicNode = {
id: this.id,
type: this.type
};
if (controller) {
publicNode.controller = controller;
}
this.addEncodedPublicKey(publicNode); // Subclass-specific
return publicNode;
};
_proto.toJwk = function toJwk(_private) {

@@ -846,6 +770,10 @@ if (_private === void 0) {

if (_private) {
return privateKeyJwkFromPrivateKeyHex(bs58.decode(this.privateKeyBase58).toString('hex'));
if (!this.privateKeyBuffer) {
throw new Error('No private key to export');
}
return privateKeyJwkFromPrivateKeyHex(this.privateKeyBuffer.toString('hex'));
}
return publicKeyJwkFromPublicKeyHex(bs58.decode(this.publicKeyBase58).toString('hex'));
return publicKeyJwkFromPublicKeyHex(this.publicKeyBuffer.toString('hex'));
};

@@ -859,6 +787,6 @@

try {
var _temp14 = function _temp14(_result) {
var _temp13 = function _temp13(_result) {
if (_exit2) return _result;
var _publicKeyHexFromJwk = publicKeyHexFromJwk;
return Promise.resolve(publicKeyJwkFromPublicKeyHex(bs58.decode(_this2.publicKeyBase58).toString('hex'))).then(function (_keyUtils$publicKeyJw) {
return Promise.resolve(publicKeyJwkFromPublicKeyHex(_this2.publicKeyBuffer.toString('hex'))).then(function (_keyUtils$publicKeyJw) {
return _publicKeyHexFromJwk.call(keyUtils, _keyUtils$publicKeyJw);

@@ -872,7 +800,11 @@ });

var _temp15 = function () {
var _temp14 = function () {
if (_private) {
if (!_this2.privateKeyBuffer) {
throw new Error('No private key to export');
}
_exit2 = true;
var _privateKeyHexFromJwk2 = privateKeyHexFromJwk;
return Promise.resolve(privateKeyJwkFromPrivateKeyHex(bs58.decode(_this2.privateKeyBase58).toString('hex'))).then(function (_keyUtils$privateKeyJ) {
return Promise.resolve(privateKeyJwkFromPrivateKeyHex(_this2.privateKeyBuffer.toString('hex'))).then(function (_keyUtils$privateKeyJ) {
return _privateKeyHexFromJwk2.call(keyUtils, _keyUtils$privateKeyJ);

@@ -883,3 +815,3 @@ });

return Promise.resolve(_temp15 && _temp15.then ? _temp15.then(_temp14) : _temp14(_temp15));
return Promise.resolve(_temp14 && _temp14.then ? _temp14.then(_temp13) : _temp13(_temp14));
} catch (e) {

@@ -899,7 +831,7 @@ return Promise.reject(e);

controller: this.controller,
publicKeyBase58: this.publicKeyBase58
publicKeyBase58: bs58.encode(this.publicKeyBuffer)
};
if (exportPrivate) {
kp.privateKeyBase58 = this.privateKeyBase58;
kp.privateKeyBase58 = bs58.encode(this.privateKeyBuffer);
}

@@ -931,74 +863,13 @@

_createClass(Secp256k1KeyPair, [{
key: "publicKey",
get: function get() {
return this.publicKeyBase58;
}
}, {
key: "privateKey",
get: function get() {
return this.privateKeyBase58;
}
}]);
return Secp256k1KeyPair;
}();
var computeKeyId = function computeKeyId(_ref) {
var key = _ref.key;
exports.Secp256k1KeyPair = Secp256k1KeyPair_1 = /*#__PURE__*/tslib.__decorate([/*#__PURE__*/common.types.staticImplements()], exports.Secp256k1KeyPair);
try {
return Promise.resolve("did:key:" + key.fingerprint() + "#" + key.fingerprint());
} catch (e) {
return Promise.reject(e);
}
};
var keyToDidDoc = function keyToDidDoc(secp256k1Key) {
var did = "did:key:" + secp256k1Key.fingerprint();
var keyId = "#" + secp256k1Key.fingerprint();
return {
'@context': ['https://www.w3.org/ns/did/v1', {
'@base': did
}],
id: did,
publicKey: [{
id: keyId,
type: secp256k1Key.type,
controller: did,
publicKeyBase58: secp256k1Key.publicKeyBase58
}],
authentication: [keyId],
assertionMethod: [keyId],
capabilityDelegation: [keyId],
capabilityInvocation: [keyId]
};
};
var get = function get(_temp) {
var _ref2 = _temp === void 0 ? {} : _temp,
did = _ref2.did,
url = _ref2.url;
var resolve = /*#__PURE__*/common.getResolve(exports.Secp256k1KeyPair);
var get = /*#__PURE__*/common.getGet(resolve);
try {
did = did || url;
if (!did) {
throw new TypeError('"did" must be a string.');
}
var fingerprint = did.split('#')[0].split('did:key:').pop();
return Promise.resolve(Secp256k1KeyPair.fromFingerprint({
fingerprint: fingerprint
})).then(function (publicKey) {
var didDoc = keyToDidDoc(publicKey);
return didDoc;
});
} catch (e) {
return Promise.reject(e);
}
};
var driver = {
__proto__: null,
computeKeyId: computeKeyId,
keyToDidDoc: keyToDidDoc,
resolve: resolve,
get: get

@@ -1008,5 +879,4 @@ };

exports.ES256K = ES256K;
exports.Secp256k1KeyPair = Secp256k1KeyPair;
exports.driver = driver;
exports.keyUtils = keyUtils;
//# sourceMappingURL=did-key-secp256k1.cjs.development.js.map

@@ -1,2 +0,2 @@

"use strict";function e(e){return e&&"object"==typeof e&&"default"in e?e.default:e}Object.defineProperty(exports,"__esModule",{value:!0});var r=e(require("@trust/keyto")),t=e(require("base64url")),i=e(require("crypto")),n=e(require("bs58")),o=e(require("secp256k1")),c=e(require("canonicalize"));function u(){return(u=Object.assign||function(e){for(var r=1;r<arguments.length;r++){var t=arguments[r];for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i])}return e}).apply(this,arguments)}function a(e){return(a=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)})(e)}function f(e,r){return(f=Object.setPrototypeOf||function(e,r){return e.__proto__=r,e})(e,r)}function s(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Date.prototype.toString.call(Reflect.construct(Date,[],(function(){}))),!0}catch(e){return!1}}function l(e,r,t){return(l=s()?Reflect.construct:function(e,r,t){var i=[null];i.push.apply(i,r);var n=new(Function.bind.apply(e,i));return t&&f(n,t.prototype),n}).apply(null,arguments)}function p(e){var r="function"==typeof Map?new Map:void 0;return(p=function(e){if(null===e||-1===Function.toString.call(e).indexOf("[native code]"))return e;if("function"!=typeof e)throw new TypeError("Super expression must either be null or a function");if(void 0!==r){if(r.has(e))return r.get(e);r.set(e,t)}function t(){return l(e,arguments,a(this).constructor)}return t.prototype=Object.create(e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),f(t,e)})(e)}var y=function(e){var r=u({},e);delete r.d,delete r.kid,delete r.alg;var n=i.createHash("sha256").update(c(r)).digest();return t.encode(Buffer.from(n))},d=function(e){var t=u({},r.from(e,"blk").toJwk("private"),{crv:"secp256k1"});return u({},t,{kid:y(t)})},v=function(e){var t=e;if(66===e.length){var i=o.publicKeyConvert(Buffer.from(e,"hex"),!1);t=Buffer.from(i).toString("hex")}var n=u({},r.from(t,"blk").toJwk("public"),{crv:"secp256k1"});return u({},n,{kid:y(n)})},h=function(e){try{return Promise.resolve(r.from(u({},e,{crv:"K-256"}),"jwk").toString("blk","private"))}catch(e){return Promise.reject(e)}},m=function(e){try{var t=r.from(u({},e,{crv:"K-256"}),"jwk").toString("blk","public"),i=o.publicKeyConvert(Buffer.from(t,"hex"),!0);return Promise.resolve(Buffer.from(i).toString("hex"))}catch(e){return Promise.reject(e)}},b=function(e){try{return Promise.resolve(h(e)).then((function(e){return Buffer.from(e,"hex")}))}catch(e){return Promise.reject(e)}},K=function(e){try{return Promise.resolve(m(e)).then((function(e){return Buffer.from(e,"hex")}))}catch(e){return Promise.reject(e)}},g=function(e){return n.encode(Buffer.from(e,"hex"))},P=function(e){return n.encode(Buffer.from(e,"hex"))},w=function(e){try{return Promise.resolve(n.decode(e))}catch(e){return Promise.reject(e)}},B=function(e){try{return Promise.resolve(n.decode(e))}catch(e){return Promise.reject(e)}},k={__proto__:null,getKid:y,privateKeyJwkFromPrivateKeyHex:d,publicKeyJwkFromPublicKeyHex:v,privateKeyJwkFromPrivateKeyPem:function(e){var t=u({},r.from(e,"pem").toJwk("private"),{crv:"secp256k1"});return u({},t,{kid:y(t)})},publicKeyJwkFromPublicKeyPem:function(e){var t=u({},r.from(e,"pem").toJwk("public"),{crv:"secp256k1"});return u({},t,{kid:y(t)})},privateKeyHexFromJwk:h,publicKeyHexFromJwk:m,privateKeyUInt8ArrayFromJwk:b,publicKeyUInt8ArrayFromJwk:K,publicKeyBase58FromPublicKeyHex:g,privateKeyBase58FromPrivateKeyHex:P,privateKeyUInt8ArrayFromPrivateKeyBase58:w,publicKeyUInt8ArrayFromPublicKeyBase58:B,publicKeyHexFromPrivateKeyHex:function(e){try{var r=o.publicKeyCreate(new Uint8Array(Buffer.from(e,"hex")));return Promise.resolve(Buffer.from(r).toString("hex"))}catch(e){return Promise.reject(e)}}},x=function(e){var r,t;function i(r){var t;return(t=e.call(this,r)||this).name="JWSVerificationFailed",t}return t=e,(r=i).prototype=Object.create(t.prototype),r.prototype.constructor=r,r.__proto__=t,i}(p(Error)),S={__proto__:null,signDetached:function(e,r,n){void 0===n&&(n={alg:"ES256K",b64:!1,crit:["b64"]});try{return Promise.resolve(b(r)).then((function(r){var c=t.encode(JSON.stringify(n)),u=Buffer.concat([Buffer.from(c+".","utf8"),Buffer.from(e.buffer,e.byteOffset,e.length)]),a=Buffer.from(u),f=i.createHash("sha256").update(a).digest(),s=o.ecdsaSign(f,r);return c+".."+t.encode(Buffer.from(s.signature))}))}catch(e){return Promise.reject(e)}},verifyDetached:function(e,r,n){try{if(-1===e.indexOf(".."))throw new x("not a valid rfc7797 jws.");var c=e.split(".."),u=c[0],a=c[1],f=JSON.parse(t.decode(u));if("ES256K"!==f.alg)throw new Error("JWS alg is not signed with ES256K.");if(!1!==f.b64||!f.crit||!f.crit.length||"b64"!==f.crit[0])throw new Error("JWS Header is not in rfc7797 format (not detached).");return Promise.resolve(K(n)).then((function(e){var n=Buffer.concat([Buffer.from(u+".","utf8"),Buffer.from(r.buffer,r.byteOffset,r.length)]),c=Buffer.from(n),f=i.createHash("sha256").update(c).digest(),s=t.toBuffer(a),l=o.signatureNormalize(s);if(o.ecdsaVerify(l,f,e))return!0;var p={signature:s.toString("hex")};throw new x("ECDSA Verify Failed: "+JSON.stringify(p,null,2))}))}catch(e){return Promise.reject(e)}},sign:function(e,r,n){void 0===n&&(n={alg:"ES256K"});try{return Promise.resolve(b(r)).then((function(r){var c=t.encode(JSON.stringify(n)),u=t.encode(JSON.stringify(e)),a=Buffer.from(c+"."+u),f=i.createHash("sha256").update(a).digest(),s=o.ecdsaSign(f,r);return c+"."+u+"."+t.encode(s.signature)}))}catch(e){return Promise.reject(e)}},verify:function(e,r){try{return Promise.resolve(K(r)).then((function(r){var n=e.split("."),c=n[1],u=n[2],a=Buffer.from(n[0]+"."+c),f=i.createHash("sha256").update(a).digest(),s=t.toBuffer(u),l=o.signatureNormalize(s);if(o.ecdsaVerify(l,f,r))return JSON.parse(t.decode(c));var p={signature:s.toString("hex"),message:f.toString("hex"),publicKey:r.toString("hex")};throw new x("ECDSA Verify Failed: "+JSON.stringify(p,null,2))}))}catch(e){return Promise.reject(e)}},decode:function(e,r){void 0===r&&(r={complete:!1});var i=e.split("."),n=i[1],o=i[2];return r.complete?{header:JSON.parse(t.decode(i[0])),payload:JSON.parse(t.decode(n)),signature:o}:JSON.parse(t.decode(n))}},J=function(e){var r;do{r=e()}while(!o.privateKeyVerify(r));return{publicKey:o.publicKeyCreate(r),privateKey:r}},j=function(){function e(e){void 0===e&&(e={}),this.type="EcdsaSecp256k1VerificationKey2019",this.id=e.id,this.controller=e.controller,this.privateKeyBase58=e.privateKeyBase58,this.publicKeyBase58=e.publicKeyBase58}e.fingerprintFromPublicKey=function(e){var r=n.decode(e.publicKeyBase58),t=new Uint8Array(2+r.length);return t[0]=231,t[1]=1,t.set(r,2),"z"+n.encode(t)},e.generate=function(r){void 0===r&&(r={});try{var t,i;if(r.secureRandom){var n=J(r.secureRandom);t=n.privateKey,i=n.publicKey}if(r.seed){var o=J((function(){return new Uint8Array(r.seed)}));t=o.privateKey,i=o.publicKey}if(!t)throw new Error("Cannot generate private key.");var c=g(Buffer.from(i).toString("hex")),u=P(Buffer.from(t).toString("hex")),a="did:key:"+e.fingerprintFromPublicKey({publicKeyBase58:c}),f="#"+e.fingerprintFromPublicKey({publicKeyBase58:c});return Promise.resolve(new e({id:f,controller:a,publicKeyBase58:c,privateKeyBase58:u}))}catch(e){return Promise.reject(e)}},e.from=function(r){try{var t=function(){function t(){function t(){function t(){return new e(u({},r,{privateKeyBase58:i,publicKeyBase58:n}))}var o=function(){if(r.publicKeyJwk){var e=P;return Promise.resolve(m(r.publicKeyJwk)).then((function(r){n=e.call(k,r)}))}}();return o&&o.then?o.then(t):t()}var o=function(){if(r.privateKeyJwk){var e=P;return Promise.resolve(h(r.privateKeyJwk)).then((function(r){i=e.call(k,r)}))}}();return o&&o.then?o.then(t):t()}var o=function(){if(r.publicKeyHex)return Promise.resolve(g(r.publicKeyHex)).then((function(e){n=e}))}();return o&&o.then?o.then(t):t()},i=r.privateKeyBase58,n=r.publicKeyBase58,o=function(){if(r.privateKeyHex)return Promise.resolve(P(r.privateKeyHex)).then((function(e){i=e}))}();return Promise.resolve(o&&o.then?o.then(t):t())}catch(e){return Promise.reject(e)}},e.fromFingerprint=function(r){var t=r.fingerprint,i=n.decode(t.substr(1));if(231===i[0]&&1===i[1]){var o=n.encode(i.slice(2)),c="did:key:"+e.fingerprintFromPublicKey({publicKeyBase58:o}),u="#"+e.fingerprintFromPublicKey({publicKeyBase58:o});return new e({id:u,controller:c,publicKeyBase58:o})}throw new Error("Unsupported Fingerprint Type: "+t)};var r,t=e.prototype;return t.signer=function(){if(!this.privateKeyBase58)return{sign:function(){try{throw new Error("No private key to sign with.")}catch(e){return Promise.reject(e)}}};var e=this.privateKeyBase58;return{sign:function(r){var t=r.data;try{var n=i.createHash("sha256").update(t).digest();return Promise.resolve(w(e)).then((function(e){return o.ecdsaSign(n,e).signature}))}catch(e){return Promise.reject(e)}}}},t.verifier=function(){if(!this.publicKeyBase58)return{sign:function(){try{throw new Error("No public key to verify with.")}catch(e){return Promise.reject(e)}}};var e=this.publicKeyBase58;return{verify:function(r){var t=r.data,n=r.signature;try{var c=i.createHash("sha256").update(t).digest();return Promise.resolve(B(e)).then((function(e){var r=!1;try{r=o.ecdsaVerify(n,c,e)}catch(e){console.error("An error occurred when verifying signature: ",e)}return r}))}catch(e){return Promise.reject(e)}}}},t.addEncodedPublicKey=function(e){return e.publicKeyBase58=this.publicKeyBase58,e},t.fingerprint=function(){return e.fingerprintFromPublicKey({publicKeyBase58:this.publicKeyBase58})},t.verifyFingerprint=function(e){if("string"!=typeof e||"z"!==e[0])return{error:new Error("`fingerprint` must be a multibase encoded string."),valid:!1};var r,t;try{r=n.decode(e.slice(1))}catch(e){return{error:e,valid:!1}}try{t=n.decode(this.publicKeyBase58)}catch(e){return{error:e,valid:!1}}var i="e701"===r.slice(0,2).toString("hex")&&t.equals(r.slice(2));return i?{valid:i}:{error:new Error("The fingerprint does not match the public key."),valid:!1}},t.publicNode=function(e){var r=(void 0===e?{}:e).controller,t=void 0===r?this.controller:r,i={id:this.id,type:this.type};return t&&(i.controller=t),this.addEncodedPublicKey(i),i},t.toJwk=function(e){return void 0===e&&(e=!1),e?d(n.decode(this.privateKeyBase58).toString("hex")):v(n.decode(this.publicKeyBase58).toString("hex"))},t.toHex=function(e){void 0===e&&(e=!1);try{var r=function(e){if(t)return e;var r=m;return Promise.resolve(v(n.decode(i.publicKeyBase58).toString("hex"))).then((function(e){return r.call(k,e)}))},t=!1,i=this,o=function(){if(e){t=!0;var r=h;return Promise.resolve(d(n.decode(i.privateKeyBase58).toString("hex"))).then((function(e){return r.call(k,e)}))}}();return Promise.resolve(o&&o.then?o.then(r):r(o))}catch(e){return Promise.reject(e)}},t.toKeyPair=function(e){void 0===e&&(e=!1);var r={id:this.id,type:this.type,controller:this.controller,publicKeyBase58:this.publicKeyBase58};return e&&(r.privateKeyBase58=this.privateKeyBase58),r},t.toJsonWebKeyPair=function(e){void 0===e&&(e=!1);var r={id:this.id,type:"JsonWebKey2020",controller:this.controller,publicKeyJwk:this.toJwk()};return delete r.publicKeyJwk.kid,e&&(r.privateKeyJwk=this.toJwk(!0),delete r.privateKeyJwk.kid),r},(r=[{key:"publicKey",get:function(){return this.publicKeyBase58}},{key:"privateKey",get:function(){return this.privateKeyBase58}}])&&function(e,r){for(var t=0;t<r.length;t++){var i=r[t];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}(e.prototype,r),e}(),O=function(e){var r="did:key:"+e.fingerprint(),t="#"+e.fingerprint();return{"@context":["https://www.w3.org/ns/did/v1",{"@base":r}],id:r,publicKey:[{id:t,type:e.type,controller:r,publicKeyBase58:e.publicKeyBase58}],authentication:[t],assertionMethod:[t],capabilityDelegation:[t],capabilityInvocation:[t]}},F={__proto__:null,computeKeyId:function(e){var r=e.key;try{return Promise.resolve("did:key:"+r.fingerprint()+"#"+r.fingerprint())}catch(e){return Promise.reject(e)}},keyToDidDoc:O,get:function(e){var r=void 0===e?{}:e,t=r.did,i=r.url;try{if(!(t=t||i))throw new TypeError('"did" must be a string.');var n=t.split("#")[0].split("did:key:").pop();return Promise.resolve(j.fromFingerprint({fingerprint:n})).then((function(e){return O(e)}))}catch(e){return Promise.reject(e)}}};exports.ES256K=S,exports.Secp256k1KeyPair=j,exports.driver=F,exports.keyUtils=k;
"use strict";function e(e){return e&&"object"==typeof e&&"default"in e?e.default:e}Object.defineProperty(exports,"__esModule",{value:!0});var r=e(require("@trust/keyto")),t=e(require("base64url")),i=e(require("crypto")),n=e(require("bs58")),o=e(require("secp256k1")),u=e(require("canonicalize")),c=require("tslib"),f=require("@transmute/did-key-common");function a(){return(a=Object.assign||function(e){for(var r=1;r<arguments.length;r++){var t=arguments[r];for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i])}return e}).apply(this,arguments)}function s(e){return(s=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)})(e)}function p(e,r){return(p=Object.setPrototypeOf||function(e,r){return e.__proto__=r,e})(e,r)}function l(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Date.prototype.toString.call(Reflect.construct(Date,[],(function(){}))),!0}catch(e){return!1}}function y(e,r,t){return(y=l()?Reflect.construct:function(e,r,t){var i=[null];i.push.apply(i,r);var n=new(Function.bind.apply(e,i));return t&&p(n,t.prototype),n}).apply(null,arguments)}function v(e){var r="function"==typeof Map?new Map:void 0;return(v=function(e){if(null===e||-1===Function.toString.call(e).indexOf("[native code]"))return e;if("function"!=typeof e)throw new TypeError("Super expression must either be null or a function");if(void 0!==r){if(r.has(e))return r.get(e);r.set(e,t)}function t(){return y(e,arguments,s(this).constructor)}return t.prototype=Object.create(e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),p(t,e)})(e)}var h,d=function(e){var r=a({},e);delete r.d,delete r.kid,delete r.alg;var n=i.createHash("sha256").update(u(r)).digest();return t.encode(Buffer.from(n))},K=function(e){var t=a({},r.from(e,"blk").toJwk("private"),{crv:"secp256k1"});return a({},t,{kid:d(t)})},b=function(e){var t=e;if(66===e.length){var i=o.publicKeyConvert(Buffer.from(e,"hex"),!1);t=Buffer.from(i).toString("hex")}var n=a({},r.from(t,"blk").toJwk("public"),{crv:"secp256k1"});return a({},n,{kid:d(n)})},m=function(e){return r.from(a({},e,{crv:"K-256"}),"jwk").toString("blk","private")},g=function(e){var t=r.from(a({},e,{crv:"K-256"}),"jwk").toString("blk","public"),i=o.publicKeyConvert(Buffer.from(t,"hex"),!0);return Buffer.from(i).toString("hex")},w=function(e){var r=m(e);return Buffer.from(r,"hex")},B=function(e){var r=g(e);return Buffer.from(r,"hex")},k=function(e){return n.encode(Buffer.from(e,"hex"))},P=function(e){return n.encode(Buffer.from(e,"hex"))},x={__proto__:null,getKid:d,privateKeyJwkFromPrivateKeyHex:K,publicKeyJwkFromPublicKeyHex:b,privateKeyJwkFromPrivateKeyPem:function(e){var t=a({},r.from(e,"pem").toJwk("private"),{crv:"secp256k1"});return a({},t,{kid:d(t)})},publicKeyJwkFromPublicKeyPem:function(e){var t=a({},r.from(e,"pem").toJwk("public"),{crv:"secp256k1"});return a({},t,{kid:d(t)})},privateKeyHexFromJwk:m,publicKeyHexFromJwk:g,privateKeyUInt8ArrayFromJwk:w,publicKeyUInt8ArrayFromJwk:B,publicKeyBase58FromPublicKeyHex:k,privateKeyBase58FromPrivateKeyHex:P,privateKeyUInt8ArrayFromPrivateKeyBase58:function(e){return n.decode(e)},publicKeyUInt8ArrayFromPublicKeyBase58:function(e){return n.decode(e)},publicKeyHexFromPrivateKeyHex:function(e){var r=o.publicKeyCreate(new Uint8Array(Buffer.from(e,"hex")));return Buffer.from(r).toString("hex")}},S=function(e){var r,t;function i(r){var t;return(t=e.call(this,r)||this).name="JWSVerificationFailed",t}return t=e,(r=i).prototype=Object.create(t.prototype),r.prototype.constructor=r,r.__proto__=t,i}(v(Error)),J={__proto__:null,signDetached:function(e,r,n){void 0===n&&(n={alg:"ES256K",b64:!1,crit:["b64"]});try{return Promise.resolve(w(r)).then((function(r){var u=t.encode(JSON.stringify(n)),c=Buffer.concat([Buffer.from(u+".","utf8"),Buffer.from(e.buffer,e.byteOffset,e.length)]),f=Buffer.from(c),a=i.createHash("sha256").update(f).digest(),s=o.ecdsaSign(a,r);return u+".."+t.encode(Buffer.from(s.signature))}))}catch(e){return Promise.reject(e)}},verifyDetached:function(e,r,n){try{if(-1===e.indexOf(".."))throw new S("not a valid rfc7797 jws.");var u=e.split(".."),c=u[0],f=u[1],a=JSON.parse(t.decode(c));if("ES256K"!==a.alg)throw new Error("JWS alg is not signed with ES256K.");if(!1!==a.b64||!a.crit||!a.crit.length||"b64"!==a.crit[0])throw new Error("JWS Header is not in rfc7797 format (not detached).");return Promise.resolve(B(n)).then((function(e){var n=Buffer.concat([Buffer.from(c+".","utf8"),Buffer.from(r.buffer,r.byteOffset,r.length)]),u=Buffer.from(n),a=i.createHash("sha256").update(u).digest(),s=t.toBuffer(f),p=o.signatureNormalize(s);if(o.ecdsaVerify(p,a,e))return!0;var l={signature:s.toString("hex")};throw new S("ECDSA Verify Failed: "+JSON.stringify(l,null,2))}))}catch(e){return Promise.reject(e)}},sign:function(e,r,n){void 0===n&&(n={alg:"ES256K"});try{return Promise.resolve(w(r)).then((function(r){var u=t.encode(JSON.stringify(n)),c=t.encode(JSON.stringify(e)),f=Buffer.from(u+"."+c),a=i.createHash("sha256").update(f).digest(),s=o.ecdsaSign(a,r);return u+"."+c+"."+t.encode(s.signature)}))}catch(e){return Promise.reject(e)}},verify:function(e,r){try{return Promise.resolve(B(r)).then((function(r){var n=e.split("."),u=n[1],c=n[2],f=Buffer.from(n[0]+"."+u),a=i.createHash("sha256").update(f).digest(),s=t.toBuffer(c),p=o.signatureNormalize(s);if(o.ecdsaVerify(p,a,r))return JSON.parse(t.decode(u));var l={signature:s.toString("hex"),message:a.toString("hex"),publicKey:r.toString("hex")};throw new S("ECDSA Verify Failed: "+JSON.stringify(l,null,2))}))}catch(e){return Promise.reject(e)}},decode:function(e,r){void 0===r&&(r={complete:!1});var i=e.split("."),n=i[1],o=i[2];return r.complete?{header:JSON.parse(t.decode(i[0])),payload:JSON.parse(t.decode(n)),signature:o}:JSON.parse(t.decode(n))}};exports.Secp256k1KeyPair=h=function(){function e(e){if(void 0===e&&(e={}),this.type="EcdsaSecp256k1VerificationKey2019",this.id=e.id,this.controller=e.controller,e.publicKeyBase58)this.publicKeyBuffer=n.decode(e.publicKeyBase58);else{if(!e.publicKeyJwk)throw new Error("Secp256k1KeyPair requires publicKeyBase58 or publicKeyJwk, recieved neither.");this.publicKeyBuffer=Buffer.from(g(e.publicKeyJwk),"hex")}e.privateKeyBase58&&(this.privateKeyBuffer=n.decode(e.privateKeyBase58)),e.privateKeyJwk&&(this.privateKeyBuffer=Buffer.from(m(e.privateKeyJwk),"hex")),this.controller&&!this.id&&(this.id=this.controller+"#"+this.fingerprint())}e.fingerprintFromPublicKey=function(e){var r;e.publicKeyBase58&&(r=n.decode(e.publicKeyBase58)),e.publicKeyJwk&&(r=new Uint8Array(Buffer.from(g(e.publicKeyJwk))));var t=new Uint8Array(2+r.length);return t[0]=231,t[1]=1,t.set(r,2),"z"+n.encode(t)},e.generate=function(e){void 0===e&&(e={});try{var r,t;if(e.secureRandom){var i=function(e){var r;do{r=e()}while(!o.privateKeyVerify(r));return{publicKey:o.publicKeyCreate(r),privateKey:r}}(e.secureRandom);r=i.privateKey,t=i.publicKey}if(!r)throw new Error("Cannot generate private key.");var n=k(Buffer.from(t).toString("hex")),u=P(Buffer.from(r).toString("hex")),c="did:key:"+h.fingerprintFromPublicKey({publicKeyBase58:n}),f="#"+h.fingerprintFromPublicKey({publicKeyBase58:n});return Promise.resolve(new h({id:f,controller:c,publicKeyBase58:n,privateKeyBase58:u}))}catch(e){return Promise.reject(e)}},e.from=function(e){try{var r=function(){function r(){function r(){function r(){return new h(a({},e,{privateKeyBase58:t,publicKeyBase58:i}))}var n=function(){if(e.publicKeyJwk){var r=P;return Promise.resolve(g(e.publicKeyJwk)).then((function(e){i=r.call(x,e)}))}}();return n&&n.then?n.then(r):r()}var n=function(){if(e.privateKeyJwk){var r=P;return Promise.resolve(m(e.privateKeyJwk)).then((function(e){t=r.call(x,e)}))}}();return n&&n.then?n.then(r):r()}var n=function(){if(e.publicKeyHex)return Promise.resolve(k(e.publicKeyHex)).then((function(e){i=e}))}();return n&&n.then?n.then(r):r()},t=e.privateKeyBase58,i=e.publicKeyBase58,n=function(){if(e.privateKeyHex)return Promise.resolve(P(e.privateKeyHex)).then((function(e){t=e}))}();return Promise.resolve(n&&n.then?n.then(r):r())}catch(e){return Promise.reject(e)}},e.fromFingerprint=function(e){var r=e.fingerprint,t=n.decode(r.substr(1));if(231===t[0]&&1===t[1]){var i=n.encode(t.slice(2)),o="did:key:"+h.fingerprintFromPublicKey({publicKeyBase58:i}),u="#"+h.fingerprintFromPublicKey({publicKeyBase58:i});return new h({id:u,controller:o,publicKeyBase58:i})}throw new Error("Unsupported Fingerprint Type: "+r)};var r=e.prototype;return r.publicNode=function(){return this.toKeyPair(!1)},r.signer=function(){if(!this.privateKeyBuffer)throw new Error("No private key to sign with.");var e=this.privateKeyBuffer;return{sign:function(r){var t=r.data;try{var n=i.createHash("sha256").update(t).digest(),u=o.ecdsaSign(n,new Uint8Array(e));return Promise.resolve(u.signature)}catch(e){return Promise.reject(e)}}}},r.verifier=function(){if(!this.publicKeyBuffer)throw new Error("No public key to verify with.");var e=this.publicKeyBuffer;return{verify:function(r){var t=r.data,n=r.signature;try{var u=i.createHash("sha256").update(t).digest(),c=!1;try{c=o.ecdsaVerify(n,u,new Uint8Array(e))}catch(e){console.error("An error occurred when verifying signature: ",e)}return Promise.resolve(c)}catch(e){return Promise.reject(e)}}}},r.fingerprint=function(){return h.fingerprintFromPublicKey({publicKeyBase58:n.encode(this.publicKeyBuffer)})},r.verifyFingerprint=function(e){if("string"!=typeof e||"z"!==e[0])return{error:new Error("`fingerprint` must be a multibase encoded string."),valid:!1};var r;try{r=n.decode(e.slice(1))}catch(e){return{error:e,valid:!1}}var t=this.publicKeyBuffer,i="e701"===r.slice(0,2).toString("hex")&&t.equals(r.slice(2));return i?{valid:i}:{error:new Error("The fingerprint does not match the public key."),valid:!1}},r.toJwk=function(e){if(void 0===e&&(e=!1),e){if(!this.privateKeyBuffer)throw new Error("No private key to export");return K(this.privateKeyBuffer.toString("hex"))}return b(this.publicKeyBuffer.toString("hex"))},r.toHex=function(e){void 0===e&&(e=!1);try{var r=function(e){if(t)return e;var r=g;return Promise.resolve(b(i.publicKeyBuffer.toString("hex"))).then((function(e){return r.call(x,e)}))},t=!1,i=this,n=function(){if(e){if(!i.privateKeyBuffer)throw new Error("No private key to export");t=!0;var r=m;return Promise.resolve(K(i.privateKeyBuffer.toString("hex"))).then((function(e){return r.call(x,e)}))}}();return Promise.resolve(n&&n.then?n.then(r):r(n))}catch(e){return Promise.reject(e)}},r.toKeyPair=function(e){void 0===e&&(e=!1);var r={id:this.id,type:this.type,controller:this.controller,publicKeyBase58:n.encode(this.publicKeyBuffer)};return e&&(r.privateKeyBase58=n.encode(this.privateKeyBuffer)),r},r.toJsonWebKeyPair=function(e){void 0===e&&(e=!1);var r={id:this.id,type:"JsonWebKey2020",controller:this.controller,publicKeyJwk:this.toJwk()};return delete r.publicKeyJwk.kid,e&&(r.privateKeyJwk=this.toJwk(!0),delete r.privateKeyJwk.kid),r},e}(),exports.Secp256k1KeyPair=h=c.__decorate([f.types.staticImplements()],exports.Secp256k1KeyPair);var O=f.getResolve(exports.Secp256k1KeyPair),_={__proto__:null,resolve:O,get:f.getGet(O)};exports.ES256K=J,exports.driver=_,exports.keyUtils=x;
//# sourceMappingURL=did-key-secp256k1.cjs.production.min.js.map

@@ -7,19 +7,5 @@ import keyto from '@trust/keyto';

import canonicalize from 'canonicalize';
import { __decorate } from 'tslib';
import { types, getResolve, getGet } from '@transmute/did-key-common';
function _defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
return Constructor;
}
function _extends() {

@@ -217,9 +203,5 @@ _extends = Object.assign || function (target) {

var privateKeyHexFromJwk = function privateKeyHexFromJwk(jwk) {
try {
return Promise.resolve(keyto.from(_extends({}, jwk, {
crv: 'K-256'
}), 'jwk').toString('blk', 'private'));
} catch (e) {
return Promise.reject(e);
}
return keyto.from(_extends({}, jwk, {
crv: 'K-256'
}), 'jwk').toString('blk', 'private');
};

@@ -229,11 +211,7 @@ /** convert jwk to hex encoded public key */

var publicKeyHexFromJwk = function publicKeyHexFromJwk(jwk) {
try {
var uncompressedPublicKey = keyto.from(_extends({}, jwk, {
crv: 'K-256'
}), 'jwk').toString('blk', 'public');
var compressed = secp256k1.publicKeyConvert(Buffer.from(uncompressedPublicKey, 'hex'), true);
return Promise.resolve(Buffer.from(compressed).toString('hex'));
} catch (e) {
return Promise.reject(e);
}
var uncompressedPublicKey = keyto.from(_extends({}, jwk, {
crv: 'K-256'
}), 'jwk').toString('blk', 'public');
var compressed = secp256k1.publicKeyConvert(Buffer.from(uncompressedPublicKey, 'hex'), true);
return Buffer.from(compressed).toString('hex');
};

@@ -243,9 +221,4 @@ /** convert jwk to binary encoded private key */

var privateKeyUInt8ArrayFromJwk = function privateKeyUInt8ArrayFromJwk(jwk) {
try {
return Promise.resolve(privateKeyHexFromJwk(jwk)).then(function (privateKeyHex) {
return Buffer.from(privateKeyHex, 'hex');
});
} catch (e) {
return Promise.reject(e);
}
var privateKeyHex = privateKeyHexFromJwk(jwk);
return Buffer.from(privateKeyHex, 'hex');
};

@@ -255,9 +228,4 @@ /** convert jwk to binary encoded public key */

var publicKeyUInt8ArrayFromJwk = function publicKeyUInt8ArrayFromJwk(jwk) {
try {
return Promise.resolve(publicKeyHexFromJwk(jwk)).then(function (publicKeyHex) {
return Buffer.from(publicKeyHex, 'hex');
});
} catch (e) {
return Promise.reject(e);
}
var publicKeyHex = publicKeyHexFromJwk(jwk);
return Buffer.from(publicKeyHex, 'hex');
};

@@ -275,22 +243,10 @@ /** convert publicKeyHex to base58 */

var privateKeyUInt8ArrayFromPrivateKeyBase58 = function privateKeyUInt8ArrayFromPrivateKeyBase58(privateKeyBase58) {
try {
return Promise.resolve(bs58.decode(privateKeyBase58));
} catch (e) {
return Promise.reject(e);
}
return bs58.decode(privateKeyBase58);
};
var publicKeyUInt8ArrayFromPublicKeyBase58 = function publicKeyUInt8ArrayFromPublicKeyBase58(publicKeyBase58) {
try {
return Promise.resolve(bs58.decode(publicKeyBase58));
} catch (e) {
return Promise.reject(e);
}
return bs58.decode(publicKeyBase58);
};
var publicKeyHexFromPrivateKeyHex = function publicKeyHexFromPrivateKeyHex(privateKeyHex) {
try {
var publicKey = secp256k1.publicKeyCreate(new Uint8Array(Buffer.from(privateKeyHex, 'hex')));
return Promise.resolve(Buffer.from(publicKey).toString('hex'));
} catch (e) {
return Promise.reject(e);
}
var publicKey = secp256k1.publicKeyCreate(new Uint8Array(Buffer.from(privateKeyHex, 'hex')));
return Buffer.from(publicKey).toString('hex');
};

@@ -495,2 +451,4 @@

var Secp256k1KeyPair_1;
var _generate = function _generate(secureRandom) {

@@ -510,3 +468,3 @@ var privateKey;

var Secp256k1KeyPair = /*#__PURE__*/function () {
var Secp256k1KeyPair = Secp256k1KeyPair_1 = /*#__PURE__*/function () {
function Secp256k1KeyPair(options) {

@@ -520,9 +478,35 @@ if (options === void 0) {

this.controller = options.controller;
this.privateKeyBase58 = options.privateKeyBase58;
this.publicKeyBase58 = options.publicKeyBase58;
if (options.publicKeyBase58) {
this.publicKeyBuffer = bs58.decode(options.publicKeyBase58);
} else if (options.publicKeyJwk) {
this.publicKeyBuffer = Buffer.from(publicKeyHexFromJwk(options.publicKeyJwk), 'hex');
} else {
throw new Error('Secp256k1KeyPair requires publicKeyBase58 or publicKeyJwk, recieved neither.');
}
if (options.privateKeyBase58) {
this.privateKeyBuffer = bs58.decode(options.privateKeyBase58);
}
if (options.privateKeyJwk) {
this.privateKeyBuffer = Buffer.from(privateKeyHexFromJwk(options.privateKeyJwk), 'hex');
}
if (this.controller && !this.id) {
this.id = this.controller + "#" + this.fingerprint();
}
}
Secp256k1KeyPair.fingerprintFromPublicKey = function fingerprintFromPublicKey(_ref) {
var publicKeyBase58 = _ref.publicKeyBase58;
var pubkeyBytes = bs58.decode(publicKeyBase58);
Secp256k1KeyPair.fingerprintFromPublicKey = function fingerprintFromPublicKey(keypair) {
var pubkeyBytes;
if (keypair.publicKeyBase58) {
pubkeyBytes = bs58.decode(keypair.publicKeyBase58);
}
if (keypair.publicKeyJwk) {
pubkeyBytes = new Uint8Array(Buffer.from(publicKeyHexFromJwk(keypair.publicKeyJwk)));
}
var buffer = new Uint8Array(2 + pubkeyBytes.length); // See https://github.com/multiformats/multicodec/blob/master/table.csv

@@ -555,11 +539,2 @@ // 0xe7 is Secp256k1 public key

if (options.seed) {
var _generate3 = _generate(function () {
return new Uint8Array(options.seed);
});
privateKey = _generate3.privateKey;
publicKey = _generate3.publicKey;
}
if (!privateKey) {

@@ -571,9 +546,9 @@ throw new Error('Cannot generate private key.');

var privateKeyBase58 = privateKeyBase58FromPrivateKeyHex(Buffer.from(privateKey).toString('hex'));
var did = "did:key:" + Secp256k1KeyPair.fingerprintFromPublicKey({
var did = "did:key:" + Secp256k1KeyPair_1.fingerprintFromPublicKey({
publicKeyBase58: publicKeyBase58
});
var keyId = "#" + Secp256k1KeyPair.fingerprintFromPublicKey({
var keyId = "#" + Secp256k1KeyPair_1.fingerprintFromPublicKey({
publicKeyBase58: publicKeyBase58
});
return Promise.resolve(new Secp256k1KeyPair({
return Promise.resolve(new Secp256k1KeyPair_1({
id: keyId,

@@ -595,3 +570,3 @@ controller: did,

function _temp2() {
return new Secp256k1KeyPair(_extends({}, options, {
return new Secp256k1KeyPair_1(_extends({}, options, {
privateKeyBase58: privateKeyBase58,

@@ -654,4 +629,4 @@ publicKeyBase58: publicKeyBase58

Secp256k1KeyPair.fromFingerprint = function fromFingerprint(_ref2) {
var fingerprint = _ref2.fingerprint;
Secp256k1KeyPair.fromFingerprint = function fromFingerprint(_ref) {
var fingerprint = _ref.fingerprint;
// skip leading `z` that indicates base58 encoding

@@ -662,9 +637,9 @@ var buffer = bs58.decode(fingerprint.substr(1)); // https://github.com/multiformats/multicodec/blob/master/table.csv#L77

var publicKeyBase58 = bs58.encode(buffer.slice(2));
var did = "did:key:" + Secp256k1KeyPair.fingerprintFromPublicKey({
var did = "did:key:" + Secp256k1KeyPair_1.fingerprintFromPublicKey({
publicKeyBase58: publicKeyBase58
});
var keyId = "#" + Secp256k1KeyPair.fingerprintFromPublicKey({
var keyId = "#" + Secp256k1KeyPair_1.fingerprintFromPublicKey({
publicKeyBase58: publicKeyBase58
});
return new Secp256k1KeyPair({
return new Secp256k1KeyPair_1({
id: keyId,

@@ -681,26 +656,20 @@ controller: did,

_proto.publicNode = function publicNode() {
return this.toKeyPair(false);
};
_proto.signer = function signer() {
if (!this.privateKeyBase58) {
return {
sign: function sign() {
try {
throw new Error('No private key to sign with.');
} catch (e) {
return Promise.reject(e);
}
}
};
if (!this.privateKeyBuffer) {
throw new Error('No private key to sign with.');
}
var privateKeyBase58 = this.privateKeyBase58;
var privateKeyBuffer = this.privateKeyBuffer;
return {
sign: function sign(_ref3) {
var data = _ref3.data;
sign: function sign(_ref2) {
var data = _ref2.data;
try {
var messageHashUInt8Array = crypto.createHash('sha256').update(data).digest();
return Promise.resolve(privateKeyUInt8ArrayFromPrivateKeyBase58(privateKeyBase58)).then(function (privateKeyUInt8Array) {
var sigObj = secp256k1.ecdsaSign(messageHashUInt8Array, privateKeyUInt8Array);
return sigObj.signature;
});
var sigObj = secp256k1.ecdsaSign(messageHashUInt8Array, new Uint8Array(privateKeyBuffer));
return Promise.resolve(sigObj.signature);
} catch (e) {

@@ -714,33 +683,23 @@ return Promise.reject(e);

_proto.verifier = function verifier() {
if (!this.publicKeyBase58) {
return {
sign: function sign() {
try {
throw new Error('No public key to verify with.');
} catch (e) {
return Promise.reject(e);
}
}
};
if (!this.publicKeyBuffer) {
throw new Error('No public key to verify with.');
}
var publicKeyBase58 = this.publicKeyBase58;
var publicKeyBuffer = this.publicKeyBuffer;
return {
verify: function verify(_ref4) {
var data = _ref4.data,
signature = _ref4.signature;
verify: function verify(_ref3) {
var data = _ref3.data,
signature = _ref3.signature;
try {
var messageHashUInt8Array = crypto.createHash('sha256').update(data).digest();
return Promise.resolve(publicKeyUInt8ArrayFromPublicKeyBase58(publicKeyBase58)).then(function (publicKeyUInt8Array) {
var verified = false;
var verified = false;
try {
verified = secp256k1.ecdsaVerify(signature, messageHashUInt8Array, publicKeyUInt8Array);
} catch (e) {
console.error('An error occurred when verifying signature: ', e);
}
try {
verified = secp256k1.ecdsaVerify(signature, messageHashUInt8Array, new Uint8Array(publicKeyBuffer));
} catch (e) {
console.error('An error occurred when verifying signature: ', e);
}
return verified;
});
return Promise.resolve(verified);
} catch (e) {

@@ -753,11 +712,5 @@ return Promise.reject(e);

_proto.addEncodedPublicKey = function addEncodedPublicKey(publicKeyNode) {
publicKeyNode.publicKeyBase58 = this.publicKeyBase58;
return publicKeyNode;
};
_proto.fingerprint = function fingerprint() {
var publicKeyBase58 = this.publicKeyBase58;
return Secp256k1KeyPair.fingerprintFromPublicKey({
publicKeyBase58: publicKeyBase58
return Secp256k1KeyPair_1.fingerprintFromPublicKey({
publicKeyBase58: bs58.encode(this.publicKeyBuffer)
});

@@ -787,14 +740,4 @@ };

var publicKeyBuffer;
var publicKeyBuffer = this.publicKeyBuffer; // validate the first two multicodec bytes 0xe701
try {
publicKeyBuffer = bs58.decode(this.publicKeyBase58);
} catch (e) {
return {
error: e,
valid: false
};
} // validate the first two multicodec bytes 0xe701
var valid = fingerprintBuffer.slice(0, 2).toString('hex') === 'e701' && publicKeyBuffer.equals(fingerprintBuffer.slice(2));

@@ -814,21 +757,2 @@

_proto.publicNode = function publicNode(_temp11) {
var _ref5 = _temp11 === void 0 ? {} : _temp11,
_ref5$controller = _ref5.controller,
controller = _ref5$controller === void 0 ? this.controller : _ref5$controller;
var publicNode = {
id: this.id,
type: this.type
};
if (controller) {
publicNode.controller = controller;
}
this.addEncodedPublicKey(publicNode); // Subclass-specific
return publicNode;
};
_proto.toJwk = function toJwk(_private) {

@@ -840,6 +764,10 @@ if (_private === void 0) {

if (_private) {
return privateKeyJwkFromPrivateKeyHex(bs58.decode(this.privateKeyBase58).toString('hex'));
if (!this.privateKeyBuffer) {
throw new Error('No private key to export');
}
return privateKeyJwkFromPrivateKeyHex(this.privateKeyBuffer.toString('hex'));
}
return publicKeyJwkFromPublicKeyHex(bs58.decode(this.publicKeyBase58).toString('hex'));
return publicKeyJwkFromPublicKeyHex(this.publicKeyBuffer.toString('hex'));
};

@@ -853,6 +781,6 @@

try {
var _temp14 = function _temp14(_result) {
var _temp13 = function _temp13(_result) {
if (_exit2) return _result;
var _publicKeyHexFromJwk = publicKeyHexFromJwk;
return Promise.resolve(publicKeyJwkFromPublicKeyHex(bs58.decode(_this2.publicKeyBase58).toString('hex'))).then(function (_keyUtils$publicKeyJw) {
return Promise.resolve(publicKeyJwkFromPublicKeyHex(_this2.publicKeyBuffer.toString('hex'))).then(function (_keyUtils$publicKeyJw) {
return _publicKeyHexFromJwk.call(keyUtils, _keyUtils$publicKeyJw);

@@ -866,7 +794,11 @@ });

var _temp15 = function () {
var _temp14 = function () {
if (_private) {
if (!_this2.privateKeyBuffer) {
throw new Error('No private key to export');
}
_exit2 = true;
var _privateKeyHexFromJwk2 = privateKeyHexFromJwk;
return Promise.resolve(privateKeyJwkFromPrivateKeyHex(bs58.decode(_this2.privateKeyBase58).toString('hex'))).then(function (_keyUtils$privateKeyJ) {
return Promise.resolve(privateKeyJwkFromPrivateKeyHex(_this2.privateKeyBuffer.toString('hex'))).then(function (_keyUtils$privateKeyJ) {
return _privateKeyHexFromJwk2.call(keyUtils, _keyUtils$privateKeyJ);

@@ -877,3 +809,3 @@ });

return Promise.resolve(_temp15 && _temp15.then ? _temp15.then(_temp14) : _temp14(_temp15));
return Promise.resolve(_temp14 && _temp14.then ? _temp14.then(_temp13) : _temp13(_temp14));
} catch (e) {

@@ -893,7 +825,7 @@ return Promise.reject(e);

controller: this.controller,
publicKeyBase58: this.publicKeyBase58
publicKeyBase58: bs58.encode(this.publicKeyBuffer)
};
if (exportPrivate) {
kp.privateKeyBase58 = this.privateKeyBase58;
kp.privateKeyBase58 = bs58.encode(this.privateKeyBuffer);
}

@@ -925,74 +857,13 @@

_createClass(Secp256k1KeyPair, [{
key: "publicKey",
get: function get() {
return this.publicKeyBase58;
}
}, {
key: "privateKey",
get: function get() {
return this.privateKeyBase58;
}
}]);
return Secp256k1KeyPair;
}();
var computeKeyId = function computeKeyId(_ref) {
var key = _ref.key;
Secp256k1KeyPair = Secp256k1KeyPair_1 = /*#__PURE__*/__decorate([/*#__PURE__*/types.staticImplements()], Secp256k1KeyPair);
try {
return Promise.resolve("did:key:" + key.fingerprint() + "#" + key.fingerprint());
} catch (e) {
return Promise.reject(e);
}
};
var keyToDidDoc = function keyToDidDoc(secp256k1Key) {
var did = "did:key:" + secp256k1Key.fingerprint();
var keyId = "#" + secp256k1Key.fingerprint();
return {
'@context': ['https://www.w3.org/ns/did/v1', {
'@base': did
}],
id: did,
publicKey: [{
id: keyId,
type: secp256k1Key.type,
controller: did,
publicKeyBase58: secp256k1Key.publicKeyBase58
}],
authentication: [keyId],
assertionMethod: [keyId],
capabilityDelegation: [keyId],
capabilityInvocation: [keyId]
};
};
var get = function get(_temp) {
var _ref2 = _temp === void 0 ? {} : _temp,
did = _ref2.did,
url = _ref2.url;
var resolve = /*#__PURE__*/getResolve(Secp256k1KeyPair);
var get = /*#__PURE__*/getGet(resolve);
try {
did = did || url;
if (!did) {
throw new TypeError('"did" must be a string.');
}
var fingerprint = did.split('#')[0].split('did:key:').pop();
return Promise.resolve(Secp256k1KeyPair.fromFingerprint({
fingerprint: fingerprint
})).then(function (publicKey) {
var didDoc = keyToDidDoc(publicKey);
return didDoc;
});
} catch (e) {
return Promise.reject(e);
}
};
var driver = {
__proto__: null,
computeKeyId: computeKeyId,
keyToDidDoc: keyToDidDoc,
resolve: resolve,
get: get

@@ -999,0 +870,0 @@ };

@@ -1,33 +0,8 @@

export declare const computeKeyId: ({ key }: any) => Promise<string>;
export declare const keyToDidDoc: (secp256k1Key: any) => {
'@context': (string | {
'@base': string;
})[];
id: string;
publicKey: {
id: string;
type: any;
controller: string;
publicKeyBase58: any;
}[];
authentication: string[];
assertionMethod: string[];
capabilityDelegation: string[];
capabilityInvocation: string[];
};
export declare const get: ({ did, url }?: any) => Promise<{
'@context': (string | {
'@base': string;
})[];
id: string;
publicKey: {
id: string;
type: any;
controller: string;
publicKeyBase58: any;
}[];
authentication: string[];
assertionMethod: string[];
capabilityDelegation: string[];
capabilityInvocation: string[];
export declare const resolve: (didUri: string, resolutionMetaData?: any) => Promise<{
didDocument: any;
didDocumentMetaData: {
'content-type': any;
};
didResolutionMetaData: {};
}>;
export declare const get: ({ did, url }?: any) => Promise<any>;

@@ -54,9 +54,9 @@ /// <reference types="node" />

/** convert jwk to hex encoded private key */
export declare const privateKeyHexFromJwk: (jwk: ISecp256k1PrivateKeyJwk) => Promise<any>;
export declare const privateKeyHexFromJwk: (jwk: ISecp256k1PrivateKeyJwk) => any;
/** convert jwk to hex encoded public key */
export declare const publicKeyHexFromJwk: (jwk: ISecp256k1PublicKeyJwk) => Promise<string>;
export declare const publicKeyHexFromJwk: (jwk: ISecp256k1PublicKeyJwk) => string;
/** convert jwk to binary encoded private key */
export declare const privateKeyUInt8ArrayFromJwk: (jwk: ISecp256k1PrivateKeyJwk) => Promise<Buffer>;
export declare const privateKeyUInt8ArrayFromJwk: (jwk: ISecp256k1PrivateKeyJwk) => Buffer;
/** convert jwk to binary encoded public key */
export declare const publicKeyUInt8ArrayFromJwk: (jwk: ISecp256k1PublicKeyJwk) => Promise<Buffer>;
export declare const publicKeyUInt8ArrayFromJwk: (jwk: ISecp256k1PublicKeyJwk) => Buffer;
/** convert publicKeyHex to base58 */

@@ -66,4 +66,4 @@ export declare const publicKeyBase58FromPublicKeyHex: (publicKeyHex: string) => any;

export declare const privateKeyBase58FromPrivateKeyHex: (privateKeyHex: string) => any;
export declare const privateKeyUInt8ArrayFromPrivateKeyBase58: (privateKeyBase58: string) => Promise<any>;
export declare const publicKeyUInt8ArrayFromPublicKeyBase58: (publicKeyBase58: string) => Promise<any>;
export declare const publicKeyHexFromPrivateKeyHex: (privateKeyHex: string) => Promise<string>;
export declare const privateKeyUInt8ArrayFromPrivateKeyBase58: (privateKeyBase58: string) => any;
export declare const publicKeyUInt8ArrayFromPublicKeyBase58: (publicKeyBase58: string) => any;
export declare const publicKeyHexFromPrivateKeyHex: (privateKeyHex: string) => string;

@@ -0,1 +1,3 @@

/// <reference types="node" />
import * as common from '@transmute/did-key-common';
export declare class Secp256k1KeyPair {

@@ -5,5 +7,5 @@ id: string;

controller: string;
publicKeyBase58: string;
privateKeyBase58: string;
static fingerprintFromPublicKey({ publicKeyBase58 }: any): string;
publicKeyBuffer: Buffer;
privateKeyBuffer?: Buffer;
static fingerprintFromPublicKey(keypair: common.types.KeyPairJwk | common.types.KeyPairBase58): string;
static generate(options?: any): Promise<Secp256k1KeyPair>;

@@ -13,15 +15,9 @@ static from(options: any): Promise<Secp256k1KeyPair>;

constructor(options?: any);
get publicKey(): string;
get privateKey(): string;
publicNode(): any;
signer(): {
sign(): Promise<never>;
} | {
sign({ data }: any): Promise<any>;
};
verifier(): {
sign(): Promise<never>;
} | {
verify({ data, signature }: any): Promise<boolean>;
};
addEncodedPublicKey(publicKeyNode: any): any;
fingerprint(): string;

@@ -32,8 +28,5 @@ verifyFingerprint(fingerprint: string): {

} | {
valid: any;
valid: true;
error?: undefined;
};
publicNode({ controller }?: {
controller?: string | undefined;
}): any;
toJwk(_private?: boolean): any;

@@ -40,0 +33,0 @@ toHex(_private?: boolean): Promise<any>;

@@ -5,3 +5,3 @@ {

"module": "dist/did-key-secp256k1.esm.js",
"version": "0.2.1-unstable.20",
"version": "0.2.1-unstable.21",
"publishConfig": {

@@ -34,2 +34,3 @@ "access": "public"

"devDependencies": {
"@transmute/did-key-test-vectors": "^0.2.1-unstable.21",
"bitcoin-ts": "1.14.2",

@@ -42,2 +43,3 @@ "jose": "^1.28.0",

"dependencies": {
"@transmute/did-key-common": "^0.2.1-unstable.21",
"@trust/keyto": "^1.0.1",

@@ -49,3 +51,3 @@ "base64url": "^3.0.1",

},
"gitHead": "29d870c1ec1449ed726e0d9b5818a03e7abfc71c"
"gitHead": "28e7977d60b1074bfa8154cf83d9f6f97895e441"
}
import { JWS, JWK } from 'jose';
import * as ES256K from '../ES256K';
import * as fixtures from '../__fixtures__';
import { didCoreConformance } from '@transmute/did-key-test-vectors';
const [example] = didCoreConformance.secp256k1.key;
const { publicKeyJwk, privateKeyJwk } = example.keypair['application/did+json'];
const payload = Buffer.from('hello');

@@ -21,3 +24,3 @@ const header = {

payload,
JWK.asKey(fixtures.privateKeyJwk as any),
JWK.asKey(privateKeyJwk as any),
header

@@ -28,15 +31,11 @@ );

theirJws,
JWK.asKey(fixtures.publicKeyJwk as any),
JWK.asKey(publicKeyJwk as any),
{ crit: ['b64'] }
);
expect(theirVerification).toEqual(payload.toString());
const ourJws = await ES256K.signDetached(
payload,
fixtures.privateKeyJwk,
header
);
const ourJws = await ES256K.signDetached(payload, privateKeyJwk, header);
const ourVerification = await ES256K.verifyDetached(
ourJws,
payload,
fixtures.publicKeyJwk
publicKeyJwk
);

@@ -48,3 +47,3 @@ expect(ourVerification).toEqual(true);

ourJwsForThem,
JWK.asKey(fixtures.publicKeyJwk as any),
JWK.asKey(publicKeyJwk as any),
{ crit: ['b64'] }

@@ -60,3 +59,3 @@ );

payload,
fixtures.publicKeyJwk
publicKeyJwk
);

@@ -63,0 +62,0 @@ expect(ourVerificationOfTheirs).toEqual(true);

import { JWS, JWK } from 'jose';
import * as ES256K from '../ES256K';
import * as fixtures from '../__fixtures__';
import { didCoreConformance } from '@transmute/did-key-test-vectors';
const [example] = didCoreConformance.secp256k1.key;
const payload = { hello: 'world' };
const { publicKeyJwk, privateKeyJwk } = example.keypair['application/did+json'];
it('interop', async () => {

@@ -14,13 +17,10 @@ let count = 0;

while (count < limit) {
const theirJws = await JWS.sign(
payload,
JWK.asKey(fixtures.privateKeyJwk as any)
);
const theirJws = await JWS.sign(payload, JWK.asKey(privateKeyJwk as any));
const theirVerification = await JWS.verify(
theirJws,
JWK.asKey(fixtures.publicKeyJwk as any)
JWK.asKey(publicKeyJwk as any)
);
expect(theirVerification).toEqual(payload);
const ourJws = await ES256K.sign(payload, fixtures.privateKeyJwk);
const ourVerification = await ES256K.verify(ourJws, fixtures.publicKeyJwk);
const ourJws = await ES256K.sign(payload, privateKeyJwk);
const ourVerification = await ES256K.verify(ourJws, publicKeyJwk);
expect(ourVerification).toEqual(payload);

@@ -30,3 +30,3 @@

ourJws,
JWK.asKey(fixtures.publicKeyJwk as any)
JWK.asKey(publicKeyJwk as any)
);

@@ -38,3 +38,3 @@ expect(theirVerificationOfOurs).toEqual(payload);

theirJws,
fixtures.publicKeyJwk
publicKeyJwk
);

@@ -41,0 +41,0 @@ expect(ourVerificationOfTheirs).toEqual(payload);

@@ -1,25 +0,34 @@

import { Secp256k1KeyPair } from './Secp256k1KeyPair';
import { seed, didDocument } from './__fixtures__';
import { didCoreConformance } from '@transmute/did-key-test-vectors';
import { keyToDidDoc, get } from './driver';
import { get, resolve } from './driver';
describe('driver', () => {
describe('keyToDidDoc', () => {
it('convert a secp256k1 key to a did document', async () => {
let key: any = await Secp256k1KeyPair.generate({
seed: Buffer.from(seed, 'hex'),
});
const _didDocument = keyToDidDoc(key);
expect(_didDocument).toEqual(didDocument);
});
const [example] = didCoreConformance.secp256k1.key;
it('get interface defaults to application/did+ld+json', async () => {
let _didDocument: any = await get({
did: example.resolution['application/did+ld+json'].didDocument.id,
});
expect(_didDocument).toEqual(
example.resolution['application/did+ld+json'].didDocument
);
});
describe('get', () => {
it('resolve a key from id', async () => {
let _didDocument: any = await get({
did: didDocument.id,
});
expect(_didDocument).toEqual(didDocument);
let representations = [
{
keyType: 'JsonWebKey2020',
contentType: 'application/did+json',
},
{
keyType: 'EcdsaSecp256k1VerificationKey2019',
contentType: 'application/did+ld+json',
},
];
representations.forEach(rep => {
let { id } = example.resolution[rep.contentType].didDocument;
it(`resolve supports ${rep.contentType}`, async () => {
let resolutionResponse: any = await resolve(id, {
accept: rep.contentType,
});
expect(resolutionResponse).toEqual(example.resolution[rep.contentType]);
});
});
import { Secp256k1KeyPair } from './Secp256k1KeyPair';
export const computeKeyId = async ({ key }: any) => {
return `did:key:${key.fingerprint()}#${key.fingerprint()}`;
};
import { getResolve, getGet } from '@transmute/did-key-common';
export const keyToDidDoc = (secp256k1Key: any) => {
const did = `did:key:${secp256k1Key.fingerprint()}`;
const keyId = `#${secp256k1Key.fingerprint()}`;
return {
'@context': [
'https://www.w3.org/ns/did/v1',
{
'@base': did,
},
],
id: did,
publicKey: [
{
id: keyId,
type: secp256k1Key.type,
controller: did,
publicKeyBase58: secp256k1Key.publicKeyBase58,
},
],
authentication: [keyId],
assertionMethod: [keyId],
capabilityDelegation: [keyId],
capabilityInvocation: [keyId],
};
};
export const get = async ({ did, url }: any = {}) => {
did = did || url;
if (!did) {
throw new TypeError('"did" must be a string.');
}
const fingerprint = did
.split('#')[0]
.split('did:key:')
.pop();
const publicKey = await Secp256k1KeyPair.fromFingerprint({ fingerprint });
const didDoc = keyToDidDoc(publicKey);
return didDoc;
};
export const resolve = getResolve(Secp256k1KeyPair);
export const get = getGet(resolve);

@@ -0,47 +1,75 @@

import {
didCoreConformance,
getKeyResolver,
} from '@transmute/did-key-test-vectors';
import * as ES256K from './ES256K';
import * as fixtures from './__fixtures__';
import jose from 'jose';
const payload = {
hello: true,
};
const [example] = didCoreConformance.secp256k1.jws;
describe('ES256K', () => {
describe('sign', () => {
it('should produce a ES256K', async () => {
const signature = await ES256K.sign(payload, fixtures.privateKeyJwk);
expect(signature).toBe(
'eyJhbGciOiJFUzI1NksifQ.eyJoZWxsbyI6dHJ1ZX0.NdmDdVLxgeu-IcmzrE4RsZpB-245i_7qu5nRxK6CUepunNiTuA33EG2jeqU1yaAPbMRgdwgShPZGmUNyYF4Rgg'
);
});
});
const keyResolver = getKeyResolver(
didCoreConformance.secp256k1.key,
'application/did+json'
);
describe('verify', () => {
it('should return the decoded payload for a valid ES256K', async () => {
const jws =
'eyJhbGciOiJFUzI1NksifQ.eyJoZWxsbyI6dHJ1ZX0.NdmDdVLxgeu-IcmzrE4RsZpB-245i_7qu5nRxK6CUepunNiTuA33EG2jeqU1yaAPbMRgdwgShPZGmUNyYF4Rgg';
const verified = await ES256K.verify(jws, fixtures.publicKeyJwk);
expect(verified).toEqual(payload);
});
});
const keypair = keyResolver({ id: example.id });
describe('decode', () => {
it('should return the decoded payload for a ES256K', async () => {
const jws =
'eyJhbGciOiJFUzI1NksifQ.eyJoZWxsbyI6dHJ1ZX0.NdmDdVLxgeu-IcmzrE4RsZpB-245i_7qu5nRxK6CUepunNiTuA33EG2jeqU1yaAPbMRgdwgShPZGmUNyYF4Rgg';
const decoded = await ES256K.decode(jws);
expect(decoded).toEqual(payload);
});
it('compact sign / verify ', async () => {
const header = {
alg: 'ES256K',
};
const _jws = await ES256K.sign(
example.payload,
keypair.privateKeyJwk,
header
);
const _jws2 = await jose.JWS.sign(
example.payload,
jose.JWK.asKey(keypair.privateKeyJwk as any),
header
);
// JOSE ES256K does not produce stable signatures.
expect(_jws).not.toBe(_jws2);
expect(_jws).toBe(example.jws.compact);
const _verified = await ES256K.verify(
example.jws.compact,
keypair.publicKeyJwk
);
const _verified2 = jose.JWS.verify(
example.jws.compact,
jose.JWK.asKey(keypair.publicKeyJwk as any)
);
expect(_verified2).toEqual(example.payload);
expect(_verified).toEqual(example.payload);
});
it('should return the decoded complete payload for a ES256K', async () => {
const jws =
'eyJhbGciOiJFUzI1NksifQ.eyJoZWxsbyI6dHJ1ZX0.NdmDdVLxgeu-IcmzrE4RsZpB-245i_7qu5nRxK6CUepunNiTuA33EG2jeqU1yaAPbMRgdwgShPZGmUNyYF4Rgg';
const decoded = await ES256K.decode(jws, { complete: true });
expect(decoded.payload).toEqual(payload);
expect(decoded.header).toEqual({ alg: 'ES256K' });
expect(decoded.signature).toBe(
'NdmDdVLxgeu-IcmzrE4RsZpB-245i_7qu5nRxK6CUepunNiTuA33EG2jeqU1yaAPbMRgdwgShPZGmUNyYF4Rgg'
);
});
});
it('detached sign / verify', async () => {
const header = {
alg: 'ES256K',
b64: false,
crit: ['b64'],
};
// account for non ascii characters
const payload = Buffer.from(new Uint8Array([127, 128]));
const _jws = await ES256K.signDetached(
payload,
keypair.privateKeyJwk,
header
);
const flat = await jose.JWS.sign.flattened(
payload,
jose.JWK.asKey(keypair.privateKeyJwk as any),
header
);
// JOSE ES256K does not produce stable signatures.
expect(_jws).not.toBe(`${flat.protected}..${flat.signature}`);
const _verified = await ES256K.verifyDetached(
_jws,
payload,
keypair.publicKeyJwk
);
expect(_verified).toBe(true);
});
import * as keyUtils from './keyUtils';
import bs58 from 'bs58';
import { didCoreConformance } from '@transmute/did-key-test-vectors';
import * as fixtures from './__fixtures__';
const [example] = didCoreConformance.secp256k1.key;
describe('keyUtils', () => {
describe('getKid', () => {
it('should convert a jwk to a kid', async () => {
const kid = keyUtils.getKid(fixtures.rsaKeyExample as any);
expect(kid).toBe('NzbLsXh8uDCcd-6MNwXF4W_7noWXFZAfHkxZsRGC9Xs');
});
describe('getKid', () => {
it('should convert a jwk to a kid', async () => {
const kid = keyUtils.getKid(
example.keypair['application/did+json'].publicKeyJwk
);
expect(kid).toBeDefined();
});
});
describe('privateKeyJwkFromPrivateKeyHex', () => {
it('should convert a hex encoded keyUtils to a Jwk', async () => {
const _jwk = await keyUtils.privateKeyJwkFromPrivateKeyHex(
fixtures.privateKeyHex
);
expect(_jwk).toEqual(fixtures.privateKeyJwk);
});
describe('privateKeyJwkFromPrivateKeyHex', () => {
it('should convert a hex encoded keyUtils to a Jwk', async () => {
const _jwk = await keyUtils.privateKeyJwkFromPrivateKeyHex(
bs58
.decode(example.keypair['application/did+ld+json'].privateKeyBase58)
.toString('hex')
);
delete _jwk.kid;
expect(_jwk).toEqual(example.keypair['application/did+json'].privateKeyJwk);
});
});
describe('publicKeyJwkFromPublicKeyHex', () => {
it('should convert a hex encoded keyUtils to a Jwk', async () => {
const _jwk = await keyUtils.publicKeyJwkFromPublicKeyHex(
fixtures.publicKeyHex
);
expect(_jwk).toEqual(fixtures.publicKeyJwk);
});
describe('publicKeyJwkFromPublicKeyHex', () => {
it('should convert a hex encoded keyUtils to a Jwk', async () => {
const _jwk = await keyUtils.publicKeyJwkFromPublicKeyHex(
bs58
.decode(example.keypair['application/did+ld+json'].publicKeyBase58)
.toString('hex')
);
delete _jwk.kid;
expect(_jwk).toEqual(example.keypair['application/did+json'].publicKeyJwk);
});
});
describe('privateKeyJwkFromPrivateKeyPem', () => {
it('should convert a hex encoded keyUtils to a Jwk', async () => {
const _jwk = await keyUtils.privateKeyJwkFromPrivateKeyPem(
fixtures.privateKeyPem
);
expect(_jwk).toEqual(fixtures.privateKeyJwk);
});
describe('privateKeyHexFromJwk', () => {
it('should convert a hex encoded keyUtils to a Jwk', async () => {
const _privateKeyHex = await keyUtils.privateKeyHexFromJwk(
example.keypair['application/did+json'].privateKeyJwk
);
expect(_privateKeyHex).toBe(
bs58
.decode(example.keypair['application/did+ld+json'].privateKeyBase58)
.toString('hex')
);
});
});
describe('publicKeyJwkFromPublicKeyPem', () => {
it('should convert a hex encoded keyUtils to a Jwk', async () => {
const _jwk = await keyUtils.publicKeyJwkFromPublicKeyPem(
fixtures.privateKeyPem
);
expect(_jwk).toEqual(fixtures.publicKeyJwk);
});
describe('publicKeyHexFromJwk', () => {
it('should convert a jwk to compressed hex', async () => {
const _publicKeyHex = await keyUtils.publicKeyHexFromJwk(
example.keypair['application/did+json'].publicKeyJwk
);
expect(_publicKeyHex).toBe(
bs58
.decode(example.keypair['application/did+ld+json'].publicKeyBase58)
.toString('hex')
);
});
describe('privateKeyHexFromJwk', () => {
it('should convert a hex encoded keyUtils to a Jwk', async () => {
const _privateKeyHex = await keyUtils.privateKeyHexFromJwk(
fixtures.privateKeyJwk
);
expect(_privateKeyHex).toBe(fixtures.privateKeyHex);
});
});
describe('publicKeyHexFromJwk', () => {
it('should convert a jwk to compressed hex', async () => {
const _publicKeyHex = await keyUtils.publicKeyHexFromJwk(
fixtures.publicKeyJwk
);
expect(_publicKeyHex).toBe(fixtures.publicKeyHex);
});
});
describe('privateKeyUInt8ArrayFromJwk', () => {
it('should convert a jwk to UInt8Array', async () => {
const _privateKeyUInt8Array = await keyUtils.privateKeyUInt8ArrayFromJwk(
fixtures.privateKeyJwk
);
expect(Buffer.from(_privateKeyUInt8Array).toString('hex')).toBe(
fixtures.privateKeyHex
);
});
});
describe('publicKeyUInt8ArrayFromJwk', () => {
it('should convert a jwk to UInt8Array', async () => {
const _publicKeyUInt8Array = await keyUtils.publicKeyUInt8ArrayFromJwk(
fixtures.publicKeyJwk
);
expect(Buffer.from(_publicKeyUInt8Array).toString('hex')).toBe(
fixtures.publicKeyHex
);
});
});
describe('publicKeyBase58FromPublicKeyHex', () => {
it('should convert a jwk to base58', async () => {
const _publicKeyBase58 = await keyUtils.publicKeyBase58FromPublicKeyHex(
fixtures.publicKeyHex
);
expect(_publicKeyBase58).toBe(fixtures.publicKeyBase58);
});
});
describe('privateKeyBase58FromPrivateKeyHex', () => {
it('should convert a jwk to base58', async () => {
const _privateKeyBase58 = await keyUtils.privateKeyBase58FromPrivateKeyHex(
fixtures.privateKeyHex
);
expect(_privateKeyBase58).toBe(fixtures.privateKeyBase58);
});
});
describe('publicKeyHexFromPrivateKeyHex', () => {
it('should get public key from private key', async () => {
const _publicKeyHex = await keyUtils.publicKeyHexFromPrivateKeyHex(
fixtures.privateKeyHex
);
expect(_publicKeyHex).toBe(fixtures.publicKeyHex);
});
});
});

@@ -144,3 +144,3 @@ import keyto from '@trust/keyto';

/** convert jwk to hex encoded private key */
export const privateKeyHexFromJwk = async (jwk: ISecp256k1PrivateKeyJwk) =>
export const privateKeyHexFromJwk = (jwk: ISecp256k1PrivateKeyJwk) =>
keyto

@@ -157,3 +157,3 @@ .from(

/** convert jwk to hex encoded public key */
export const publicKeyHexFromJwk = async (jwk: ISecp256k1PublicKeyJwk) => {
export const publicKeyHexFromJwk = (jwk: ISecp256k1PublicKeyJwk) => {
const uncompressedPublicKey = keyto

@@ -177,6 +177,4 @@ .from(

/** convert jwk to binary encoded private key */
export const privateKeyUInt8ArrayFromJwk = async (
jwk: ISecp256k1PrivateKeyJwk
) => {
const privateKeyHex = await privateKeyHexFromJwk(jwk);
export const privateKeyUInt8ArrayFromJwk = (jwk: ISecp256k1PrivateKeyJwk) => {
const privateKeyHex = privateKeyHexFromJwk(jwk);
return Buffer.from(privateKeyHex, 'hex');

@@ -186,6 +184,4 @@ };

/** convert jwk to binary encoded public key */
export const publicKeyUInt8ArrayFromJwk = async (
jwk: ISecp256k1PublicKeyJwk
) => {
const publicKeyHex = await publicKeyHexFromJwk(jwk);
export const publicKeyUInt8ArrayFromJwk = (jwk: ISecp256k1PublicKeyJwk) => {
const publicKeyHex = publicKeyHexFromJwk(jwk);
return Buffer.from(publicKeyHex, 'hex');

@@ -204,3 +200,3 @@ };

export const privateKeyUInt8ArrayFromPrivateKeyBase58 = async (
export const privateKeyUInt8ArrayFromPrivateKeyBase58 = (
privateKeyBase58: string

@@ -211,3 +207,3 @@ ) => {

export const publicKeyUInt8ArrayFromPublicKeyBase58 = async (
export const publicKeyUInt8ArrayFromPublicKeyBase58 = (
publicKeyBase58: string

@@ -218,3 +214,3 @@ ) => {

export const publicKeyHexFromPrivateKeyHex = async (privateKeyHex: string) => {
export const publicKeyHexFromPrivateKeyHex = (privateKeyHex: string) => {
const publicKey = secp256k1.publicKeyCreate(

@@ -221,0 +217,0 @@ new Uint8Array(Buffer.from(privateKeyHex, 'hex'))

import crypto from 'crypto';
import { Secp256k1KeyPair } from './Secp256k1KeyPair';
import * as fixtures from './__fixtures__';
import bs58 from 'bs58';
import { didCoreConformance } from '@transmute/did-key-test-vectors';
const [example] = didCoreConformance.secp256k1.key;
describe('generate', () => {
it('from random seed', async () => {
let key: any = await Secp256k1KeyPair.generate({
let key = await Secp256k1KeyPair.generate({
secureRandom: () => {

@@ -17,6 +21,10 @@ return crypto.randomBytes(32);

it('from chosen seed', async () => {
let key: any = await Secp256k1KeyPair.generate({
seed: Buffer.from(fixtures.seed, 'hex'),
let key = await Secp256k1KeyPair.generate({
secureRandom: () => {
return Buffer.from(example.seed, 'hex');
},
});
expect(key).toEqual(fixtures.secp256k1_key_base58btc);
expect(key.toJsonWebKeyPair(true)).toEqual(
example.keypair['application/did+json']
);
});

@@ -27,21 +35,16 @@ });

it('from base58', async () => {
let key: any = await Secp256k1KeyPair.from(
fixtures.secp256k1_key_base58btc
let key = await Secp256k1KeyPair.from(
example.keypair['application/did+ld+json']
);
expect(key.id).toBe(fixtures.secp256k1_key_base58btc.id);
expect(key.toJsonWebKeyPair(true)).toEqual(
example.keypair['application/did+json']
);
});
it('from jwk', async () => {
let key: any = await Secp256k1KeyPair.from(fixtures.secp256k1_key_jwk);
expect('#' + key.fingerprint()).toBe(fixtures.secp256k1_key_base58btc.id);
expect(key.publicKey).toBe(
fixtures.secp256k1_key_base58btc.publicKeyBase58
let key = await Secp256k1KeyPair.from(
example.keypair['application/did+json']
);
});
it('from hex', async () => {
let key: any = await Secp256k1KeyPair.from(fixtures.secp256k1_key_hex);
expect('#' + key.fingerprint()).toBe(fixtures.secp256k1_key_base58btc.id);
expect(key.publicKey).toBe(
fixtures.secp256k1_key_base58btc.publicKeyBase58
expect(key.toJsonWebKeyPair(true)).toEqual(
example.keypair['application/did+json']
);

@@ -53,9 +56,9 @@ });

it('public key from fingerprint', async () => {
let key: any = await Secp256k1KeyPair.fromFingerprint({
fingerprint: fixtures.secp256k1_key_base58btc.id.split('#').pop(),
let key = await Secp256k1KeyPair.fromFingerprint({
fingerprint: example.keypair['application/did+ld+json'].id
.split('#')
.pop(),
});
expect(key.id).toBe('#' + key.fingerprint());
expect(key.publicKey).toBe(
fixtures.secp256k1_key_base58btc.publicKeyBase58
);
expect(key.publicKeyBuffer).toBeDefined();
});

@@ -66,4 +69,6 @@ });

it('can calculate fingerprint', async () => {
let key: any = await Secp256k1KeyPair.generate({
seed: Buffer.from(fixtures.seed, 'hex'),
let key = await Secp256k1KeyPair.generate({
secureRandom: () => {
return Buffer.from(example.seed, 'hex');
},
});

@@ -76,4 +81,6 @@ expect(key.id).toBe('#' + key.fingerprint());

it('can verifyFingerprint', async () => {
let key: any = await Secp256k1KeyPair.generate({
seed: Buffer.from(fixtures.seed, 'hex'),
let key = await Secp256k1KeyPair.generate({
secureRandom: () => {
return Buffer.from(example.seed, 'hex');
},
});

@@ -84,22 +91,16 @@ expect(key.verifyFingerprint(key.fingerprint())).toEqual({ valid: true });

describe('sign', () => {
it('can sign', async () => {
let key: any = await Secp256k1KeyPair.generate({
seed: Buffer.from(fixtures.seed, 'hex'),
describe('sign / verify', () => {
it('can sign / verify', async () => {
let key = await Secp256k1KeyPair.generate({
secureRandom: () => {
return Buffer.from(example.seed, 'hex');
},
});
const message = Buffer.from('hello');
const signer = key.signer();
const _signature = await signer.sign({ data: fixtures.message });
expect(Buffer.from(_signature).toString('hex')).toBe(fixtures.signature);
});
});
describe('verify', () => {
it('can verify', async () => {
let key: any = await Secp256k1KeyPair.generate({
seed: Buffer.from(fixtures.seed, 'hex'),
});
const signature = await signer.sign({ data: message });
const verifier = key.verifier();
const _verified = await verifier.verify({
data: fixtures.message,
signature: Buffer.from(fixtures.signature, 'hex'),
data: message,
signature,
});

@@ -112,10 +113,14 @@ expect(_verified).toBe(true);

it('can convert to Jwk', async () => {
let key: any = await Secp256k1KeyPair.generate({
seed: Buffer.from(fixtures.seed, 'hex'),
let key = await Secp256k1KeyPair.generate({
secureRandom: () => {
return Buffer.from(example.seed, 'hex');
},
});
let _jwk = await key.toJwk();
expect(_jwk).toEqual(fixtures.secp256k1_key_jwk.publicKeyJwk);
delete _jwk.kid;
expect(_jwk).toEqual(example.keypair['application/did+json'].publicKeyJwk);
_jwk = await key.toJwk(true);
expect(_jwk).toEqual(fixtures.secp256k1_key_jwk.privateKeyJwk);
delete _jwk.kid;
expect(_jwk).toEqual(example.keypair['application/did+json'].privateKeyJwk);
});

@@ -126,9 +131,15 @@ });

it('can convert to hex', async () => {
let key: any = await Secp256k1KeyPair.generate({
seed: Buffer.from(fixtures.seed, 'hex'),
let key = await Secp256k1KeyPair.generate({
secureRandom: () => {
return Buffer.from(example.seed, 'hex');
},
});
let _publicKeyHex = await key.toHex();
expect(_publicKeyHex).toBe(fixtures.secp256k1_key_hex.publicKeyHex);
expect(Buffer.from(_publicKeyHex, 'hex')).toEqual(
bs58.decode(example.keypair['application/did+ld+json'].publicKeyBase58)
);
let _privateKeyHex = await key.toHex(true);
expect(_privateKeyHex).toBe(fixtures.secp256k1_key_hex.privateKeyHex);
expect(Buffer.from(_privateKeyHex, 'hex')).toEqual(
bs58.decode(example.keypair['application/did+ld+json'].privateKeyBase58)
);
});

@@ -139,26 +150,10 @@ });

it('can convert to to json web key 2020', async () => {
let key: any = await Secp256k1KeyPair.generate({
seed: Buffer.from(fixtures.seed, 'hex'),
let key = await Secp256k1KeyPair.generate({
secureRandom: () => {
return Buffer.from(example.seed, 'hex');
},
});
let _key1 = await key.toJsonWebKeyPair(true);
expect(_key1).toEqual({
id: '#zQ3shP2mWsZYWgvgM11nenXRTx9L1yiJKmkf9dfX7NaMKb1pX',
type: 'JsonWebKey2020',
controller: 'did:key:zQ3shP2mWsZYWgvgM11nenXRTx9L1yiJKmkf9dfX7NaMKb1pX',
publicKeyJwk: {
kty: 'EC',
crv: 'secp256k1',
x: 'GBMxavme-AfIVDKqI6WBJ4V5wZItsxJ9muhxPByllHQ',
y: 'SChlfVBhTXG_sRGc9ZdFeCYzI3Kbph3ivE12OFVk4jo',
},
privateKeyJwk: {
kty: 'EC',
crv: 'secp256k1',
d: 'm5N7gTItgWz6udWjuqzJsqX-vksUnxJrNjD5OilScBc',
x: 'GBMxavme-AfIVDKqI6WBJ4V5wZItsxJ9muhxPByllHQ',
y: 'SChlfVBhTXG_sRGc9ZdFeCYzI3Kbph3ivE12OFVk4jo',
},
});
expect(_key1).toEqual(example.keypair['application/did+json']);
});
});

@@ -7,2 +7,4 @@ import crypto from 'crypto';

import * as common from '@transmute/did-key-common';
const _generate = (secureRandom: any) => {

@@ -18,2 +20,3 @@ let privateKey;

@common.types.staticImplements<common.types.KeyPairClass>()
export class Secp256k1KeyPair {

@@ -24,7 +27,26 @@ public id: string;

public publicKeyBase58: string;
public privateKeyBase58: string;
public publicKeyBuffer: Buffer;
public privateKeyBuffer?: Buffer;
static fingerprintFromPublicKey({ publicKeyBase58 }: any) {
const pubkeyBytes = bs58.decode(publicKeyBase58);
static fingerprintFromPublicKey(
keypair: common.types.KeyPairJwk | common.types.KeyPairBase58
) {
let pubkeyBytes: any;
if ((keypair as any).publicKeyBase58) {
pubkeyBytes = bs58.decode(
(keypair as common.types.KeyPairBase58).publicKeyBase58
);
}
if ((keypair as any).publicKeyJwk) {
pubkeyBytes = new Uint8Array(
Buffer.from(
keyUtils.publicKeyHexFromJwk(
(keypair as common.types.KeyPairJwk).publicKeyJwk
)
)
);
}
const buffer = new Uint8Array(2 + pubkeyBytes.length);

@@ -46,7 +68,3 @@ // See https://github.com/multiformats/multicodec/blob/master/table.csv

}
if (options.seed) {
({ privateKey, publicKey } = _generate(() => {
return new Uint8Array(options.seed);
}));
}
if (!privateKey) {

@@ -65,6 +83,6 @@ throw new Error('Cannot generate private key.');

publicKeyBase58,
})}`;
} as any)}`;
const keyId = `#${Secp256k1KeyPair.fingerprintFromPublicKey({
publicKeyBase58,
})}`;
} as any)}`;

@@ -123,6 +141,6 @@ return new Secp256k1KeyPair({

publicKeyBase58,
})}`;
} as any)}`;
const keyId = `#${Secp256k1KeyPair.fingerprintFromPublicKey({
publicKeyBase58,
})}`;
} as any)}`;
return new Secp256k1KeyPair({

@@ -140,26 +158,43 @@ id: keyId,

this.type = 'EcdsaSecp256k1VerificationKey2019';
this.id = options.id;
this.controller = options.controller;
this.privateKeyBase58 = options.privateKeyBase58;
this.publicKeyBase58 = options.publicKeyBase58;
}
get publicKey() {
return this.publicKeyBase58;
if (options.publicKeyBase58) {
this.publicKeyBuffer = bs58.decode(options.publicKeyBase58);
} else if (options.publicKeyJwk) {
this.publicKeyBuffer = Buffer.from(
keyUtils.publicKeyHexFromJwk(options.publicKeyJwk),
'hex'
);
} else {
throw new Error(
'Secp256k1KeyPair requires publicKeyBase58 or publicKeyJwk, recieved neither.'
);
}
if (options.privateKeyBase58) {
this.privateKeyBuffer = bs58.decode(options.privateKeyBase58);
}
if (options.privateKeyJwk) {
this.privateKeyBuffer = Buffer.from(
keyUtils.privateKeyHexFromJwk(options.privateKeyJwk),
'hex'
);
}
if (this.controller && !this.id) {
this.id = `${this.controller}#${this.fingerprint()}`;
}
}
get privateKey() {
return this.privateKeyBase58;
publicNode() {
return this.toKeyPair(false);
}
signer() {
if (!this.privateKeyBase58) {
return {
async sign() {
throw new Error('No private key to sign with.');
},
};
if (!this.privateKeyBuffer) {
throw new Error('No private key to sign with.');
}
let privateKeyBase58 = this.privateKeyBase58;
let { privateKeyBuffer } = this;
return {

@@ -171,8 +206,6 @@ async sign({ data }: any) {

.digest();
const privateKeyUInt8Array = await keyUtils.privateKeyUInt8ArrayFromPrivateKeyBase58(
privateKeyBase58
);
const sigObj: any = secp256k1.ecdsaSign(
messageHashUInt8Array,
privateKeyUInt8Array
new Uint8Array(privateKeyBuffer)
);

@@ -186,10 +219,6 @@

verifier() {
if (!this.publicKeyBase58) {
return {
async sign() {
throw new Error('No public key to verify with.');
},
};
if (!this.publicKeyBuffer) {
throw new Error('No public key to verify with.');
}
let publicKeyBase58 = this.publicKeyBase58;
let { publicKeyBuffer } = this;
return {

@@ -202,6 +231,2 @@ async verify({ data, signature }: any) {

const publicKeyUInt8Array = await keyUtils.publicKeyUInt8ArrayFromPublicKeyBase58(
publicKeyBase58
);
let verified = false;

@@ -212,3 +237,3 @@ try {

messageHashUInt8Array,
publicKeyUInt8Array
new Uint8Array(publicKeyBuffer)
);

@@ -223,10 +248,6 @@ } catch (e) {

addEncodedPublicKey(publicKeyNode: any) {
publicKeyNode.publicKeyBase58 = this.publicKeyBase58;
return publicKeyNode;
}
fingerprint() {
const { publicKeyBase58 } = this;
return Secp256k1KeyPair.fingerprintFromPublicKey({ publicKeyBase58 });
return Secp256k1KeyPair.fingerprintFromPublicKey({
publicKeyBase58: bs58.encode(this.publicKeyBuffer),
} as any);
}

@@ -249,8 +270,3 @@

}
let publicKeyBuffer;
try {
publicKeyBuffer = bs58.decode(this.publicKeyBase58);
} catch (e) {
return { error: e, valid: false };
}
let { publicKeyBuffer } = this;

@@ -270,22 +286,13 @@ // validate the first two multicodec bytes 0xe701

publicNode({ controller = this.controller } = {}) {
const publicNode: any = {
id: this.id,
type: this.type,
};
if (controller) {
publicNode.controller = controller;
}
this.addEncodedPublicKey(publicNode); // Subclass-specific
return publicNode;
}
toJwk(_private: boolean = false) {
if (_private) {
if (!this.privateKeyBuffer) {
throw new Error('No private key to export');
}
return keyUtils.privateKeyJwkFromPrivateKeyHex(
bs58.decode(this.privateKeyBase58).toString('hex')
this.privateKeyBuffer.toString('hex')
);
}
return keyUtils.publicKeyJwkFromPublicKeyHex(
bs58.decode(this.publicKeyBase58).toString('hex')
this.publicKeyBuffer.toString('hex')
);

@@ -296,5 +303,8 @@ }

if (_private) {
if (!this.privateKeyBuffer) {
throw new Error('No private key to export');
}
return keyUtils.privateKeyHexFromJwk(
await keyUtils.privateKeyJwkFromPrivateKeyHex(
bs58.decode(this.privateKeyBase58).toString('hex')
this.privateKeyBuffer.toString('hex')
)

@@ -305,3 +315,3 @@ );

await keyUtils.publicKeyJwkFromPublicKeyHex(
bs58.decode(this.publicKeyBase58).toString('hex')
this.publicKeyBuffer.toString('hex')
)

@@ -316,6 +326,6 @@ );

controller: this.controller,
publicKeyBase58: this.publicKeyBase58,
publicKeyBase58: bs58.encode(this.publicKeyBuffer),
};
if (exportPrivate) {
kp.privateKeyBase58 = this.privateKeyBase58;
kp.privateKeyBase58 = bs58.encode(this.privateKeyBuffer);
}

@@ -322,0 +332,0 @@ return kp;

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc