import { sm2Curve } from './curve'; import { base58, base64url } from './encoding'; import { JsonWebKey2020, Sm2VerificationKey2019, Sm2VerificationKey2020, } from './types'; import { getMultibaseFingerprintFromPublicKeyBytes } from './getMultibaseFingerprintFromPublicKeyBytes'; export const toJsonWebKey2020 = ( id: string, controller: string, publicKey: Uint8Array, privateKey?: Uint8Array, _alg?: string ) => { const { px, py } = sm2Curve.ProjectivePoint.fromHex(publicKey); const publicKeyJwk = { kty: 'EC', crv: 'SM2', x: base64url.encode(Buffer.from(px.toString(16), 'hex')), y: base64url.encode(Buffer.from(py.toString(16), 'hex')), }; const k: JsonWebKey2020 = { id: id, type: 'JsonWebKey2020', controller: controller, publicKeyJwk, }; if (privateKey) { k.privateKeyJwk = { ...publicKeyJwk, d: base64url.encode(privateKey), }; } return k; }; export const toSm2VerificationKey2019 = ( id: string, controller: string, publicKey: Uint8Array, privateKey?: Uint8Array ) => { const k: Sm2VerificationKey2019 = { id: id, type: 'Sm2VerificationKey2019', controller: controller, publicKeyBase58: base58.encode(publicKey), }; if (privateKey) { k.privateKeyBase58 = base58.encode(privateKey); } return k; }; export const toSm2VerificationKey2020 = ( id: string, controller: string, publicKey: Uint8Array, privateKey?: Uint8Array ) => { const k: Sm2VerificationKey2020 = { id: id, type: 'Sm2VerificationKey2020', controller: controller, publicKeyMultibase: getMultibaseFingerprintFromPublicKeyBytes(publicKey), }; if (privateKey) { throw new Error( 'Unable to represent sm2 private key in multibase. See https://github.com/multiformats/multicodec/pull/210' ); } return k; }; export const exportableTypes = { JsonWebKey2020: toJsonWebKey2020, Sm2VerificationKey2020: toSm2VerificationKey2020, Sm2VerificationKey2019: toSm2VerificationKey2019, };