@transmute/did-key-secp256k1
Advanced tools
Comparing version 0.2.1-unstable.42 to 0.3.0-unstable.0
338
CHANGELOG.md
@@ -6,340 +6,4 @@ # Change Log | ||
## 0.2.1-unstable.42 (2021-04-19) | ||
# [0.3.0-unstable.0](https://github.com/transmute-industries/did-key.js/compare/v0.2.1-unstable.42...v0.3.0-unstable.0) (2021-07-05) | ||
**Note:** Version bump only for package @transmute/did-key-secp256k1 | ||
## 0.2.1-unstable.41 (2021-04-16) | ||
**Note:** Version bump only for package @transmute/did-key-secp256k1 | ||
## 0.2.1-unstable.40 (2021-04-15) | ||
**Note:** Version bump only for package @transmute/did-key-secp256k1 | ||
## 0.2.1-unstable.39 (2021-04-14) | ||
**Note:** Version bump only for package @transmute/did-key-secp256k1 | ||
## 0.2.1-unstable.38 (2021-04-14) | ||
**Note:** Version bump only for package @transmute/did-key-secp256k1 | ||
## 0.2.1-unstable.37 (2021-04-14) | ||
**Note:** Version bump only for package @transmute/did-key-secp256k1 | ||
## 0.2.1-unstable.36 (2021-04-14) | ||
**Note:** Version bump only for package @transmute/did-key-secp256k1 | ||
## 0.2.1-unstable.35 (2021-02-11) | ||
**Note:** Version bump only for package @transmute/did-key-secp256k1 | ||
## 0.2.1-unstable.34 (2021-02-08) | ||
**Note:** Version bump only for package @transmute/did-key-secp256k1 | ||
## 0.2.1-unstable.33 (2021-02-06) | ||
**Note:** Version bump only for package @transmute/did-key-secp256k1 | ||
## 0.2.1-unstable.32 (2021-02-06) | ||
**Note:** Version bump only for package @transmute/did-key-secp256k1 | ||
## 0.2.1-unstable.31 (2021-01-23) | ||
**Note:** Version bump only for package @transmute/did-key-secp256k1 | ||
## 0.2.1-unstable.30 (2021-01-18) | ||
**Note:** Version bump only for package @transmute/did-key-secp256k1 | ||
## 0.2.1-unstable.29 (2020-12-13) | ||
**Note:** Version bump only for package @transmute/did-key-secp256k1 | ||
## 0.2.1-unstable.28 (2020-11-17) | ||
**Note:** Version bump only for package @transmute/did-key-secp256k1 | ||
## 0.2.1-unstable.27 (2020-11-13) | ||
**Note:** Version bump only for package @transmute/did-key-secp256k1 | ||
## 0.2.1-unstable.26 (2020-11-13) | ||
**Note:** Version bump only for package @transmute/did-key-secp256k1 | ||
## 0.2.1-unstable.25 (2020-11-13) | ||
**Note:** Version bump only for package @transmute/did-key-secp256k1 | ||
## 0.2.1-unstable.24 (2020-11-08) | ||
**Note:** Version bump only for package @transmute/did-key-secp256k1 | ||
## 0.2.1-unstable.23 (2020-10-14) | ||
**Note:** Version bump only for package @transmute/did-key-secp256k1 | ||
## 0.2.1-unstable.22 (2020-10-07) | ||
**Note:** Version bump only for package @transmute/did-key-secp256k1 | ||
## 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) | ||
**Note:** Version bump only for package @transmute/did-key-secp256k1 | ||
## 0.2.1-unstable.19 (2020-09-15) | ||
**Note:** Version bump only for package @transmute/did-key-secp256k1 | ||
## 0.2.1-unstable.18 (2020-09-14) | ||
**Note:** Version bump only for package @transmute/did-key-secp256k1 | ||
## 0.2.1-unstable.17 (2020-09-14) | ||
**Note:** Version bump only for package @transmute/did-key-secp256k1 | ||
## 0.2.1-unstable.16 (2020-09-14) | ||
**Note:** Version bump only for package @transmute/did-key-secp256k1 | ||
## 0.2.1-unstable.15 (2020-09-14) | ||
**Note:** Version bump only for package @transmute/did-key-secp256k1 | ||
## 0.2.1-unstable.14 (2020-09-06) | ||
**Note:** Version bump only for package @transmute/did-key-secp256k1 | ||
## 0.2.1-unstable.13 (2020-08-22) | ||
**Note:** Version bump only for package @transmute/did-key-secp256k1 | ||
## 0.2.1-unstable.12 (2020-08-22) | ||
**Note:** Version bump only for package @transmute/did-key-secp256k1 | ||
## 0.2.1-unstable.11 (2020-08-13) | ||
**Note:** Version bump only for package @transmute/did-key-secp256k1 | ||
## 0.2.1-unstable.10 (2020-08-04) | ||
**Note:** Version bump only for package @transmute/did-key-secp256k1 | ||
## 0.2.1-unstable.9 (2020-08-04) | ||
**Note:** Version bump only for package @transmute/did-key-secp256k1 | ||
## 0.2.1-unstable.8 (2020-08-04) | ||
**Note:** Version bump only for package @transmute/did-key-secp256k1 | ||
## 0.2.1-unstable.7 (2020-08-04) | ||
**Note:** Version bump only for package @transmute/did-key-secp256k1 | ||
## 0.2.1-unstable.6 (2020-08-01) | ||
**Note:** Version bump only for package @transmute/did-key-secp256k1 | ||
## 0.2.1-unstable.5 (2020-08-01) | ||
**Note:** Version bump only for package @transmute/did-key-secp256k1 | ||
## 0.2.1-unstable.4 (2020-08-01) | ||
**Note:** Version bump only for package @transmute/did-key-secp256k1 | ||
## 0.2.1-unstable.3 (2020-07-29) | ||
**Note:** Version bump only for package @transmute/did-key-secp256k1 | ||
## 0.2.1-unstable.2 (2020-07-28) | ||
**Note:** Version bump only for package @transmute/did-key-secp256k1 | ||
## 0.2.1-unstable.1 (2020-07-17) | ||
**Note:** Version bump only for package @transmute/did-key-secp256k1 | ||
## 0.2.1-unstable.0 (2020-07-17) | ||
**Note:** Version bump only for package @transmute/did-key-secp256k1 |
@@ -5,979 +5,16 @@ 'use strict'; | ||
function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } | ||
var didKeyCommon = require('@transmute/did-key-common'); | ||
var secp256k1KeyPair = require('@transmute/secp256k1-key-pair'); | ||
var keyto = _interopDefault(require('@trust/keyto')); | ||
var base64url = _interopDefault(require('base64url')); | ||
var crypto = _interopDefault(require('crypto')); | ||
var bs58 = _interopDefault(require('bs58')); | ||
var secp256k1 = _interopDefault(require('secp256k1')); | ||
var canonicalize = _interopDefault(require('canonicalize')); | ||
var tslib = require('tslib'); | ||
var common = require('@transmute/did-key-common'); | ||
var generate = /*#__PURE__*/didKeyCommon.getGenerator(secp256k1KeyPair.Secp256k1KeyPair); | ||
var resolve = /*#__PURE__*/didKeyCommon.getResolver(secp256k1KeyPair.Secp256k1KeyPair); | ||
function _extends() { | ||
_extends = Object.assign || function (target) { | ||
for (var i = 1; i < arguments.length; i++) { | ||
var source = arguments[i]; | ||
for (var key in source) { | ||
if (Object.prototype.hasOwnProperty.call(source, key)) { | ||
target[key] = source[key]; | ||
} | ||
} | ||
} | ||
return target; | ||
}; | ||
return _extends.apply(this, arguments); | ||
} | ||
function _inheritsLoose(subClass, superClass) { | ||
subClass.prototype = Object.create(superClass.prototype); | ||
subClass.prototype.constructor = subClass; | ||
subClass.__proto__ = superClass; | ||
} | ||
function _getPrototypeOf(o) { | ||
_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { | ||
return o.__proto__ || Object.getPrototypeOf(o); | ||
}; | ||
return _getPrototypeOf(o); | ||
} | ||
function _setPrototypeOf(o, p) { | ||
_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { | ||
o.__proto__ = p; | ||
return o; | ||
}; | ||
return _setPrototypeOf(o, p); | ||
} | ||
function _isNativeReflectConstruct() { | ||
if (typeof Reflect === "undefined" || !Reflect.construct) return false; | ||
if (Reflect.construct.sham) return false; | ||
if (typeof Proxy === "function") return true; | ||
try { | ||
Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); | ||
return true; | ||
} catch (e) { | ||
return false; | ||
} | ||
} | ||
function _construct(Parent, args, Class) { | ||
if (_isNativeReflectConstruct()) { | ||
_construct = Reflect.construct; | ||
} else { | ||
_construct = function _construct(Parent, args, Class) { | ||
var a = [null]; | ||
a.push.apply(a, args); | ||
var Constructor = Function.bind.apply(Parent, a); | ||
var instance = new Constructor(); | ||
if (Class) _setPrototypeOf(instance, Class.prototype); | ||
return instance; | ||
}; | ||
} | ||
return _construct.apply(null, arguments); | ||
} | ||
function _isNativeFunction(fn) { | ||
return Function.toString.call(fn).indexOf("[native code]") !== -1; | ||
} | ||
function _wrapNativeSuper(Class) { | ||
var _cache = typeof Map === "function" ? new Map() : undefined; | ||
_wrapNativeSuper = function _wrapNativeSuper(Class) { | ||
if (Class === null || !_isNativeFunction(Class)) return Class; | ||
if (typeof Class !== "function") { | ||
throw new TypeError("Super expression must either be null or a function"); | ||
} | ||
if (typeof _cache !== "undefined") { | ||
if (_cache.has(Class)) return _cache.get(Class); | ||
_cache.set(Class, Wrapper); | ||
} | ||
function Wrapper() { | ||
return _construct(Class, arguments, _getPrototypeOf(this).constructor); | ||
} | ||
Wrapper.prototype = Object.create(Class.prototype, { | ||
constructor: { | ||
value: Wrapper, | ||
enumerable: false, | ||
writable: true, | ||
configurable: true | ||
} | ||
}); | ||
return _setPrototypeOf(Wrapper, Class); | ||
}; | ||
return _wrapNativeSuper(Class); | ||
} | ||
var compressedHexEncodedPublicKeyLength = 66; | ||
/** | ||
* Example | ||
* ```js | ||
* { | ||
* kty: 'EC', | ||
* crv: 'secp256k1', | ||
* d: 'rhYFsBPF9q3-uZThy7B3c4LDF_8wnozFUAEm5LLC4Zw', | ||
* x: 'dWCvM4fTdeM0KmloF57zxtBPXTOythHPMm1HCLrdd3A', | ||
* y: '36uMVGM7hnw-N6GnjFcihWE3SkrhMLzzLCdPMXPEXlA', | ||
* kid: 'JUvpllMEYUZ2joO59UNui_XYDqxVqiFLLAJ8klWuPBw' | ||
* } | ||
* ``` | ||
* See [rfc7638](https://tools.ietf.org/html/rfc7638) for more details on Jwk. | ||
*/ | ||
var getKid = function getKid(jwk) { | ||
var copy = _extends({}, jwk); | ||
delete copy.d; | ||
delete copy.kid; | ||
delete copy.alg; | ||
var digest = crypto.createHash('sha256').update(canonicalize(copy)).digest(); | ||
return base64url.encode(Buffer.from(digest)); | ||
}; | ||
/** convert compressed hex encoded private key to jwk */ | ||
var privateKeyJwkFromPrivateKeyHex = function privateKeyJwkFromPrivateKeyHex(privateKeyHex) { | ||
var jwk = _extends({}, keyto.from(privateKeyHex, 'blk').toJwk('private'), { | ||
crv: 'secp256k1' | ||
}); | ||
var kid = getKid(jwk); | ||
return _extends({}, jwk, { | ||
kid: kid | ||
}); | ||
}; | ||
/** convert compressed hex encoded public key to jwk */ | ||
var publicKeyJwkFromPublicKeyHex = function publicKeyJwkFromPublicKeyHex(publicKeyHex) { | ||
var key = publicKeyHex; | ||
if (publicKeyHex.length === compressedHexEncodedPublicKeyLength) { | ||
var keyBin = secp256k1.publicKeyConvert(Buffer.from(publicKeyHex, 'hex'), false); | ||
key = Buffer.from(keyBin).toString('hex'); | ||
} | ||
var jwk = _extends({}, keyto.from(key, 'blk').toJwk('public'), { | ||
crv: 'secp256k1' | ||
}); | ||
var kid = getKid(jwk); | ||
return _extends({}, jwk, { | ||
kid: kid | ||
}); | ||
}; | ||
/** convert pem encoded private key to jwk */ | ||
var privateKeyJwkFromPrivateKeyPem = function privateKeyJwkFromPrivateKeyPem(privateKeyPem) { | ||
var jwk = _extends({}, keyto.from(privateKeyPem, 'pem').toJwk('private'), { | ||
crv: 'secp256k1' | ||
}); // console.log(jwk); | ||
var kid = getKid(jwk); | ||
return _extends({}, jwk, { | ||
kid: kid | ||
}); | ||
}; | ||
/** convert pem encoded public key to jwk */ | ||
var publicKeyJwkFromPublicKeyPem = function publicKeyJwkFromPublicKeyPem(publicKeyPem) { | ||
var jwk = _extends({}, keyto.from(publicKeyPem, 'pem').toJwk('public'), { | ||
crv: 'secp256k1' | ||
}); | ||
var kid = getKid(jwk); | ||
return _extends({}, jwk, { | ||
kid: kid | ||
}); | ||
}; | ||
/** convert jwk to hex encoded private key */ | ||
var privateKeyHexFromJwk = function privateKeyHexFromJwk(jwk) { | ||
return keyto.from(_extends({}, jwk, { | ||
crv: 'K-256' | ||
}), 'jwk').toString('blk', 'private'); | ||
}; | ||
/** convert jwk to hex encoded public key */ | ||
var publicKeyHexFromJwk = function publicKeyHexFromJwk(jwk) { | ||
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'); | ||
}; | ||
/** convert jwk to binary encoded private key */ | ||
var privateKeyUInt8ArrayFromJwk = function privateKeyUInt8ArrayFromJwk(jwk) { | ||
var privateKeyHex = privateKeyHexFromJwk(jwk); | ||
var asBuffer = Buffer.from(privateKeyHex, 'hex'); | ||
var padding = 32 - asBuffer.length; | ||
while (padding > 0) { | ||
asBuffer = Buffer.concat([Buffer.from('00', 'hex'), asBuffer]); | ||
padding--; | ||
} | ||
return asBuffer; | ||
}; | ||
/** convert jwk to binary encoded public key */ | ||
var publicKeyUInt8ArrayFromJwk = function publicKeyUInt8ArrayFromJwk(jwk) { | ||
var publicKeyHex = publicKeyHexFromJwk(jwk); | ||
var asBuffer = Buffer.from(publicKeyHex, 'hex'); | ||
var padding = 32 - asBuffer.length; | ||
while (padding > 0) { | ||
asBuffer = Buffer.concat([Buffer.from('00', 'hex'), asBuffer]); | ||
padding--; | ||
} | ||
return asBuffer; | ||
}; | ||
/** convert publicKeyHex to base58 */ | ||
var publicKeyBase58FromPublicKeyHex = function publicKeyBase58FromPublicKeyHex(publicKeyHex) { | ||
return bs58.encode(Buffer.from(publicKeyHex, 'hex')); | ||
}; | ||
/** convert publicKeyHex to base58 */ | ||
var privateKeyBase58FromPrivateKeyHex = function privateKeyBase58FromPrivateKeyHex(privateKeyHex) { | ||
return bs58.encode(Buffer.from(privateKeyHex, 'hex')); | ||
}; | ||
var privateKeyUInt8ArrayFromPrivateKeyBase58 = function privateKeyUInt8ArrayFromPrivateKeyBase58(privateKeyBase58) { | ||
return bs58.decode(privateKeyBase58); | ||
}; | ||
var publicKeyUInt8ArrayFromPublicKeyBase58 = function publicKeyUInt8ArrayFromPublicKeyBase58(publicKeyBase58) { | ||
return bs58.decode(publicKeyBase58); | ||
}; | ||
var publicKeyHexFromPrivateKeyHex = function publicKeyHexFromPrivateKeyHex(privateKeyHex) { | ||
var publicKey = secp256k1.publicKeyCreate(new Uint8Array(Buffer.from(privateKeyHex, 'hex'))); | ||
return Buffer.from(publicKey).toString('hex'); | ||
}; | ||
var publicKeyJwkFromPublicKeyBase58 = function publicKeyJwkFromPublicKeyBase58(publicKeybase58) { | ||
return publicKeyJwkFromPublicKeyHex(bs58.decode(publicKeybase58).toString('hex')); | ||
}; | ||
var privateKeyJwkFromPrivateKeyBase58 = function privateKeyJwkFromPrivateKeyBase58(privateKeyBase58) { | ||
return privateKeyJwkFromPrivateKeyHex(bs58.decode(privateKeyBase58).toString('hex')); | ||
}; | ||
var keyUtils = { | ||
__proto__: null, | ||
getKid: getKid, | ||
privateKeyJwkFromPrivateKeyHex: privateKeyJwkFromPrivateKeyHex, | ||
publicKeyJwkFromPublicKeyHex: publicKeyJwkFromPublicKeyHex, | ||
privateKeyJwkFromPrivateKeyPem: privateKeyJwkFromPrivateKeyPem, | ||
publicKeyJwkFromPublicKeyPem: publicKeyJwkFromPublicKeyPem, | ||
privateKeyHexFromJwk: privateKeyHexFromJwk, | ||
publicKeyHexFromJwk: publicKeyHexFromJwk, | ||
privateKeyUInt8ArrayFromJwk: privateKeyUInt8ArrayFromJwk, | ||
publicKeyUInt8ArrayFromJwk: publicKeyUInt8ArrayFromJwk, | ||
publicKeyBase58FromPublicKeyHex: publicKeyBase58FromPublicKeyHex, | ||
privateKeyBase58FromPrivateKeyHex: privateKeyBase58FromPrivateKeyHex, | ||
privateKeyUInt8ArrayFromPrivateKeyBase58: privateKeyUInt8ArrayFromPrivateKeyBase58, | ||
publicKeyUInt8ArrayFromPublicKeyBase58: publicKeyUInt8ArrayFromPublicKeyBase58, | ||
publicKeyHexFromPrivateKeyHex: publicKeyHexFromPrivateKeyHex, | ||
publicKeyJwkFromPublicKeyBase58: publicKeyJwkFromPublicKeyBase58, | ||
privateKeyJwkFromPrivateKeyBase58: privateKeyJwkFromPrivateKeyBase58 | ||
}; | ||
/** error matching @panva/jose for JWS verification failure. */ | ||
var JWSVerificationFailed = /*#__PURE__*/function (_Error) { | ||
_inheritsLoose(JWSVerificationFailed, _Error); | ||
function JWSVerificationFailed(message) { | ||
var _this; | ||
_this = _Error.call(this, message) || this; | ||
_this.name = 'JWSVerificationFailed'; | ||
return _this; | ||
} | ||
return JWSVerificationFailed; | ||
}( /*#__PURE__*/_wrapNativeSuper(Error)); | ||
/** Produce a JWS Unencoded Payload per https://tools.ietf.org/html/rfc7797#section-6 */ | ||
var signDetached = function signDetached( // in the case of EcdsaSecp256k1Signature2019 this is the result of createVerifyData | ||
payload, privateKeyJwk, header) { | ||
if (header === void 0) { | ||
header = { | ||
alg: 'ES256K', | ||
b64: false, | ||
crit: ['b64'] | ||
}; | ||
} | ||
try { | ||
return Promise.resolve(privateKeyUInt8ArrayFromJwk(privateKeyJwk)).then(function (privateKeyUInt8Array) { | ||
var encodedHeader = base64url.encode(JSON.stringify(header)); | ||
var toBeSignedBuffer = Buffer.concat([Buffer.from(encodedHeader + '.', 'utf8'), Buffer.from(payload.buffer, payload.byteOffset, payload.length)]); | ||
var message = Buffer.from(toBeSignedBuffer); | ||
var digest = crypto.createHash('sha256').update(message).digest(); | ||
var messageHashUInt8Array = digest; | ||
var sigObj = secp256k1.ecdsaSign(messageHashUInt8Array, privateKeyUInt8Array); | ||
var encodedSignature = base64url.encode(Buffer.from(sigObj.signature)); | ||
return encodedHeader + ".." + encodedSignature; | ||
}); | ||
} catch (e) { | ||
return Promise.reject(e); | ||
} | ||
}; | ||
/** Verify a JWS Unencoded Payload per https://tools.ietf.org/html/rfc7797#section-6 */ | ||
var verifyDetached = function verifyDetached(jws, payload, publicKeyJwk) { | ||
try { | ||
if (jws.indexOf('..') === -1) { | ||
throw new JWSVerificationFailed('not a valid rfc7797 jws.'); | ||
} | ||
var _jws$split = jws.split('..'), | ||
encodedHeader = _jws$split[0], | ||
encodedSignature = _jws$split[1]; | ||
var header = JSON.parse(base64url.decode(encodedHeader)); | ||
if (header.alg !== 'ES256K') { | ||
throw new Error('JWS alg is not signed with ES256K.'); | ||
} | ||
if (header.b64 !== false || !header.crit || !header.crit.length || header.crit[0] !== 'b64') { | ||
throw new Error('JWS Header is not in rfc7797 format (not detached).'); | ||
} | ||
return Promise.resolve(publicKeyUInt8ArrayFromJwk(publicKeyJwk)).then(function (publicKeyUInt8Array) { | ||
var toBeSignedBuffer = Buffer.concat([Buffer.from(encodedHeader + '.', 'utf8'), Buffer.from(payload.buffer, payload.byteOffset, payload.length)]); | ||
var message = Buffer.from(toBeSignedBuffer); | ||
var digest = crypto.createHash('sha256').update(message).digest(); | ||
var messageHashUInt8Array = digest; | ||
var signatureUInt8Array = base64url.toBuffer(encodedSignature); | ||
var signatureLowerS = secp256k1.signatureNormalize(signatureUInt8Array); | ||
var verified = secp256k1.ecdsaVerify(signatureLowerS, messageHashUInt8Array, publicKeyUInt8Array); | ||
return verified; | ||
}); | ||
} catch (e) { | ||
return Promise.reject(e); | ||
} | ||
}; | ||
/** Produce a normal ES256K JWS */ | ||
var sign = function sign(payload, privateKeyJwk, header) { | ||
if (header === void 0) { | ||
header = { | ||
alg: 'ES256K' | ||
}; | ||
} | ||
try { | ||
return Promise.resolve(privateKeyUInt8ArrayFromJwk(privateKeyJwk)).then(function (privateKeyUInt8Array) { | ||
var encodedHeader = base64url.encode(JSON.stringify(header)); | ||
var encodedPayload = base64url.encode(JSON.stringify(payload)); | ||
var toBeSigned = encodedHeader + "." + encodedPayload; | ||
var message = Buffer.from(toBeSigned); | ||
var digest = crypto.createHash('sha256').update(message).digest(); | ||
var messageHashUInt8Array = digest; | ||
var sigObj = secp256k1.ecdsaSign(messageHashUInt8Array, privateKeyUInt8Array); | ||
var encodedSignature = base64url.encode(sigObj.signature); | ||
return encodedHeader + "." + encodedPayload + "." + encodedSignature; | ||
}); | ||
} catch (e) { | ||
return Promise.reject(e); | ||
} | ||
}; | ||
/** Verify an ES256K JWS, returns the decoded object if successful, throws otherwise. */ | ||
var verify = function verify(jws, publicKeyJwk) { | ||
try { | ||
return Promise.resolve(publicKeyUInt8ArrayFromJwk(publicKeyJwk)).then(function (publicKeyUInt8Array) { | ||
var _jws$split2 = jws.split('.'), | ||
encodedHeader = _jws$split2[0], | ||
encodedPayload = _jws$split2[1], | ||
encodedSignature = _jws$split2[2]; | ||
var toBeSigned = encodedHeader + "." + encodedPayload; | ||
var message = Buffer.from(toBeSigned); | ||
var digest = crypto.createHash('sha256').update(message).digest(); | ||
var messageHashUInt8Array = digest; | ||
var signatureUInt8Array = base64url.toBuffer(encodedSignature); | ||
var signatureLowerS = secp256k1.signatureNormalize(signatureUInt8Array); | ||
var verified = secp256k1.ecdsaVerify(signatureLowerS, messageHashUInt8Array, publicKeyUInt8Array); | ||
return verified; | ||
}); | ||
} catch (e) { | ||
return Promise.reject(e); | ||
} | ||
}; | ||
/** decode a JWS (without verifying it) */ | ||
var decode = function decode(jws, options) { | ||
if (options === void 0) { | ||
options = { | ||
complete: false | ||
}; | ||
} | ||
var _jws$split3 = jws.split('.'), | ||
encodedHeader = _jws$split3[0], | ||
encodedPayload = _jws$split3[1], | ||
encodedSignature = _jws$split3[2]; | ||
if (options.complete) { | ||
return { | ||
header: JSON.parse(base64url.decode(encodedHeader)), | ||
payload: JSON.parse(base64url.decode(encodedPayload)), | ||
signature: encodedSignature | ||
}; | ||
} | ||
return JSON.parse(base64url.decode(encodedPayload)); | ||
}; | ||
var ES256K = { | ||
__proto__: null, | ||
signDetached: signDetached, | ||
verifyDetached: verifyDetached, | ||
sign: sign, | ||
verify: verify, | ||
decode: decode | ||
}; | ||
var sign$1 = function sign(payload, privateKeyJwk, header) { | ||
if (header === void 0) { | ||
header = { | ||
alg: 'ES256K-R' | ||
}; | ||
} | ||
try { | ||
return Promise.resolve(privateKeyUInt8ArrayFromJwk(privateKeyJwk)).then(function (privateKeyUInt8Array) { | ||
var encodedHeader = base64url.encode(JSON.stringify(header)); | ||
var encodedPayload = base64url.encode(JSON.stringify(payload)); | ||
var toBeSigned = encodedHeader + "." + encodedPayload; | ||
var message = Buffer.from(toBeSigned); | ||
var digest = crypto.createHash('sha256').update(message).digest(); | ||
var messageHashUInt8Array = digest; | ||
var sigObj = secp256k1.ecdsaSign(messageHashUInt8Array, privateKeyUInt8Array); | ||
var encodedSignature = base64url.encode(sigObj.signature); | ||
return encodedHeader + "." + encodedPayload + "." + encodedSignature; | ||
}); | ||
} catch (e) { | ||
return Promise.reject(e); | ||
} | ||
}; | ||
var verify$1 = function verify(jws, publicKeyJwk) { | ||
try { | ||
return Promise.resolve(publicKeyUInt8ArrayFromJwk(publicKeyJwk)).then(function (publicKeyUInt8Array) { | ||
var _jws$split = jws.split('.'), | ||
encodedHeader = _jws$split[0], | ||
encodedPayload = _jws$split[1], | ||
encodedSignature = _jws$split[2]; | ||
var header = JSON.parse(base64url.decode(encodedHeader)); | ||
if (header.alg !== 'ES256K-R') { | ||
throw new Error('Expecteed header.alg to be ES256K-R'); | ||
} | ||
var toBeSigned = encodedHeader + "." + encodedPayload; | ||
var message = Buffer.from(toBeSigned); | ||
var digest = crypto.createHash('sha256').update(message).digest(); | ||
var messageHashUInt8Array = digest; | ||
var signatureUInt8Array = base64url.toBuffer(encodedSignature); | ||
var signatureLowerS = secp256k1.signatureNormalize(signatureUInt8Array); | ||
var verified = secp256k1.ecdsaVerify(signatureLowerS, messageHashUInt8Array, publicKeyUInt8Array); | ||
return verified; | ||
}); | ||
} catch (e) { | ||
return Promise.reject(e); | ||
} | ||
}; | ||
var signDetached$1 = function signDetached(payload, privateKeyJwk, header) { | ||
if (header === void 0) { | ||
header = { | ||
alg: 'ES256K-R', | ||
b64: false, | ||
crit: ['b64'] | ||
}; | ||
} | ||
try { | ||
return Promise.resolve(privateKeyUInt8ArrayFromJwk(privateKeyJwk)).then(function (privateKeyUInt8Array) { | ||
var encodedHeader = base64url.encode(JSON.stringify(header)); | ||
var toBeSignedBuffer = Buffer.concat([Buffer.from(encodedHeader + '.', 'utf8'), Buffer.from(payload.buffer, payload.byteOffset, payload.length)]); | ||
var message = Buffer.from(toBeSignedBuffer); | ||
var digest = crypto.createHash('sha256').update(message).digest(); | ||
var messageHashUInt8Array = digest; | ||
var _secp256k1$ecdsaSign = secp256k1.ecdsaSign(messageHashUInt8Array, privateKeyUInt8Array), | ||
signature = _secp256k1$ecdsaSign.signature, | ||
recid = _secp256k1$ecdsaSign.recid; | ||
var signatureUInt8Array = Buffer.concat([Buffer.from(signature), Buffer.from(new Uint8Array([recid]))]); | ||
var encodedSignature = base64url.encode(signatureUInt8Array); | ||
return encodedHeader + ".." + encodedSignature; | ||
}); | ||
} catch (e) { | ||
return Promise.reject(e); | ||
} | ||
}; | ||
var recoverPublicKey = function recoverPublicKey(jws, payload) { | ||
try { | ||
if (jws.indexOf('..') === -1) { | ||
throw new Error('not a valid rfc7797 jws.'); | ||
} | ||
var _jws$split2 = jws.split('..'), | ||
encodedHeader = _jws$split2[0], | ||
encodedSignature = _jws$split2[1]; | ||
var header = JSON.parse(base64url.decode(encodedHeader)); | ||
if (header.alg !== 'ES256K-R') { | ||
throw new Error('JWS alg is not signed with ES256K-R.'); | ||
} | ||
if (header.b64 !== false || !header.crit || !header.crit.length || header.crit[0] !== 'b64') { | ||
throw new Error('JWS Header is not in rfc7797 format (not detached).'); | ||
} | ||
var toBeSignedBuffer = Buffer.concat([Buffer.from(encodedHeader + '.', 'utf8'), Buffer.from(payload.buffer, payload.byteOffset, payload.length)]); | ||
var message = Buffer.from(toBeSignedBuffer); | ||
var digest = new Uint8Array(crypto.createHash('sha256').update(message).digest()); | ||
var signatureUInt8Array = new Uint8Array(base64url.toBuffer(encodedSignature)); | ||
var recoveryId = signatureUInt8Array[64]; | ||
signatureUInt8Array = signatureUInt8Array.slice(0, 64); | ||
return Promise.resolve(secp256k1.ecdsaRecover(signatureUInt8Array, recoveryId, digest)); | ||
} catch (e) { | ||
return Promise.reject(e); | ||
} | ||
}; | ||
var ES256KR = { | ||
__proto__: null, | ||
sign: sign$1, | ||
verify: verify$1, | ||
signDetached: signDetached$1, | ||
recoverPublicKey: recoverPublicKey | ||
}; | ||
var Secp256k1KeyPair_1; | ||
var _generate = function _generate(secureRandom) { | ||
var privateKey; | ||
do { | ||
privateKey = secureRandom(); | ||
} while (!secp256k1.privateKeyVerify(privateKey)); | ||
var publicKey = secp256k1.publicKeyCreate(privateKey); | ||
return { | ||
publicKey: publicKey, | ||
privateKey: privateKey | ||
}; | ||
}; | ||
exports.Secp256k1KeyPair = Secp256k1KeyPair_1 = /*#__PURE__*/function () { | ||
function Secp256k1KeyPair(options) { | ||
if (options === void 0) { | ||
options = {}; | ||
} | ||
this.type = 'EcdsaSecp256k1VerificationKey2019'; | ||
this.id = options.id; | ||
this.controller = options.controller; | ||
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(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 | ||
// 0xe7 is Secp256k1 public key | ||
buffer[0] = 0xe7; // | ||
buffer[1] = 0x01; | ||
buffer.set(pubkeyBytes, 2); // prefix with `z` to indicate multi-base base58btc encoding | ||
return "z" + bs58.encode(buffer); | ||
}; | ||
Secp256k1KeyPair.generate = function generate(options) { | ||
if (options === void 0) { | ||
options = {}; | ||
} | ||
try { | ||
var privateKey; | ||
var publicKey; | ||
if (options.secureRandom) { | ||
var _generate2 = _generate(options.secureRandom); | ||
privateKey = _generate2.privateKey; | ||
publicKey = _generate2.publicKey; | ||
} | ||
if (!privateKey) { | ||
throw new Error('Cannot generate private key.'); | ||
} | ||
var publicKeyBase58 = publicKeyBase58FromPublicKeyHex(Buffer.from(publicKey).toString('hex')); | ||
var privateKeyBase58 = privateKeyBase58FromPrivateKeyHex(Buffer.from(privateKey).toString('hex')); | ||
var did = "did:key:" + Secp256k1KeyPair_1.fingerprintFromPublicKey({ | ||
publicKeyBase58: publicKeyBase58 | ||
}); | ||
var keyId = "#" + Secp256k1KeyPair_1.fingerprintFromPublicKey({ | ||
publicKeyBase58: publicKeyBase58 | ||
}); | ||
return Promise.resolve(new Secp256k1KeyPair_1({ | ||
id: keyId, | ||
controller: did, | ||
publicKeyBase58: publicKeyBase58, | ||
privateKeyBase58: privateKeyBase58 | ||
})); | ||
} catch (e) { | ||
return Promise.reject(e); | ||
} | ||
}; | ||
Secp256k1KeyPair.from = function from(options) { | ||
try { | ||
var _temp9 = function _temp9() { | ||
function _temp6() { | ||
function _temp4() { | ||
function _temp2() { | ||
return new Secp256k1KeyPair_1(_extends({}, options, { | ||
privateKeyBase58: privateKeyBase58, | ||
publicKeyBase58: publicKeyBase58 | ||
})); | ||
} | ||
var _temp = function () { | ||
if (options.publicKeyJwk) { | ||
var _privateKeyBase58From3 = privateKeyBase58FromPrivateKeyHex; | ||
return Promise.resolve(publicKeyHexFromJwk(options.publicKeyJwk)).then(function (_keyUtils$publicKeyHe) { | ||
publicKeyBase58 = _privateKeyBase58From3.call(keyUtils, _keyUtils$publicKeyHe); | ||
}); | ||
} | ||
}(); | ||
return _temp && _temp.then ? _temp.then(_temp2) : _temp2(_temp); | ||
} | ||
var _temp3 = function () { | ||
if (options.privateKeyJwk) { | ||
var _privateKeyBase58From4 = privateKeyBase58FromPrivateKeyHex; | ||
return Promise.resolve(privateKeyHexFromJwk(options.privateKeyJwk)).then(function (_keyUtils$privateKeyH) { | ||
privateKeyBase58 = _privateKeyBase58From4.call(keyUtils, _keyUtils$privateKeyH); | ||
}); | ||
} | ||
}(); | ||
return _temp3 && _temp3.then ? _temp3.then(_temp4) : _temp4(_temp3); | ||
} | ||
var _temp5 = function () { | ||
if (options.publicKeyHex) { | ||
return Promise.resolve(publicKeyBase58FromPublicKeyHex(options.publicKeyHex)).then(function (_keyUtils$publicKeyBa) { | ||
publicKeyBase58 = _keyUtils$publicKeyBa; | ||
}); | ||
} | ||
}(); | ||
return _temp5 && _temp5.then ? _temp5.then(_temp6) : _temp6(_temp5); | ||
}; | ||
var privateKeyBase58 = options.privateKeyBase58; | ||
var publicKeyBase58 = options.publicKeyBase58; | ||
var _temp10 = function () { | ||
if (options.privateKeyHex) { | ||
return Promise.resolve(privateKeyBase58FromPrivateKeyHex(options.privateKeyHex)).then(function (_keyUtils$privateKeyB) { | ||
privateKeyBase58 = _keyUtils$privateKeyB; | ||
}); | ||
} | ||
}(); | ||
return Promise.resolve(_temp10 && _temp10.then ? _temp10.then(_temp9) : _temp9(_temp10)); | ||
} catch (e) { | ||
return Promise.reject(e); | ||
} | ||
}; | ||
Secp256k1KeyPair.fromFingerprint = function fromFingerprint(_ref) { | ||
var fingerprint = _ref.fingerprint; | ||
// skip leading `z` that indicates base58 encoding | ||
var buffer = bs58.decode(fingerprint.substr(1)); // https://github.com/multiformats/multicodec/blob/master/table.csv#L77 | ||
if (buffer[0] === 0xe7 && buffer[1] === 0x01) { | ||
var publicKeyBase58 = bs58.encode(buffer.slice(2)); | ||
var did = "did:key:" + Secp256k1KeyPair_1.fingerprintFromPublicKey({ | ||
publicKeyBase58: publicKeyBase58 | ||
}); | ||
var keyId = "#" + Secp256k1KeyPair_1.fingerprintFromPublicKey({ | ||
publicKeyBase58: publicKeyBase58 | ||
}); | ||
return new Secp256k1KeyPair_1({ | ||
id: keyId, | ||
controller: did, | ||
publicKeyBase58: publicKeyBase58 | ||
}); | ||
} | ||
throw new Error("Unsupported Fingerprint Type: " + fingerprint); | ||
}; | ||
var _proto = Secp256k1KeyPair.prototype; | ||
_proto.publicNode = function publicNode() { | ||
return this.toKeyPair(false); | ||
}; | ||
_proto.signer = function signer() { | ||
if (!this.privateKeyBuffer) { | ||
throw new Error('No private key to sign with.'); | ||
} | ||
var privateKeyBuffer = this.privateKeyBuffer; | ||
return { | ||
sign: function sign(_ref2) { | ||
var data = _ref2.data; | ||
try { | ||
var messageHashUInt8Array = crypto.createHash('sha256').update(data).digest(); | ||
var sigObj = secp256k1.ecdsaSign(messageHashUInt8Array, new Uint8Array(privateKeyBuffer)); | ||
return Promise.resolve(sigObj.signature); | ||
} catch (e) { | ||
return Promise.reject(e); | ||
} | ||
} | ||
}; | ||
}; | ||
_proto.verifier = function verifier() { | ||
if (!this.publicKeyBuffer) { | ||
throw new Error('No public key to verify with.'); | ||
} | ||
var publicKeyBuffer = this.publicKeyBuffer; | ||
return { | ||
verify: function verify(_ref3) { | ||
var data = _ref3.data, | ||
signature = _ref3.signature; | ||
try { | ||
var messageHashUInt8Array = crypto.createHash('sha256').update(data).digest(); | ||
var verified = false; | ||
try { | ||
verified = secp256k1.ecdsaVerify(signature, messageHashUInt8Array, new Uint8Array(publicKeyBuffer)); | ||
} catch (e) { | ||
console.error('An error occurred when verifying signature: ', e); | ||
} | ||
return Promise.resolve(verified); | ||
} catch (e) { | ||
return Promise.reject(e); | ||
} | ||
} | ||
}; | ||
}; | ||
_proto.fingerprint = function fingerprint() { | ||
return Secp256k1KeyPair_1.fingerprintFromPublicKey({ | ||
publicKeyBase58: bs58.encode(this.publicKeyBuffer) | ||
}); | ||
}; | ||
_proto.verifyFingerprint = function verifyFingerprint(fingerprint) { | ||
// fingerprint should have `z` prefix indicating | ||
// that it's multi-base encoded | ||
if (!(typeof fingerprint === 'string' && fingerprint[0] === 'z')) { | ||
return { | ||
error: new Error('`fingerprint` must be a multibase encoded string.'), | ||
valid: false | ||
}; | ||
} | ||
var fingerprintBuffer; | ||
try { | ||
fingerprintBuffer = bs58.decode(fingerprint.slice(1)); | ||
} catch (e) { | ||
return { | ||
error: e, | ||
valid: false | ||
}; | ||
} | ||
var publicKeyBuffer = this.publicKeyBuffer; // validate the first two multicodec bytes 0xe701 | ||
var valid = fingerprintBuffer.slice(0, 2).toString('hex') === 'e701' && publicKeyBuffer.equals(fingerprintBuffer.slice(2)); | ||
if (!valid) { | ||
return { | ||
error: new Error('The fingerprint does not match the public key.'), | ||
valid: false | ||
}; | ||
} | ||
return { | ||
valid: valid | ||
}; | ||
}; | ||
_proto.toJwk = function toJwk(_private) { | ||
if (_private === void 0) { | ||
_private = false; | ||
} | ||
if (_private) { | ||
if (!this.privateKeyBuffer) { | ||
throw new Error('No private key to export'); | ||
} | ||
return privateKeyJwkFromPrivateKeyHex(this.privateKeyBuffer.toString('hex')); | ||
} | ||
return publicKeyJwkFromPublicKeyHex(this.publicKeyBuffer.toString('hex')); | ||
}; | ||
_proto.toHex = function toHex(_private) { | ||
if (_private === void 0) { | ||
_private = false; | ||
} | ||
try { | ||
var _temp13 = function _temp13(_result) { | ||
if (_exit2) return _result; | ||
var _publicKeyHexFromJwk = publicKeyHexFromJwk; | ||
return Promise.resolve(publicKeyJwkFromPublicKeyHex(_this2.publicKeyBuffer.toString('hex'))).then(function (_keyUtils$publicKeyJw) { | ||
return _publicKeyHexFromJwk.call(keyUtils, _keyUtils$publicKeyJw); | ||
}); | ||
}; | ||
var _exit2 = false; | ||
var _this2 = this; | ||
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(_this2.privateKeyBuffer.toString('hex'))).then(function (_keyUtils$privateKeyJ) { | ||
return _privateKeyHexFromJwk2.call(keyUtils, _keyUtils$privateKeyJ); | ||
}); | ||
} | ||
}(); | ||
return Promise.resolve(_temp14 && _temp14.then ? _temp14.then(_temp13) : _temp13(_temp14)); | ||
} catch (e) { | ||
return Promise.reject(e); | ||
} | ||
}; | ||
_proto.toKeyPair = function toKeyPair(exportPrivate) { | ||
if (exportPrivate === void 0) { | ||
exportPrivate = false; | ||
} | ||
var kp = { | ||
id: this.id, | ||
type: this.type, | ||
controller: this.controller, | ||
publicKeyBase58: bs58.encode(this.publicKeyBuffer) | ||
}; | ||
if (exportPrivate) { | ||
kp.privateKeyBase58 = bs58.encode(this.privateKeyBuffer); | ||
} | ||
return kp; | ||
}; | ||
_proto.toJsonWebKeyPair = function toJsonWebKeyPair(exportPrivate) { | ||
if (exportPrivate === void 0) { | ||
exportPrivate = false; | ||
} | ||
var kp = { | ||
id: this.id, | ||
type: 'JsonWebKey2020', | ||
controller: this.controller, | ||
publicKeyJwk: this.toJwk() | ||
}; | ||
delete kp.publicKeyJwk.kid; | ||
if (exportPrivate) { | ||
kp.privateKeyJwk = this.toJwk(true); | ||
delete kp.privateKeyJwk.kid; | ||
} | ||
return kp; | ||
}; | ||
return Secp256k1KeyPair; | ||
}(); | ||
exports.Secp256k1KeyPair = Secp256k1KeyPair_1 = /*#__PURE__*/tslib.__decorate([/*#__PURE__*/common.types.staticImplements()], exports.Secp256k1KeyPair); | ||
var resolve = /*#__PURE__*/common.getResolve(exports.Secp256k1KeyPair); | ||
var get = /*#__PURE__*/common.getGet(resolve); | ||
var driver = { | ||
__proto__: null, | ||
resolve: resolve, | ||
get: get | ||
}; | ||
exports.ES256K = ES256K; | ||
exports.ES256KR = ES256KR; | ||
exports.driver = driver; | ||
exports.keyUtils = keyUtils; | ||
Object.defineProperty(exports, 'Secp256k1KeyPair', { | ||
enumerable: true, | ||
get: function () { | ||
return secp256k1KeyPair.Secp256k1KeyPair; | ||
} | ||
}); | ||
exports.generate = generate; | ||
exports.resolve = resolve; | ||
//# 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")),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 l(e,r){return(l=Object.setPrototypeOf||function(e,r){return e.__proto__=r,e})(e,r)}function p(){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=p()?Reflect.construct:function(e,r,t){var i=[null];i.push.apply(i,r);var n=new(Function.bind.apply(e,i));return t&&l(n,t.prototype),n}).apply(null,arguments)}function d(e){var r="function"==typeof Map?new Map:void 0;return(d=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}}),l(t,e)})(e)}var v,h=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:h(t)})},m=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:h(n)})},b=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")},B=function(e){for(var r=b(e),t=Buffer.from(r,"hex"),i=32-t.length;i>0;)t=Buffer.concat([Buffer.from("00","hex"),t]),i--;return t},w=function(e){for(var r=g(e),t=Buffer.from(r,"hex"),i=32-t.length;i>0;)t=Buffer.concat([Buffer.from("00","hex"),t]),i--;return t},k=function(e){return n.encode(Buffer.from(e,"hex"))},P=function(e){return n.encode(Buffer.from(e,"hex"))},S={__proto__:null,getKid:h,privateKeyJwkFromPrivateKeyHex:K,publicKeyJwkFromPublicKeyHex:m,privateKeyJwkFromPrivateKeyPem:function(e){var t=a({},r.from(e,"pem").toJwk("private"),{crv:"secp256k1"});return a({},t,{kid:h(t)})},publicKeyJwkFromPublicKeyPem:function(e){var t=a({},r.from(e,"pem").toJwk("public"),{crv:"secp256k1"});return a({},t,{kid:h(t)})},privateKeyHexFromJwk:b,publicKeyHexFromJwk:g,privateKeyUInt8ArrayFromJwk:B,publicKeyUInt8ArrayFromJwk:w,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")},publicKeyJwkFromPublicKeyBase58:function(e){return m(n.decode(e).toString("hex"))},privateKeyJwkFromPrivateKeyBase58:function(e){return K(n.decode(e).toString("hex"))}},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}(d(Error)),J={__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 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 x("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(w(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),l=o.signatureNormalize(s);return o.ecdsaVerify(l,a,e)}))}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 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(w(r)).then((function(r){var n=e.split("."),u=n[2],c=Buffer.from(n[0]+"."+n[1]),f=i.createHash("sha256").update(c).digest(),a=t.toBuffer(u),s=o.signatureNormalize(a);return o.ecdsaVerify(s,f,r)}))}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))}},O={__proto__:null,sign:function(e,r,n){void 0===n&&(n={alg:"ES256K-R"});try{return Promise.resolve(B(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(w(r)).then((function(r){var n=e.split("."),u=n[0],c=n[1],f=n[2];if("ES256K-R"!==JSON.parse(t.decode(u)).alg)throw new Error("Expecteed header.alg to be ES256K-R");var a=Buffer.from(u+"."+c),s=i.createHash("sha256").update(a).digest(),l=t.toBuffer(f),p=o.signatureNormalize(l);return o.ecdsaVerify(p,s,r)}))}catch(e){return Promise.reject(e)}},signDetached:function(e,r,n){void 0===n&&(n={alg:"ES256K-R",b64:!1,crit:["b64"]});try{return Promise.resolve(B(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),l=s.recid,p=Buffer.concat([Buffer.from(s.signature),Buffer.from(new Uint8Array([l]))]);return u+".."+t.encode(p)}))}catch(e){return Promise.reject(e)}},recoverPublicKey:function(e,r){try{if(-1===e.indexOf(".."))throw new Error("not a valid rfc7797 jws.");var n=e.split(".."),u=n[0],c=n[1],f=JSON.parse(t.decode(u));if("ES256K-R"!==f.alg)throw new Error("JWS alg is not signed with ES256K-R.");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).");var a=Buffer.concat([Buffer.from(u+".","utf8"),Buffer.from(r.buffer,r.byteOffset,r.length)]),s=Buffer.from(a),l=new Uint8Array(i.createHash("sha256").update(s).digest()),p=new Uint8Array(t.toBuffer(c)),y=p[64];return p=p.slice(0,64),Promise.resolve(o.ecdsaRecover(p,y,l))}catch(e){return Promise.reject(e)}}};exports.Secp256k1KeyPair=v=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(b(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:"+v.fingerprintFromPublicKey({publicKeyBase58:n}),f="#"+v.fingerprintFromPublicKey({publicKeyBase58:n});return Promise.resolve(new v({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 v(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(S,e)}))}}();return n&&n.then?n.then(r):r()}var n=function(){if(e.privateKeyJwk){var r=P;return Promise.resolve(b(e.privateKeyJwk)).then((function(e){t=r.call(S,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:"+v.fingerprintFromPublicKey({publicKeyBase58:i}),u="#"+v.fingerprintFromPublicKey({publicKeyBase58:i});return new v({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 v.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 m(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(m(i.publicKeyBuffer.toString("hex"))).then((function(e){return r.call(S,e)}))},t=!1,i=this,n=function(){if(e){if(!i.privateKeyBuffer)throw new Error("No private key to export");t=!0;var r=b;return Promise.resolve(K(i.privateKeyBuffer.toString("hex"))).then((function(e){return r.call(S,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=v=c.__decorate([f.types.staticImplements()],exports.Secp256k1KeyPair);var _=f.getResolve(exports.Secp256k1KeyPair),E={__proto__:null,resolve:_,get:f.getGet(_)};exports.ES256K=J,exports.ES256KR=O,exports.driver=E,exports.keyUtils=S; | ||
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("@transmute/did-key-common"),r=require("@transmute/secp256k1-key-pair"),t=e.getGenerator(r.Secp256k1KeyPair),o=e.getResolver(r.Secp256k1KeyPair);Object.defineProperty(exports,"Secp256k1KeyPair",{enumerable:!0,get:function(){return r.Secp256k1KeyPair}}),exports.generate=t,exports.resolve=o; | ||
//# sourceMappingURL=did-key-secp256k1.cjs.production.min.js.map |
@@ -1,973 +0,9 @@ | ||
import keyto from '@trust/keyto'; | ||
import base64url from 'base64url'; | ||
import crypto from 'crypto'; | ||
import bs58 from 'bs58'; | ||
import secp256k1 from 'secp256k1'; | ||
import canonicalize from 'canonicalize'; | ||
import { __decorate } from 'tslib'; | ||
import { types, getResolve, getGet } from '@transmute/did-key-common'; | ||
import { getGenerator, getResolver } from '@transmute/did-key-common'; | ||
import { Secp256k1KeyPair } from '@transmute/secp256k1-key-pair'; | ||
export { Secp256k1KeyPair } from '@transmute/secp256k1-key-pair'; | ||
function _extends() { | ||
_extends = Object.assign || function (target) { | ||
for (var i = 1; i < arguments.length; i++) { | ||
var source = arguments[i]; | ||
var generate = /*#__PURE__*/getGenerator(Secp256k1KeyPair); | ||
var resolve = /*#__PURE__*/getResolver(Secp256k1KeyPair); | ||
for (var key in source) { | ||
if (Object.prototype.hasOwnProperty.call(source, key)) { | ||
target[key] = source[key]; | ||
} | ||
} | ||
} | ||
return target; | ||
}; | ||
return _extends.apply(this, arguments); | ||
} | ||
function _inheritsLoose(subClass, superClass) { | ||
subClass.prototype = Object.create(superClass.prototype); | ||
subClass.prototype.constructor = subClass; | ||
subClass.__proto__ = superClass; | ||
} | ||
function _getPrototypeOf(o) { | ||
_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { | ||
return o.__proto__ || Object.getPrototypeOf(o); | ||
}; | ||
return _getPrototypeOf(o); | ||
} | ||
function _setPrototypeOf(o, p) { | ||
_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { | ||
o.__proto__ = p; | ||
return o; | ||
}; | ||
return _setPrototypeOf(o, p); | ||
} | ||
function _isNativeReflectConstruct() { | ||
if (typeof Reflect === "undefined" || !Reflect.construct) return false; | ||
if (Reflect.construct.sham) return false; | ||
if (typeof Proxy === "function") return true; | ||
try { | ||
Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); | ||
return true; | ||
} catch (e) { | ||
return false; | ||
} | ||
} | ||
function _construct(Parent, args, Class) { | ||
if (_isNativeReflectConstruct()) { | ||
_construct = Reflect.construct; | ||
} else { | ||
_construct = function _construct(Parent, args, Class) { | ||
var a = [null]; | ||
a.push.apply(a, args); | ||
var Constructor = Function.bind.apply(Parent, a); | ||
var instance = new Constructor(); | ||
if (Class) _setPrototypeOf(instance, Class.prototype); | ||
return instance; | ||
}; | ||
} | ||
return _construct.apply(null, arguments); | ||
} | ||
function _isNativeFunction(fn) { | ||
return Function.toString.call(fn).indexOf("[native code]") !== -1; | ||
} | ||
function _wrapNativeSuper(Class) { | ||
var _cache = typeof Map === "function" ? new Map() : undefined; | ||
_wrapNativeSuper = function _wrapNativeSuper(Class) { | ||
if (Class === null || !_isNativeFunction(Class)) return Class; | ||
if (typeof Class !== "function") { | ||
throw new TypeError("Super expression must either be null or a function"); | ||
} | ||
if (typeof _cache !== "undefined") { | ||
if (_cache.has(Class)) return _cache.get(Class); | ||
_cache.set(Class, Wrapper); | ||
} | ||
function Wrapper() { | ||
return _construct(Class, arguments, _getPrototypeOf(this).constructor); | ||
} | ||
Wrapper.prototype = Object.create(Class.prototype, { | ||
constructor: { | ||
value: Wrapper, | ||
enumerable: false, | ||
writable: true, | ||
configurable: true | ||
} | ||
}); | ||
return _setPrototypeOf(Wrapper, Class); | ||
}; | ||
return _wrapNativeSuper(Class); | ||
} | ||
var compressedHexEncodedPublicKeyLength = 66; | ||
/** | ||
* Example | ||
* ```js | ||
* { | ||
* kty: 'EC', | ||
* crv: 'secp256k1', | ||
* d: 'rhYFsBPF9q3-uZThy7B3c4LDF_8wnozFUAEm5LLC4Zw', | ||
* x: 'dWCvM4fTdeM0KmloF57zxtBPXTOythHPMm1HCLrdd3A', | ||
* y: '36uMVGM7hnw-N6GnjFcihWE3SkrhMLzzLCdPMXPEXlA', | ||
* kid: 'JUvpllMEYUZ2joO59UNui_XYDqxVqiFLLAJ8klWuPBw' | ||
* } | ||
* ``` | ||
* See [rfc7638](https://tools.ietf.org/html/rfc7638) for more details on Jwk. | ||
*/ | ||
var getKid = function getKid(jwk) { | ||
var copy = _extends({}, jwk); | ||
delete copy.d; | ||
delete copy.kid; | ||
delete copy.alg; | ||
var digest = crypto.createHash('sha256').update(canonicalize(copy)).digest(); | ||
return base64url.encode(Buffer.from(digest)); | ||
}; | ||
/** convert compressed hex encoded private key to jwk */ | ||
var privateKeyJwkFromPrivateKeyHex = function privateKeyJwkFromPrivateKeyHex(privateKeyHex) { | ||
var jwk = _extends({}, keyto.from(privateKeyHex, 'blk').toJwk('private'), { | ||
crv: 'secp256k1' | ||
}); | ||
var kid = getKid(jwk); | ||
return _extends({}, jwk, { | ||
kid: kid | ||
}); | ||
}; | ||
/** convert compressed hex encoded public key to jwk */ | ||
var publicKeyJwkFromPublicKeyHex = function publicKeyJwkFromPublicKeyHex(publicKeyHex) { | ||
var key = publicKeyHex; | ||
if (publicKeyHex.length === compressedHexEncodedPublicKeyLength) { | ||
var keyBin = secp256k1.publicKeyConvert(Buffer.from(publicKeyHex, 'hex'), false); | ||
key = Buffer.from(keyBin).toString('hex'); | ||
} | ||
var jwk = _extends({}, keyto.from(key, 'blk').toJwk('public'), { | ||
crv: 'secp256k1' | ||
}); | ||
var kid = getKid(jwk); | ||
return _extends({}, jwk, { | ||
kid: kid | ||
}); | ||
}; | ||
/** convert pem encoded private key to jwk */ | ||
var privateKeyJwkFromPrivateKeyPem = function privateKeyJwkFromPrivateKeyPem(privateKeyPem) { | ||
var jwk = _extends({}, keyto.from(privateKeyPem, 'pem').toJwk('private'), { | ||
crv: 'secp256k1' | ||
}); // console.log(jwk); | ||
var kid = getKid(jwk); | ||
return _extends({}, jwk, { | ||
kid: kid | ||
}); | ||
}; | ||
/** convert pem encoded public key to jwk */ | ||
var publicKeyJwkFromPublicKeyPem = function publicKeyJwkFromPublicKeyPem(publicKeyPem) { | ||
var jwk = _extends({}, keyto.from(publicKeyPem, 'pem').toJwk('public'), { | ||
crv: 'secp256k1' | ||
}); | ||
var kid = getKid(jwk); | ||
return _extends({}, jwk, { | ||
kid: kid | ||
}); | ||
}; | ||
/** convert jwk to hex encoded private key */ | ||
var privateKeyHexFromJwk = function privateKeyHexFromJwk(jwk) { | ||
return keyto.from(_extends({}, jwk, { | ||
crv: 'K-256' | ||
}), 'jwk').toString('blk', 'private'); | ||
}; | ||
/** convert jwk to hex encoded public key */ | ||
var publicKeyHexFromJwk = function publicKeyHexFromJwk(jwk) { | ||
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'); | ||
}; | ||
/** convert jwk to binary encoded private key */ | ||
var privateKeyUInt8ArrayFromJwk = function privateKeyUInt8ArrayFromJwk(jwk) { | ||
var privateKeyHex = privateKeyHexFromJwk(jwk); | ||
var asBuffer = Buffer.from(privateKeyHex, 'hex'); | ||
var padding = 32 - asBuffer.length; | ||
while (padding > 0) { | ||
asBuffer = Buffer.concat([Buffer.from('00', 'hex'), asBuffer]); | ||
padding--; | ||
} | ||
return asBuffer; | ||
}; | ||
/** convert jwk to binary encoded public key */ | ||
var publicKeyUInt8ArrayFromJwk = function publicKeyUInt8ArrayFromJwk(jwk) { | ||
var publicKeyHex = publicKeyHexFromJwk(jwk); | ||
var asBuffer = Buffer.from(publicKeyHex, 'hex'); | ||
var padding = 32 - asBuffer.length; | ||
while (padding > 0) { | ||
asBuffer = Buffer.concat([Buffer.from('00', 'hex'), asBuffer]); | ||
padding--; | ||
} | ||
return asBuffer; | ||
}; | ||
/** convert publicKeyHex to base58 */ | ||
var publicKeyBase58FromPublicKeyHex = function publicKeyBase58FromPublicKeyHex(publicKeyHex) { | ||
return bs58.encode(Buffer.from(publicKeyHex, 'hex')); | ||
}; | ||
/** convert publicKeyHex to base58 */ | ||
var privateKeyBase58FromPrivateKeyHex = function privateKeyBase58FromPrivateKeyHex(privateKeyHex) { | ||
return bs58.encode(Buffer.from(privateKeyHex, 'hex')); | ||
}; | ||
var privateKeyUInt8ArrayFromPrivateKeyBase58 = function privateKeyUInt8ArrayFromPrivateKeyBase58(privateKeyBase58) { | ||
return bs58.decode(privateKeyBase58); | ||
}; | ||
var publicKeyUInt8ArrayFromPublicKeyBase58 = function publicKeyUInt8ArrayFromPublicKeyBase58(publicKeyBase58) { | ||
return bs58.decode(publicKeyBase58); | ||
}; | ||
var publicKeyHexFromPrivateKeyHex = function publicKeyHexFromPrivateKeyHex(privateKeyHex) { | ||
var publicKey = secp256k1.publicKeyCreate(new Uint8Array(Buffer.from(privateKeyHex, 'hex'))); | ||
return Buffer.from(publicKey).toString('hex'); | ||
}; | ||
var publicKeyJwkFromPublicKeyBase58 = function publicKeyJwkFromPublicKeyBase58(publicKeybase58) { | ||
return publicKeyJwkFromPublicKeyHex(bs58.decode(publicKeybase58).toString('hex')); | ||
}; | ||
var privateKeyJwkFromPrivateKeyBase58 = function privateKeyJwkFromPrivateKeyBase58(privateKeyBase58) { | ||
return privateKeyJwkFromPrivateKeyHex(bs58.decode(privateKeyBase58).toString('hex')); | ||
}; | ||
var keyUtils = { | ||
__proto__: null, | ||
getKid: getKid, | ||
privateKeyJwkFromPrivateKeyHex: privateKeyJwkFromPrivateKeyHex, | ||
publicKeyJwkFromPublicKeyHex: publicKeyJwkFromPublicKeyHex, | ||
privateKeyJwkFromPrivateKeyPem: privateKeyJwkFromPrivateKeyPem, | ||
publicKeyJwkFromPublicKeyPem: publicKeyJwkFromPublicKeyPem, | ||
privateKeyHexFromJwk: privateKeyHexFromJwk, | ||
publicKeyHexFromJwk: publicKeyHexFromJwk, | ||
privateKeyUInt8ArrayFromJwk: privateKeyUInt8ArrayFromJwk, | ||
publicKeyUInt8ArrayFromJwk: publicKeyUInt8ArrayFromJwk, | ||
publicKeyBase58FromPublicKeyHex: publicKeyBase58FromPublicKeyHex, | ||
privateKeyBase58FromPrivateKeyHex: privateKeyBase58FromPrivateKeyHex, | ||
privateKeyUInt8ArrayFromPrivateKeyBase58: privateKeyUInt8ArrayFromPrivateKeyBase58, | ||
publicKeyUInt8ArrayFromPublicKeyBase58: publicKeyUInt8ArrayFromPublicKeyBase58, | ||
publicKeyHexFromPrivateKeyHex: publicKeyHexFromPrivateKeyHex, | ||
publicKeyJwkFromPublicKeyBase58: publicKeyJwkFromPublicKeyBase58, | ||
privateKeyJwkFromPrivateKeyBase58: privateKeyJwkFromPrivateKeyBase58 | ||
}; | ||
/** error matching @panva/jose for JWS verification failure. */ | ||
var JWSVerificationFailed = /*#__PURE__*/function (_Error) { | ||
_inheritsLoose(JWSVerificationFailed, _Error); | ||
function JWSVerificationFailed(message) { | ||
var _this; | ||
_this = _Error.call(this, message) || this; | ||
_this.name = 'JWSVerificationFailed'; | ||
return _this; | ||
} | ||
return JWSVerificationFailed; | ||
}( /*#__PURE__*/_wrapNativeSuper(Error)); | ||
/** Produce a JWS Unencoded Payload per https://tools.ietf.org/html/rfc7797#section-6 */ | ||
var signDetached = function signDetached( // in the case of EcdsaSecp256k1Signature2019 this is the result of createVerifyData | ||
payload, privateKeyJwk, header) { | ||
if (header === void 0) { | ||
header = { | ||
alg: 'ES256K', | ||
b64: false, | ||
crit: ['b64'] | ||
}; | ||
} | ||
try { | ||
return Promise.resolve(privateKeyUInt8ArrayFromJwk(privateKeyJwk)).then(function (privateKeyUInt8Array) { | ||
var encodedHeader = base64url.encode(JSON.stringify(header)); | ||
var toBeSignedBuffer = Buffer.concat([Buffer.from(encodedHeader + '.', 'utf8'), Buffer.from(payload.buffer, payload.byteOffset, payload.length)]); | ||
var message = Buffer.from(toBeSignedBuffer); | ||
var digest = crypto.createHash('sha256').update(message).digest(); | ||
var messageHashUInt8Array = digest; | ||
var sigObj = secp256k1.ecdsaSign(messageHashUInt8Array, privateKeyUInt8Array); | ||
var encodedSignature = base64url.encode(Buffer.from(sigObj.signature)); | ||
return encodedHeader + ".." + encodedSignature; | ||
}); | ||
} catch (e) { | ||
return Promise.reject(e); | ||
} | ||
}; | ||
/** Verify a JWS Unencoded Payload per https://tools.ietf.org/html/rfc7797#section-6 */ | ||
var verifyDetached = function verifyDetached(jws, payload, publicKeyJwk) { | ||
try { | ||
if (jws.indexOf('..') === -1) { | ||
throw new JWSVerificationFailed('not a valid rfc7797 jws.'); | ||
} | ||
var _jws$split = jws.split('..'), | ||
encodedHeader = _jws$split[0], | ||
encodedSignature = _jws$split[1]; | ||
var header = JSON.parse(base64url.decode(encodedHeader)); | ||
if (header.alg !== 'ES256K') { | ||
throw new Error('JWS alg is not signed with ES256K.'); | ||
} | ||
if (header.b64 !== false || !header.crit || !header.crit.length || header.crit[0] !== 'b64') { | ||
throw new Error('JWS Header is not in rfc7797 format (not detached).'); | ||
} | ||
return Promise.resolve(publicKeyUInt8ArrayFromJwk(publicKeyJwk)).then(function (publicKeyUInt8Array) { | ||
var toBeSignedBuffer = Buffer.concat([Buffer.from(encodedHeader + '.', 'utf8'), Buffer.from(payload.buffer, payload.byteOffset, payload.length)]); | ||
var message = Buffer.from(toBeSignedBuffer); | ||
var digest = crypto.createHash('sha256').update(message).digest(); | ||
var messageHashUInt8Array = digest; | ||
var signatureUInt8Array = base64url.toBuffer(encodedSignature); | ||
var signatureLowerS = secp256k1.signatureNormalize(signatureUInt8Array); | ||
var verified = secp256k1.ecdsaVerify(signatureLowerS, messageHashUInt8Array, publicKeyUInt8Array); | ||
return verified; | ||
}); | ||
} catch (e) { | ||
return Promise.reject(e); | ||
} | ||
}; | ||
/** Produce a normal ES256K JWS */ | ||
var sign = function sign(payload, privateKeyJwk, header) { | ||
if (header === void 0) { | ||
header = { | ||
alg: 'ES256K' | ||
}; | ||
} | ||
try { | ||
return Promise.resolve(privateKeyUInt8ArrayFromJwk(privateKeyJwk)).then(function (privateKeyUInt8Array) { | ||
var encodedHeader = base64url.encode(JSON.stringify(header)); | ||
var encodedPayload = base64url.encode(JSON.stringify(payload)); | ||
var toBeSigned = encodedHeader + "." + encodedPayload; | ||
var message = Buffer.from(toBeSigned); | ||
var digest = crypto.createHash('sha256').update(message).digest(); | ||
var messageHashUInt8Array = digest; | ||
var sigObj = secp256k1.ecdsaSign(messageHashUInt8Array, privateKeyUInt8Array); | ||
var encodedSignature = base64url.encode(sigObj.signature); | ||
return encodedHeader + "." + encodedPayload + "." + encodedSignature; | ||
}); | ||
} catch (e) { | ||
return Promise.reject(e); | ||
} | ||
}; | ||
/** Verify an ES256K JWS, returns the decoded object if successful, throws otherwise. */ | ||
var verify = function verify(jws, publicKeyJwk) { | ||
try { | ||
return Promise.resolve(publicKeyUInt8ArrayFromJwk(publicKeyJwk)).then(function (publicKeyUInt8Array) { | ||
var _jws$split2 = jws.split('.'), | ||
encodedHeader = _jws$split2[0], | ||
encodedPayload = _jws$split2[1], | ||
encodedSignature = _jws$split2[2]; | ||
var toBeSigned = encodedHeader + "." + encodedPayload; | ||
var message = Buffer.from(toBeSigned); | ||
var digest = crypto.createHash('sha256').update(message).digest(); | ||
var messageHashUInt8Array = digest; | ||
var signatureUInt8Array = base64url.toBuffer(encodedSignature); | ||
var signatureLowerS = secp256k1.signatureNormalize(signatureUInt8Array); | ||
var verified = secp256k1.ecdsaVerify(signatureLowerS, messageHashUInt8Array, publicKeyUInt8Array); | ||
return verified; | ||
}); | ||
} catch (e) { | ||
return Promise.reject(e); | ||
} | ||
}; | ||
/** decode a JWS (without verifying it) */ | ||
var decode = function decode(jws, options) { | ||
if (options === void 0) { | ||
options = { | ||
complete: false | ||
}; | ||
} | ||
var _jws$split3 = jws.split('.'), | ||
encodedHeader = _jws$split3[0], | ||
encodedPayload = _jws$split3[1], | ||
encodedSignature = _jws$split3[2]; | ||
if (options.complete) { | ||
return { | ||
header: JSON.parse(base64url.decode(encodedHeader)), | ||
payload: JSON.parse(base64url.decode(encodedPayload)), | ||
signature: encodedSignature | ||
}; | ||
} | ||
return JSON.parse(base64url.decode(encodedPayload)); | ||
}; | ||
var ES256K = { | ||
__proto__: null, | ||
signDetached: signDetached, | ||
verifyDetached: verifyDetached, | ||
sign: sign, | ||
verify: verify, | ||
decode: decode | ||
}; | ||
var sign$1 = function sign(payload, privateKeyJwk, header) { | ||
if (header === void 0) { | ||
header = { | ||
alg: 'ES256K-R' | ||
}; | ||
} | ||
try { | ||
return Promise.resolve(privateKeyUInt8ArrayFromJwk(privateKeyJwk)).then(function (privateKeyUInt8Array) { | ||
var encodedHeader = base64url.encode(JSON.stringify(header)); | ||
var encodedPayload = base64url.encode(JSON.stringify(payload)); | ||
var toBeSigned = encodedHeader + "." + encodedPayload; | ||
var message = Buffer.from(toBeSigned); | ||
var digest = crypto.createHash('sha256').update(message).digest(); | ||
var messageHashUInt8Array = digest; | ||
var sigObj = secp256k1.ecdsaSign(messageHashUInt8Array, privateKeyUInt8Array); | ||
var encodedSignature = base64url.encode(sigObj.signature); | ||
return encodedHeader + "." + encodedPayload + "." + encodedSignature; | ||
}); | ||
} catch (e) { | ||
return Promise.reject(e); | ||
} | ||
}; | ||
var verify$1 = function verify(jws, publicKeyJwk) { | ||
try { | ||
return Promise.resolve(publicKeyUInt8ArrayFromJwk(publicKeyJwk)).then(function (publicKeyUInt8Array) { | ||
var _jws$split = jws.split('.'), | ||
encodedHeader = _jws$split[0], | ||
encodedPayload = _jws$split[1], | ||
encodedSignature = _jws$split[2]; | ||
var header = JSON.parse(base64url.decode(encodedHeader)); | ||
if (header.alg !== 'ES256K-R') { | ||
throw new Error('Expecteed header.alg to be ES256K-R'); | ||
} | ||
var toBeSigned = encodedHeader + "." + encodedPayload; | ||
var message = Buffer.from(toBeSigned); | ||
var digest = crypto.createHash('sha256').update(message).digest(); | ||
var messageHashUInt8Array = digest; | ||
var signatureUInt8Array = base64url.toBuffer(encodedSignature); | ||
var signatureLowerS = secp256k1.signatureNormalize(signatureUInt8Array); | ||
var verified = secp256k1.ecdsaVerify(signatureLowerS, messageHashUInt8Array, publicKeyUInt8Array); | ||
return verified; | ||
}); | ||
} catch (e) { | ||
return Promise.reject(e); | ||
} | ||
}; | ||
var signDetached$1 = function signDetached(payload, privateKeyJwk, header) { | ||
if (header === void 0) { | ||
header = { | ||
alg: 'ES256K-R', | ||
b64: false, | ||
crit: ['b64'] | ||
}; | ||
} | ||
try { | ||
return Promise.resolve(privateKeyUInt8ArrayFromJwk(privateKeyJwk)).then(function (privateKeyUInt8Array) { | ||
var encodedHeader = base64url.encode(JSON.stringify(header)); | ||
var toBeSignedBuffer = Buffer.concat([Buffer.from(encodedHeader + '.', 'utf8'), Buffer.from(payload.buffer, payload.byteOffset, payload.length)]); | ||
var message = Buffer.from(toBeSignedBuffer); | ||
var digest = crypto.createHash('sha256').update(message).digest(); | ||
var messageHashUInt8Array = digest; | ||
var _secp256k1$ecdsaSign = secp256k1.ecdsaSign(messageHashUInt8Array, privateKeyUInt8Array), | ||
signature = _secp256k1$ecdsaSign.signature, | ||
recid = _secp256k1$ecdsaSign.recid; | ||
var signatureUInt8Array = Buffer.concat([Buffer.from(signature), Buffer.from(new Uint8Array([recid]))]); | ||
var encodedSignature = base64url.encode(signatureUInt8Array); | ||
return encodedHeader + ".." + encodedSignature; | ||
}); | ||
} catch (e) { | ||
return Promise.reject(e); | ||
} | ||
}; | ||
var recoverPublicKey = function recoverPublicKey(jws, payload) { | ||
try { | ||
if (jws.indexOf('..') === -1) { | ||
throw new Error('not a valid rfc7797 jws.'); | ||
} | ||
var _jws$split2 = jws.split('..'), | ||
encodedHeader = _jws$split2[0], | ||
encodedSignature = _jws$split2[1]; | ||
var header = JSON.parse(base64url.decode(encodedHeader)); | ||
if (header.alg !== 'ES256K-R') { | ||
throw new Error('JWS alg is not signed with ES256K-R.'); | ||
} | ||
if (header.b64 !== false || !header.crit || !header.crit.length || header.crit[0] !== 'b64') { | ||
throw new Error('JWS Header is not in rfc7797 format (not detached).'); | ||
} | ||
var toBeSignedBuffer = Buffer.concat([Buffer.from(encodedHeader + '.', 'utf8'), Buffer.from(payload.buffer, payload.byteOffset, payload.length)]); | ||
var message = Buffer.from(toBeSignedBuffer); | ||
var digest = new Uint8Array(crypto.createHash('sha256').update(message).digest()); | ||
var signatureUInt8Array = new Uint8Array(base64url.toBuffer(encodedSignature)); | ||
var recoveryId = signatureUInt8Array[64]; | ||
signatureUInt8Array = signatureUInt8Array.slice(0, 64); | ||
return Promise.resolve(secp256k1.ecdsaRecover(signatureUInt8Array, recoveryId, digest)); | ||
} catch (e) { | ||
return Promise.reject(e); | ||
} | ||
}; | ||
var ES256KR = { | ||
__proto__: null, | ||
sign: sign$1, | ||
verify: verify$1, | ||
signDetached: signDetached$1, | ||
recoverPublicKey: recoverPublicKey | ||
}; | ||
var Secp256k1KeyPair_1; | ||
var _generate = function _generate(secureRandom) { | ||
var privateKey; | ||
do { | ||
privateKey = secureRandom(); | ||
} while (!secp256k1.privateKeyVerify(privateKey)); | ||
var publicKey = secp256k1.publicKeyCreate(privateKey); | ||
return { | ||
publicKey: publicKey, | ||
privateKey: privateKey | ||
}; | ||
}; | ||
var Secp256k1KeyPair = Secp256k1KeyPair_1 = /*#__PURE__*/function () { | ||
function Secp256k1KeyPair(options) { | ||
if (options === void 0) { | ||
options = {}; | ||
} | ||
this.type = 'EcdsaSecp256k1VerificationKey2019'; | ||
this.id = options.id; | ||
this.controller = options.controller; | ||
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(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 | ||
// 0xe7 is Secp256k1 public key | ||
buffer[0] = 0xe7; // | ||
buffer[1] = 0x01; | ||
buffer.set(pubkeyBytes, 2); // prefix with `z` to indicate multi-base base58btc encoding | ||
return "z" + bs58.encode(buffer); | ||
}; | ||
Secp256k1KeyPair.generate = function generate(options) { | ||
if (options === void 0) { | ||
options = {}; | ||
} | ||
try { | ||
var privateKey; | ||
var publicKey; | ||
if (options.secureRandom) { | ||
var _generate2 = _generate(options.secureRandom); | ||
privateKey = _generate2.privateKey; | ||
publicKey = _generate2.publicKey; | ||
} | ||
if (!privateKey) { | ||
throw new Error('Cannot generate private key.'); | ||
} | ||
var publicKeyBase58 = publicKeyBase58FromPublicKeyHex(Buffer.from(publicKey).toString('hex')); | ||
var privateKeyBase58 = privateKeyBase58FromPrivateKeyHex(Buffer.from(privateKey).toString('hex')); | ||
var did = "did:key:" + Secp256k1KeyPair_1.fingerprintFromPublicKey({ | ||
publicKeyBase58: publicKeyBase58 | ||
}); | ||
var keyId = "#" + Secp256k1KeyPair_1.fingerprintFromPublicKey({ | ||
publicKeyBase58: publicKeyBase58 | ||
}); | ||
return Promise.resolve(new Secp256k1KeyPair_1({ | ||
id: keyId, | ||
controller: did, | ||
publicKeyBase58: publicKeyBase58, | ||
privateKeyBase58: privateKeyBase58 | ||
})); | ||
} catch (e) { | ||
return Promise.reject(e); | ||
} | ||
}; | ||
Secp256k1KeyPair.from = function from(options) { | ||
try { | ||
var _temp9 = function _temp9() { | ||
function _temp6() { | ||
function _temp4() { | ||
function _temp2() { | ||
return new Secp256k1KeyPair_1(_extends({}, options, { | ||
privateKeyBase58: privateKeyBase58, | ||
publicKeyBase58: publicKeyBase58 | ||
})); | ||
} | ||
var _temp = function () { | ||
if (options.publicKeyJwk) { | ||
var _privateKeyBase58From3 = privateKeyBase58FromPrivateKeyHex; | ||
return Promise.resolve(publicKeyHexFromJwk(options.publicKeyJwk)).then(function (_keyUtils$publicKeyHe) { | ||
publicKeyBase58 = _privateKeyBase58From3.call(keyUtils, _keyUtils$publicKeyHe); | ||
}); | ||
} | ||
}(); | ||
return _temp && _temp.then ? _temp.then(_temp2) : _temp2(_temp); | ||
} | ||
var _temp3 = function () { | ||
if (options.privateKeyJwk) { | ||
var _privateKeyBase58From4 = privateKeyBase58FromPrivateKeyHex; | ||
return Promise.resolve(privateKeyHexFromJwk(options.privateKeyJwk)).then(function (_keyUtils$privateKeyH) { | ||
privateKeyBase58 = _privateKeyBase58From4.call(keyUtils, _keyUtils$privateKeyH); | ||
}); | ||
} | ||
}(); | ||
return _temp3 && _temp3.then ? _temp3.then(_temp4) : _temp4(_temp3); | ||
} | ||
var _temp5 = function () { | ||
if (options.publicKeyHex) { | ||
return Promise.resolve(publicKeyBase58FromPublicKeyHex(options.publicKeyHex)).then(function (_keyUtils$publicKeyBa) { | ||
publicKeyBase58 = _keyUtils$publicKeyBa; | ||
}); | ||
} | ||
}(); | ||
return _temp5 && _temp5.then ? _temp5.then(_temp6) : _temp6(_temp5); | ||
}; | ||
var privateKeyBase58 = options.privateKeyBase58; | ||
var publicKeyBase58 = options.publicKeyBase58; | ||
var _temp10 = function () { | ||
if (options.privateKeyHex) { | ||
return Promise.resolve(privateKeyBase58FromPrivateKeyHex(options.privateKeyHex)).then(function (_keyUtils$privateKeyB) { | ||
privateKeyBase58 = _keyUtils$privateKeyB; | ||
}); | ||
} | ||
}(); | ||
return Promise.resolve(_temp10 && _temp10.then ? _temp10.then(_temp9) : _temp9(_temp10)); | ||
} catch (e) { | ||
return Promise.reject(e); | ||
} | ||
}; | ||
Secp256k1KeyPair.fromFingerprint = function fromFingerprint(_ref) { | ||
var fingerprint = _ref.fingerprint; | ||
// skip leading `z` that indicates base58 encoding | ||
var buffer = bs58.decode(fingerprint.substr(1)); // https://github.com/multiformats/multicodec/blob/master/table.csv#L77 | ||
if (buffer[0] === 0xe7 && buffer[1] === 0x01) { | ||
var publicKeyBase58 = bs58.encode(buffer.slice(2)); | ||
var did = "did:key:" + Secp256k1KeyPair_1.fingerprintFromPublicKey({ | ||
publicKeyBase58: publicKeyBase58 | ||
}); | ||
var keyId = "#" + Secp256k1KeyPair_1.fingerprintFromPublicKey({ | ||
publicKeyBase58: publicKeyBase58 | ||
}); | ||
return new Secp256k1KeyPair_1({ | ||
id: keyId, | ||
controller: did, | ||
publicKeyBase58: publicKeyBase58 | ||
}); | ||
} | ||
throw new Error("Unsupported Fingerprint Type: " + fingerprint); | ||
}; | ||
var _proto = Secp256k1KeyPair.prototype; | ||
_proto.publicNode = function publicNode() { | ||
return this.toKeyPair(false); | ||
}; | ||
_proto.signer = function signer() { | ||
if (!this.privateKeyBuffer) { | ||
throw new Error('No private key to sign with.'); | ||
} | ||
var privateKeyBuffer = this.privateKeyBuffer; | ||
return { | ||
sign: function sign(_ref2) { | ||
var data = _ref2.data; | ||
try { | ||
var messageHashUInt8Array = crypto.createHash('sha256').update(data).digest(); | ||
var sigObj = secp256k1.ecdsaSign(messageHashUInt8Array, new Uint8Array(privateKeyBuffer)); | ||
return Promise.resolve(sigObj.signature); | ||
} catch (e) { | ||
return Promise.reject(e); | ||
} | ||
} | ||
}; | ||
}; | ||
_proto.verifier = function verifier() { | ||
if (!this.publicKeyBuffer) { | ||
throw new Error('No public key to verify with.'); | ||
} | ||
var publicKeyBuffer = this.publicKeyBuffer; | ||
return { | ||
verify: function verify(_ref3) { | ||
var data = _ref3.data, | ||
signature = _ref3.signature; | ||
try { | ||
var messageHashUInt8Array = crypto.createHash('sha256').update(data).digest(); | ||
var verified = false; | ||
try { | ||
verified = secp256k1.ecdsaVerify(signature, messageHashUInt8Array, new Uint8Array(publicKeyBuffer)); | ||
} catch (e) { | ||
console.error('An error occurred when verifying signature: ', e); | ||
} | ||
return Promise.resolve(verified); | ||
} catch (e) { | ||
return Promise.reject(e); | ||
} | ||
} | ||
}; | ||
}; | ||
_proto.fingerprint = function fingerprint() { | ||
return Secp256k1KeyPair_1.fingerprintFromPublicKey({ | ||
publicKeyBase58: bs58.encode(this.publicKeyBuffer) | ||
}); | ||
}; | ||
_proto.verifyFingerprint = function verifyFingerprint(fingerprint) { | ||
// fingerprint should have `z` prefix indicating | ||
// that it's multi-base encoded | ||
if (!(typeof fingerprint === 'string' && fingerprint[0] === 'z')) { | ||
return { | ||
error: new Error('`fingerprint` must be a multibase encoded string.'), | ||
valid: false | ||
}; | ||
} | ||
var fingerprintBuffer; | ||
try { | ||
fingerprintBuffer = bs58.decode(fingerprint.slice(1)); | ||
} catch (e) { | ||
return { | ||
error: e, | ||
valid: false | ||
}; | ||
} | ||
var publicKeyBuffer = this.publicKeyBuffer; // validate the first two multicodec bytes 0xe701 | ||
var valid = fingerprintBuffer.slice(0, 2).toString('hex') === 'e701' && publicKeyBuffer.equals(fingerprintBuffer.slice(2)); | ||
if (!valid) { | ||
return { | ||
error: new Error('The fingerprint does not match the public key.'), | ||
valid: false | ||
}; | ||
} | ||
return { | ||
valid: valid | ||
}; | ||
}; | ||
_proto.toJwk = function toJwk(_private) { | ||
if (_private === void 0) { | ||
_private = false; | ||
} | ||
if (_private) { | ||
if (!this.privateKeyBuffer) { | ||
throw new Error('No private key to export'); | ||
} | ||
return privateKeyJwkFromPrivateKeyHex(this.privateKeyBuffer.toString('hex')); | ||
} | ||
return publicKeyJwkFromPublicKeyHex(this.publicKeyBuffer.toString('hex')); | ||
}; | ||
_proto.toHex = function toHex(_private) { | ||
if (_private === void 0) { | ||
_private = false; | ||
} | ||
try { | ||
var _temp13 = function _temp13(_result) { | ||
if (_exit2) return _result; | ||
var _publicKeyHexFromJwk = publicKeyHexFromJwk; | ||
return Promise.resolve(publicKeyJwkFromPublicKeyHex(_this2.publicKeyBuffer.toString('hex'))).then(function (_keyUtils$publicKeyJw) { | ||
return _publicKeyHexFromJwk.call(keyUtils, _keyUtils$publicKeyJw); | ||
}); | ||
}; | ||
var _exit2 = false; | ||
var _this2 = this; | ||
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(_this2.privateKeyBuffer.toString('hex'))).then(function (_keyUtils$privateKeyJ) { | ||
return _privateKeyHexFromJwk2.call(keyUtils, _keyUtils$privateKeyJ); | ||
}); | ||
} | ||
}(); | ||
return Promise.resolve(_temp14 && _temp14.then ? _temp14.then(_temp13) : _temp13(_temp14)); | ||
} catch (e) { | ||
return Promise.reject(e); | ||
} | ||
}; | ||
_proto.toKeyPair = function toKeyPair(exportPrivate) { | ||
if (exportPrivate === void 0) { | ||
exportPrivate = false; | ||
} | ||
var kp = { | ||
id: this.id, | ||
type: this.type, | ||
controller: this.controller, | ||
publicKeyBase58: bs58.encode(this.publicKeyBuffer) | ||
}; | ||
if (exportPrivate) { | ||
kp.privateKeyBase58 = bs58.encode(this.privateKeyBuffer); | ||
} | ||
return kp; | ||
}; | ||
_proto.toJsonWebKeyPair = function toJsonWebKeyPair(exportPrivate) { | ||
if (exportPrivate === void 0) { | ||
exportPrivate = false; | ||
} | ||
var kp = { | ||
id: this.id, | ||
type: 'JsonWebKey2020', | ||
controller: this.controller, | ||
publicKeyJwk: this.toJwk() | ||
}; | ||
delete kp.publicKeyJwk.kid; | ||
if (exportPrivate) { | ||
kp.privateKeyJwk = this.toJwk(true); | ||
delete kp.privateKeyJwk.kid; | ||
} | ||
return kp; | ||
}; | ||
return Secp256k1KeyPair; | ||
}(); | ||
Secp256k1KeyPair = Secp256k1KeyPair_1 = /*#__PURE__*/__decorate([/*#__PURE__*/types.staticImplements()], Secp256k1KeyPair); | ||
var resolve = /*#__PURE__*/getResolve(Secp256k1KeyPair); | ||
var get = /*#__PURE__*/getGet(resolve); | ||
var driver = { | ||
__proto__: null, | ||
resolve: resolve, | ||
get: get | ||
}; | ||
export { ES256K, ES256KR, Secp256k1KeyPair, driver, keyUtils }; | ||
export { generate, resolve }; | ||
//# sourceMappingURL=did-key-secp256k1.esm.js.map |
@@ -1,6 +0,7 @@ | ||
import * as keyUtils from './keyUtils'; | ||
import * as ES256K from './ES256K'; | ||
import * as ES256KR from './ES256K-R'; | ||
import * as driver from './driver'; | ||
export * from './Secp256k1KeyPair'; | ||
export { keyUtils, driver, ES256K, ES256KR }; | ||
import { Secp256k1KeyPair } from '@transmute/secp256k1-key-pair'; | ||
export { Secp256k1KeyPair }; | ||
export declare const generate: (keyGenOptions: any, resolutionOptions?: any) => Promise<{ | ||
didDocument: import("@transmute/did-key-common/dist/types").DidDocument; | ||
keys: any[]; | ||
}>; | ||
export declare const resolve: (did: string, options?: import("@transmute/did-key-common/dist/types").ResolutionOptions | undefined) => Promise<import("@transmute/did-key-common/dist/types").ResolutionResponse>; |
@@ -5,9 +5,15 @@ { | ||
"module": "dist/did-key-secp256k1.esm.js", | ||
"version": "0.2.1-unstable.42", | ||
"version": "0.3.0-unstable.0", | ||
"license": "Apache-2.0", | ||
"main": "dist/index.js", | ||
"typings": "dist/index.d.ts", | ||
"publishConfig": { | ||
"access": "public" | ||
}, | ||
"license": "Apache-2.0", | ||
"main": "dist/index.js", | ||
"typings": "dist/index.d.ts", | ||
"homepage": "https://github.com/transmute-industries/did-key.js/tree/master/packages/did-key-secp256k1", | ||
"repository": { | ||
"type": "git", | ||
"url": "https://github.com/transmute-industries/did-key.js.git", | ||
"directory": "packages/did-key-secp256k1" | ||
}, | ||
"files": [ | ||
@@ -18,4 +24,14 @@ "dist", | ||
"engines": { | ||
"node": ">=10" | ||
"node": ">=14" | ||
}, | ||
"size-limit": [ | ||
{ | ||
"path": "dist/did-key-secp256k1.cjs.production.min.js", | ||
"limit": "10 KB" | ||
}, | ||
{ | ||
"path": "dist/did-key-secp256k1.esm.js", | ||
"limit": "10 KB" | ||
} | ||
], | ||
"scripts": { | ||
@@ -26,27 +42,26 @@ "start": "tsdx watch", | ||
"lint": "tsdx lint src --fix", | ||
"prepare": "tsdx build" | ||
"prepare": "tsdx build", | ||
"size": "size-limit", | ||
"analyze": "size-limit --why" | ||
}, | ||
"devDependencies": { | ||
"@transmute/did-key-test-vectors": "^0.2.1-unstable.42", | ||
"bitcoin-ts": "1.14.2", | ||
"jose": "^1.28.1", | ||
"tsdx": "^0.13.2", | ||
"tslib": "^2.0.0", | ||
"typescript": "^3.9.5" | ||
"@size-limit/preset-small-lib": "^4.12.0", | ||
"@transmute/credentials-context": "^0.7.0-unstable.1", | ||
"@transmute/did-context": "^0.7.0-unstable.1", | ||
"@transmute/jose-ld": "^0.7.0-unstable.1", | ||
"@transmute/json-web-signature": "^0.7.0-unstable.1", | ||
"@transmute/security-context": "^0.7.0-unstable.1", | ||
"@transmute/vc.js": "^0.2.1-unstable.12", | ||
"axios": "^0.21.1", | ||
"size-limit": "^4.12.0", | ||
"ts-jest": "^27.0.3", | ||
"tsdx": "^0.14.1", | ||
"tslib": "^2.3.0", | ||
"typescript": "^4.3.4" | ||
}, | ||
"dependencies": { | ||
"@transmute/did-key-common": "^0.2.1-unstable.42", | ||
"@trust/keyto": "^1.0.1", | ||
"base64url": "^3.0.1", | ||
"bs58": "^4.0.1", | ||
"canonicalize": "^1.0.1", | ||
"secp256k1": "^4.0.1" | ||
"@transmute/did-key-common": "^0.3.0-unstable.0", | ||
"@transmute/secp256k1-key-pair": "^0.7.0-unstable.2" | ||
}, | ||
"homepage": "https://github.com/transmute-industries/did-key.js/tree/master/packages/secp256k1", | ||
"repository": { | ||
"type": "git", | ||
"url": "https://github.com/transmute-industries/did-key.js.git", | ||
"directory": "packages/secp256k1" | ||
}, | ||
"gitHead": "9a47e6f1ec77f9a23fb16d43113560d24878b74b" | ||
"gitHead": "3bc0d6fae9336b1f7ba89b757d3f695ceb60244e" | ||
} |
175
README.md
@@ -1,2 +0,2 @@ | ||
# @transmute/did-key-secp256k1 | ||
# did-key-secp256k1 | ||
@@ -7,4 +7,173 @@ ``` | ||
# TODO | ||
## Usage | ||
- More documentation. | ||
### Generate | ||
```ts | ||
import crypto from 'crypto'; | ||
import * as secp256k1 from '@transmute/did-key-secp256k1'; | ||
const { didDocument, keys } = await secp256k1.generate( | ||
{ | ||
secureRandom: () => { | ||
return crypto.randomBytes(32); | ||
}, | ||
}, | ||
{ accept: 'application/did+json' } | ||
); | ||
``` | ||
### Export | ||
```ts | ||
import { Secp256k1KeyPair } from '@transmute/did-key-secp256k1'; | ||
const k = await Secp256k1KeyPair.generate({ | ||
secureRandom: () => { | ||
return Buffer.from( | ||
'9085d2bef69286a6cbb51623c8fa258629945cd55ca705cc4e66700396894e0c', | ||
'hex' | ||
); | ||
}, | ||
}); | ||
const exportedKeyPair = await k.export({ | ||
type: 'JsonWebKey2020', | ||
privateKey: true, | ||
}); | ||
``` | ||
### Resolve | ||
```ts | ||
import * as secp256k1 from '@transmute/did-key-secp256k1'; | ||
const { | ||
didDocument, | ||
} = await secp256k1.resolve( | ||
'did:key:z6LScNhBGJJHGPgx9AMCHjxFew9qfbAZhsi1KyJYcfdcFQ9k', | ||
{ accept: 'application/did+json' } | ||
); | ||
``` | ||
#### JsonWebSignature2020 | ||
This suite was created after `https://www.w3.org/2018/credentials/v1` so it must be added to the credential context. | ||
```ts | ||
import { ld as vcjs } from '@transmute/vc.js'; | ||
import { Secp256k1KeyPair } from '@transmute/did-key-secp256k1'; | ||
import { JsonWebSignature, JsonWebKey } from '@transmute/json-web-signature'; | ||
const k = await Secp256k1KeyPair.generate({ | ||
secureRandom: () => { | ||
return Buffer.from( | ||
'4e61bc1918ea6a47ae3307331be7798196a1a8e7cfe4b6e8f7c9a5f36017d929', | ||
'hex' | ||
); | ||
}, | ||
}); | ||
const suite = new JsonWebSignature({ | ||
key: await JsonWebKey.from( | ||
await k.export({ | ||
type: 'JsonWebSignature2020', | ||
privateKey: true, | ||
}) | ||
), | ||
date: '2020-03-10T04:24:12Z', | ||
}); | ||
const vc = await vcjs.issue({ | ||
credential: { | ||
'@context': [ | ||
'https://www.w3.org/2018/credentials/v1', | ||
// 🧙♂️ This extension context is required. | ||
'https://w3id.org/security/suites/jws-2020/v1', | ||
], | ||
id: 'http://example.gov/credentials/3732', | ||
type: ['VerifiableCredential'], | ||
issuer: { | ||
id: k.controller, | ||
}, | ||
issuanceDate: '2020-03-10T04:24:12.164Z', | ||
credentialSubject: { | ||
id: 'did:example:ebfeb1f712ebc6f1c276e12ec21', | ||
}, | ||
}, | ||
suite, | ||
documentLoader, | ||
}); | ||
``` | ||
### JOSE | ||
#### ECDSA | ||
```ts | ||
import { Secp256k1KeyPair } from '@transmute/did-key-secp256k1'; | ||
import { JWS } from '@transmute/jose-ld'; | ||
const k = await Secp256k1KeyPair.generate({ | ||
secureRandom: () => { | ||
return Buffer.from( | ||
'4e61bc1918ea6a47ae3307331be7798196a1a8e7cfe4b6e8f7c9a5f36017d929', | ||
'hex' | ||
); | ||
}, | ||
}); | ||
const JWA_ALG = 'ES256K'; | ||
const signer = JWS.createSigner(k.signer('Ecdsa'), JWA_ALG); | ||
const verifier = JWS.createVerifier(k.verifier('Ecdsa'), JWA_ALG); | ||
const message = Uint8Array.from(Buffer.from('hello')); | ||
const signature = await signer.sign({ data: message }); | ||
const verified = await verifier.verify({ | ||
signature, | ||
}); | ||
``` | ||
#### ECDH-ES+A256KW | ||
```ts | ||
import { Secp256k1KeyPair } from '@transmute/did-key-secp256k1'; | ||
import { JWE } from '@transmute/jose-ld'; | ||
const k = await Secp256k1KeyPair.generate({ | ||
secureRandom: () => { | ||
return Buffer.from( | ||
'9085d2bef69286a6cbb51623c8fa258629945cd55ca705cc4e66700396894e0c', | ||
'hex' | ||
); | ||
}, | ||
}); | ||
const cipher = new JWE.Cipher(Secp256k1KeyPair); | ||
const document = { key1: 'value1', key2: 'value2' }; | ||
const recipients = [ | ||
{ | ||
header: { | ||
kid: k.id, | ||
alg: 'ECDH-ES+A256KW', | ||
}, | ||
}, | ||
]; | ||
const jwe = await cipher.encryptObject({ | ||
obj: document, | ||
recipients, | ||
publicKeyResolver: async (id: string) => { | ||
if (id === k.id) { | ||
return k.export({ type: 'JsonWebKey2020' }); | ||
} | ||
throw new Error( | ||
'publicKeyResolver does not suppport IRI ' + JSON.stringify(id) | ||
); | ||
}, | ||
}); | ||
const plaintext = await cipher.decrypt({ jwe, keyAgreementKey: k }); | ||
console.log(JSON.parse(Buffer.from(plaintext).toString('utf-8'))); | ||
``` | ||
## Representations | ||
#### application/did+json | ||
See [application/did+json](./src/__tests__/generate/__fixtures__/doc-0.json) | ||
#### application/did+ld+json | ||
See [application/did+ld+json](./src/__tests__/generate/__fixtures__/doc-0.ld.json) |
@@ -1,7 +0,6 @@ | ||
import * as keyUtils from './keyUtils'; | ||
import * as ES256K from './ES256K'; | ||
import * as ES256KR from './ES256K-R'; | ||
import * as driver from './driver'; | ||
import { getGenerator, getResolver } from '@transmute/did-key-common'; | ||
import { Secp256k1KeyPair } from '@transmute/secp256k1-key-pair'; | ||
export * from './Secp256k1KeyPair'; | ||
export { keyUtils, driver, ES256K, ES256KR }; | ||
export { Secp256k1KeyPair }; | ||
export const generate = getGenerator(Secp256k1KeyPair); | ||
export const resolve = getResolver(Secp256k1KeyPair); |
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
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
Major refactor
Supply chain riskPackage has recently undergone a major refactor. It may be unstable or indicate significant internal changes. Use caution when updating to versions that include significant changes.
Found 1 instance in 1 package
Minified code
QualityThis package contains minified code. This may be harmless in some cases where minified code is included in packaged libraries, however packages on npm should not minify code.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
Minified code
QualityThis package contains minified code. This may be harmless in some cases where minified code is included in packaged libraries, however packages on npm should not minify code.
Found 1 instance in 1 package
No website
QualityPackage does not have a website.
Found 1 instance in 1 package
2
2
179
39764
13
550
1
+ Added@bitauth/libauth@1.19.1(transitive)
+ Added@did-core/data-model@0.1.1-unstable.15(transitive)
+ Added@did-core/did-ld-json@0.1.1-unstable.15(transitive)
+ Added@digitalbazaar/http-client@1.2.0(transitive)
+ Added@transmute/did-context@0.6.1-unstable.37(transitive)
+ Added@transmute/did-key-common@0.3.0-unstable.10(transitive)
+ Added@transmute/ld-key-pair@0.6.1-unstable.370.7.0-unstable.82(transitive)
+ Added@transmute/secp256k1-key-pair@0.7.0-unstable.82(transitive)
+ Added@transmute/security-context@0.6.1-unstable.37(transitive)
+ Addedabort-controller@3.0.0(transitive)
+ Addedbuffer-from@1.1.2(transitive)
+ Addedclone-deep@4.0.1(transitive)
+ Addeddata-uri-to-buffer@3.0.1(transitive)
+ Addedesm@3.2.25(transitive)
+ Addedevent-target-shim@5.0.1(transitive)
+ Addedfactory.ts@0.5.2(transitive)
+ Addedfetch-blob@2.1.2(transitive)
+ Addedis-plain-object@2.0.4(transitive)
+ Addedisobject@3.0.1(transitive)
+ Addedjsonld@5.2.0(transitive)
+ Addedjsonld-checker@0.1.8(transitive)
+ Addedkind-of@6.0.3(transitive)
+ Addedky@0.25.1(transitive)
+ Addedky-universal@0.8.2(transitive)
+ Addedlru-cache@6.0.0(transitive)
+ Addednode-fetch@2.7.03.0.0-beta.9(transitive)
+ Addedrdf-canonize@3.4.0(transitive)
+ Addedsetimmediate@1.0.5(transitive)
+ Addedshallow-clone@3.0.1(transitive)
+ Addedsource-map@0.6.1(transitive)
+ Addedsource-map-support@0.5.21(transitive)
+ Addedtr46@0.0.3(transitive)
+ Addedwebidl-conversions@3.0.1(transitive)
+ Addedwhatwg-url@5.0.0(transitive)
+ Addedyallist@4.0.0(transitive)
- Removed@trust/keyto@^1.0.1
- Removedbase64url@^3.0.1
- Removedbs58@^4.0.1
- Removedcanonicalize@^1.0.1
- Removedsecp256k1@^4.0.1
- Removed@transmute/did-key-common@0.2.1-unstable.42(transitive)
- Removed@trust/keyto@1.0.1(transitive)
- Removedasn1.js@5.4.1(transitive)
- Removedbase-x@3.0.10(transitive)
- Removedbase64-js@1.5.1(transitive)
- Removedbase64url@3.0.1(transitive)
- Removedbignumber.js@9.1.2(transitive)
- Removedborc@2.1.2(transitive)
- Removedbs58@4.0.1(transitive)
- Removedbuffer@5.7.1(transitive)
- Removedcbor@5.2.0(transitive)
- Removedcommander@2.20.3(transitive)
- Removeddelimit-stream@0.1.0(transitive)
- Removedieee754@1.2.1(transitive)
- Removediso-url@0.4.7(transitive)
- Removedjson-text-sequence@0.1.1(transitive)
- Removednofilter@1.0.4(transitive)
- Removedreadable-stream@3.6.2(transitive)
- Removedsafe-buffer@5.2.1(transitive)
- Removedsafer-buffer@2.1.2(transitive)
- Removedstring_decoder@1.3.0(transitive)
- Removedutil-deprecate@1.0.2(transitive)