import { v4 as uuidv4 } from 'uuid' ; import { JWK } from 'jose' ; import { PublicKey } from '../dtos/DIDDocument' ; import Base58 from 'base-58' ; import KeyEncoder from 'key-encoder' ; import { DID_SIOP_ERRORS } from '../error' ; function getRandomString ( ) { return uuidv4 ( ) ; } function getHexPubKeyFromKey ( key ) { const pemPub = key . toPEM ( false ) ; const keyEncoder = new KeyEncoder ( 'secp256k1' ) ; return keyEncoder . encodePublic ( pemPub , 'pem' , 'raw' ) ; } function getDIDFromKey ( key ) { return 'did:key:' + getBase58PubKeyFromKey ( key ) ; } function getBase58PubKeyFromKey ( key ) { const hexPubKey = getHexPubKeyFromKey ( key ) ; return Base58 . encode ( Buffer . from ( hexPubKey ) ) ; } function toHex ( data ) { return Buffer . from ( data , 'base64' ) . toString ( 'hex' ) ; } function getKeyIdFromKey ( key ) { const did = getDIDFromKey ( key ) ; return `${ did }#veri-key1` ; } function getKeyIdFromDID ( did ) { return `${ did }#veri-key1` ; } function pubkeyHexToPem ( pubkeyHex ) { const keyEncoder = new KeyEncoder ( 'secp256k1' ) ; const rawPubKey = pubkeyHex . includes ( '0x' ) ? pubkeyHex . slice ( 2 ) : pubkeyHex ; return keyEncoder . encodePublic ( rawPubKey , 'raw' , 'pem' ) ; } function getPemPubKey ( pubKey ) { if ( pubKey . publicKeyBase58 ) { return getPemFromBase58PubKey ( pubKey . publicKeyBase58 ) ; } if ( pubKey . publicKeyHex ) { return pubkeyHexToPem ( pubKey . publicKeyHex ) ; } if ( pubKey . ethereumAddress ) { return pubkeyHexToPem ( pubKey . ethereumAddress ) ; } if ( pubKey . publicKeyPem ) return pubKey . publicKeyPem ; throw new Error ( DID_SIOP_ERRORS . PUBKEY_FORMAT_NOT_SUPPORTED ) ; } function getPemFromBase58PubKey ( base58PubKey ) { const buff = Buffer . from ( Base58 . decode ( base58PubKey ) ) ; const pubKeyHex = buff . toString ( 'utf8' ) ; return pubkeyHexToPem ( pubKeyHex ) ; } export { getPemPubKey , getDIDFromKey , pubkeyHexToPem , getKeyIdFromKey , getKeyIdFromDID , getRandomString , getHexPubKeyFromKey , getBase58PubKeyFromKey } ;