Skip to content

Commit

Permalink
chore: added rawPublicKeyHexFromAsn1Der function
Browse files Browse the repository at this point in the history
  • Loading branch information
sanderPostma committed Aug 1, 2024
1 parent 56fc7da commit da9ee27
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 2 deletions.
35 changes: 35 additions & 0 deletions packages/key-utils/src/functions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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('')
}
4 changes: 2 additions & 2 deletions packages/kms-musap-rn/src/MusapKeyManagerSystem.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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')

Expand Down Expand Up @@ -133,7 +133,7 @@ export class MusapKeyManagementSystem extends AbstractKeyManagementSystem {
const keyInfo: Partial<ManagedKeyInfo> = {
kid: args.keyId,
type: this.mapAlgorithmTypeToKeyType(args.algorithm),
publicKeyHex: PEMToHex( args.publicKey.pem),
publicKeyHex: rawPublicKeyHexFromAsn1Der(args.publicKey.der),
meta: {
...args,
},
Expand Down

0 comments on commit da9ee27

Please sign in to comment.