diff --git a/packages/key-utils/src/functions.ts b/packages/key-utils/src/functions.ts index 89838e83..b6c65afa 100644 --- a/packages/key-utils/src/functions.ts +++ b/packages/key-utils/src/functions.ts @@ -350,3 +350,38 @@ export const padLeft = (args: { data: string; size?: number; padString?: string const length = padString.length return padString.repeat((size - data.length) / length) + data } + + +/** + * This function converts a DER encoded ASN.1 formatted public key to a raw public key + * @param derKey + */ +export const rawPublicKeyHexFromAsn1Der = (derKey: Uint8Array): string => { + if (derKey[0] !== 0x30) { + throw new Error('Invalid DER encoding: Expected to start with sequence tag') + } + + // Find the start of the bit string containing the public key + let index = 2 // Skip sequence tag and length + while (index < derKey.length) { + if (derKey[index] === 0x03) { // Bit string tag + break + } + index++ + } + + if (index >= derKey.length) { + throw new Error('Invalid DER encoding: Bit string not found') + } + + // Skip bit string tag and length + index += 2 + + // Skip unused bits byte + index++ + + // Convert the remaining bytes to a hex string + return Array.from(derKey.slice(index)) + .map(byte => byte.toString(16).padStart(2, '0')) + .join('') +} diff --git a/packages/kms-musap-rn/src/MusapKeyManagerSystem.ts b/packages/kms-musap-rn/src/MusapKeyManagerSystem.ts index 60290fa5..d318cf64 100644 --- a/packages/kms-musap-rn/src/MusapKeyManagerSystem.ts +++ b/packages/kms-musap-rn/src/MusapKeyManagerSystem.ts @@ -15,7 +15,7 @@ import { AbstractKeyManagementSystem } from '@veramo/key-manager' import { TextDecoder } from 'text-encoding' import { Loggers } from '@sphereon/ssi-types' import { KeyMetadata } from './index' -import { PEMToHex } from '@sphereon/ssi-sdk-ext.key-utils' +import { rawPublicKeyHexFromAsn1Der } from '@sphereon/ssi-sdk-ext.key-utils' export const logger = Loggers.DEFAULT.get('sphereon:musap-rn-kms') @@ -133,7 +133,7 @@ export class MusapKeyManagementSystem extends AbstractKeyManagementSystem { const keyInfo: Partial = { kid: args.keyId, type: this.mapAlgorithmTypeToKeyType(args.algorithm), - publicKeyHex: PEMToHex( args.publicKey.pem), + publicKeyHex: rawPublicKeyHexFromAsn1Der(args.publicKey.der), meta: { ...args, },