Skip to content

Commit

Permalink
Added secp1256k provider
Browse files Browse the repository at this point in the history
  • Loading branch information
Kolezhniuk committed Apr 9, 2023
1 parent 13e0db0 commit a495ed4
Show file tree
Hide file tree
Showing 30 changed files with 200 additions and 243 deletions.
2 changes: 1 addition & 1 deletion .eslintrc
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
"parser": "@typescript-eslint/parser",
"plugins": ["@typescript-eslint", "prettier"],
"parserOptions": {
"project": ["tsconfig.json"]
"project": ["tsconfig.json", "tsconfig.test.json"]
},
"extends": [
"eslint:recommended",
Expand Down
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion src/iden3comm/handlers/auth.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { byteDecoder, byteEncoder } from '../utils/index';
import { MediaType } from '../constants';
import { CircuitId } from '../../circuits/models';
import { IProofService } from '../../proof/proof-service';
Expand All @@ -19,6 +18,7 @@ import { proving } from '@iden3/js-jwz';
import * as uuid from 'uuid';
import { ICredentialWallet } from '../../credentials';
import { W3CCredential } from '../../verifiable';
import { byteDecoder, byteEncoder } from '../../utils';

/**
* ZKP request and credential that satisfies the zkp query conditions
Expand Down
2 changes: 1 addition & 1 deletion src/iden3comm/handlers/fetch.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { byteDecoder, byteEncoder } from '../utils/index';
import { MediaType } from '../constants';
import { PROTOCOL_MESSAGE_TYPE } from '../constants';

Expand All @@ -14,6 +13,7 @@ import { proving } from '@iden3/js-jwz';
import * as uuid from 'uuid';
import { W3CCredential } from '../../verifiable';
import axios from 'axios';
import { byteDecoder, byteEncoder } from '../../utils';

/**
* Interface that allows the processing of the credential offer in the raw format for given identifier
Expand Down
2 changes: 1 addition & 1 deletion src/iden3comm/packageManager.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { BasicMessage, IPackageManager, IPacker, PackerParams } from './types';
import { bytesToHeaderStub } from './utils/envelope';
import { base64 } from 'rfc4648';
import { byteEncoder, byteDecoder } from './utils';
import { MediaType } from './constants';
import { byteDecoder, byteEncoder } from '../utils';

/**
* Basic package manager for iden3 communication protocol
Expand Down
108 changes: 33 additions & 75 deletions src/iden3comm/packers/jws.ts
Original file line number Diff line number Diff line change
@@ -1,27 +1,11 @@
import { BasicMessage, IPacker, PackerParams } from '../types';
import { byteDecoder, byteEncoder } from '../utils';
import { MediaType, SUPPORTED_PUBLIC_KEY_TYPES } from '../constants';
import {
bytesToHex,
encodeBase64url,
extractPublicKeyBytes,
getDIDComponentById,
hexToBytes,
resolveDIDDocument
} from '../utils/did';
import { AbstractPrivateKeyStore, keyPath, KmsKeyType } from '../../kms/';

import {
ES256KSigner,
ES256Signer,
EdDSASigner,
JWTHeader,
Signer,
createJWT,
decodeJWT,
verifyJWT
} from 'did-jwt';
import { extractPublicKeyBytes, getDIDComponentById, resolveDIDDocument } from '../utils/did';
import { keyPath, KMS } from '../../kms/';

import { Signer, decodeJWT, verifyJWT } from 'did-jwt';
import { Resolvable, VerificationMethod } from 'did-resolver';
import { byteDecoder, byteEncoder, bytesToHex, encodeBase64url } from '../../utils';
export type SignerFn = (vm: VerificationMethod, data: Uint8Array) => Signer;

/**
Expand All @@ -33,18 +17,6 @@ export type SignerFn = (vm: VerificationMethod, data: Uint8Array) => Signer;
* @implements implements IPacker interface
*/
export class JWSPacker implements IPacker {
readonly signerAlgs: { [k: string]: (sk: Uint8Array) => Signer } = {
ES256: (sk: Uint8Array) => ES256Signer(sk),
ES256K: (sk: Uint8Array) => ES256KSigner(sk),
'ES256K-R': (sk: Uint8Array) => ES256KSigner(sk, true),
Ed25519: (sk: Uint8Array) => EdDSASigner(sk),
EdDSA: (sk: Uint8Array) => EdDSASigner(sk)
};
readonly algToProviderKeyType = {
ES256K: KmsKeyType.Secp256k1,
'ES256-R': KmsKeyType.Secp256k1
};

// readonly vmPubkeyExtractorHandlerMap = {
// ES256K: getPubKeyHexFromVm,
// 'ES256K-R': getPubKeyHexFromVm
Expand All @@ -56,7 +28,7 @@ export class JWSPacker implements IPacker {
// };

constructor(
private readonly _keyStore: AbstractPrivateKeyStore,
private readonly _kms: KMS,
private readonly _documentResolver: Resolvable = { resolve: resolveDIDDocument }
) {}
/**
Expand All @@ -75,6 +47,9 @@ export class JWSPacker implements IPacker {
signer?: SignerFn;
}
): Promise<Uint8Array> {
if (!params.alg) {
throw new Error('Missing algorithm');
}
const message = JSON.parse(byteDecoder.decode(payload));

const from = message.from ?? '';
Expand Down Expand Up @@ -125,53 +100,38 @@ export class JWSPacker implements IPacker {

const kid = vm.id;

let signer: Signer;
const headerObj = { alg: params.alg, kid, typ: MediaType.SignedMessage };
const header = encodeBase64url(JSON.stringify(headerObj));
const msg = encodeBase64url(JSON.stringify(message));
// construct signing input and obtain signature
const signingInput = header + '.' + msg;
const signingInputBytes = byteEncoder.encode(signingInput);
let signatureHex: string;
if (params.signer) {
const headerObj = { alg: params.alg, kid, typ: MediaType.SignedMessage };
const header = encodeBase64url(JSON.stringify(headerObj));
const msg = encodeBase64url(JSON.stringify(message));
// construct signing input and obtain signature
const signingInput = byteEncoder.encode(`${header}.${msg}`);
signer = params.signer(vm, signingInput);
const signerFn = params.signer(vm, signingInputBytes);
signatureHex = (await signerFn(signingInput)).toString();
} else {
const keyType = this.algToProviderKeyType[params.alg];
if (!keyType) {
throw new Error(`Unsupported algorithm ${params.alg}`);
}
// console.log('pk', bytesToHex(extractPublicKeyBytes(vm)));

const sk = await this._keyStore.get({
alias: keyPath(keyType, bytesToHex(extractPublicKeyBytes(vm)))
});
const { publicKeyBytes, kmsKeyType } = extractPublicKeyBytes(vm);

const signerAlg = this.signerAlgs[params.alg];
if (!publicKeyBytes) {
throw new Error('No public key found');
}

if (!signerAlg) {
throw new Error(`Unsupported algorithm ${params.alg}`);
if (!kmsKeyType) {
throw new Error('No KMS key type found');
}

signer = signerAlg(hexToBytes(sk));

// const type = this.algToProviderKeyType[params.alg];
// if (!type) {
// throw new Error(`Unsupported algorithm ${params.alg}`);
// }
// const pkFn = this.vmPubkeyExtractorHandlerMap[params.alg];
// if (!pkFn) {
// throw new Error(`Unsupported detect public key fetcher ${params.alg}`);
// }
// signature = await this._kms.sign({ type, id: keyPath(type, pkFn(vm)) }, signingInput);
const signatureBytes = await this._kms.sign(
{ type: kmsKeyType, id: keyPath(kmsKeyType, bytesToHex(publicKeyBytes)) },
signingInputBytes
);

signatureHex = byteDecoder.decode(signatureBytes);
}
// const signatureBase64 = toBase64(BytesHelper.bytesToHex(signature));
// const tokenStr = `${header}.${msg}.${signatureBase64}`;
// console.log('tokenStr', tokenStr);
const jwt = await createJWT(message, { issuer: params.issuer, signer }, {
alg: params.alg,
kid,
typ: MediaType.SignedMessage
} as unknown as JWTHeader);

return byteEncoder.encode(jwt);
// const signature = encodeBase64url(signatureHex);

return byteEncoder.encode(signingInput + '.' + signatureHex);
}

/**
Expand All @@ -183,7 +143,6 @@ export class JWSPacker implements IPacker {
async unpack(envelope: Uint8Array): Promise<BasicMessage> {
const jwt = byteDecoder.decode(envelope);
const decoded = decodeJWT(jwt);
console.log('decoded', decoded);

const verificationResponse = await verifyJWT(jwt, {
resolver: this._documentResolver
Expand Down Expand Up @@ -218,7 +177,6 @@ export class JWSPacker implements IPacker {
// byteEncoder.encode(`${headerStr}.${msgStr}`),
// fromBase64(signature64)
// );
console.log(verificationResponse);
return {
id: decoded.payload.id,
typ: MediaType.SignedMessage
Expand Down
3 changes: 1 addition & 2 deletions src/iden3comm/packers/plain.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
import { PlainPackerParams } from './../types/packer';
import { byteEncoder } from './../utils/index';
import { BasicMessage, IPacker } from '../types';
import { byteDecoder } from '../utils';
import { MediaType } from '../constants';
import { byteDecoder, byteEncoder } from '../../utils';

/**
* Plain packer just serializes bytes to JSON and adds media type
Expand Down
3 changes: 1 addition & 2 deletions src/iden3comm/packers/zkp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,8 @@ import {
ErrStateVerificationFailed,
ErrUnknownCircuitID
} from '../errors';
import { byteDecoder, byteEncoder } from '../utils';
import { MediaType } from '../constants';
import { byteDecoder, byteEncoder } from '../../utils';

const { getProvingMethod } = proving;

Expand Down Expand Up @@ -180,7 +180,6 @@ const verifySender = (token: Token, msg: BasicMessage): void => {
};

const verifyAuthV2Sender = (from: string, pubSignals: Array<string>): boolean => {
const byteEncoder = new TextEncoder();
const authSignals = new AuthV2PubSignals();

const pubSig = authSignals.pubSignalsUnmarshal(byteEncoder.encode(JSON.stringify(pubSignals)));
Expand Down
21 changes: 0 additions & 21 deletions src/iden3comm/utils/bytes.ts

This file was deleted.

Loading

0 comments on commit a495ed4

Please sign in to comment.