Skip to main content

Generate and Verify a DID Signature

In addition to being used to authorize chain operations, both light and full DIDs have off-chain applications.

One such applications is generating digital signatures. As a DID can have multiple keys, in addition to the signature data itself, a DID signature contains information about the signer's DID and key used, so that Verifiers have all the information needed to resolve the DID from the KILT blockchain and use the right key to verify the generated signature.

The snippet below shows how to generate and verify a DID signature using the KILT SDK.

import * as Kilt from '@kiltprotocol/sdk-js'

type KeyLookup = (parameter: {
didUri: Kilt.DidUri
keyRelationship: Kilt.VerificationKeyRelationship
}) => Promise<{
key: Kilt.KiltKeyringPair
keyType: Kilt.VerificationKeyType
keyUri: Kilt.DidResourceUri
}>

export async function generateAndVerifyDidAuthenticationSignature(
did: Kilt.DidDocument,
payload: Uint8Array,
keyLookup: KeyLookup
): Promise<void> {
// How the key is looked up depends on where the key is stored (e.g. memory, hardware wallet, browser extension)
const { key, keyUri } = await keyLookup({
didUri: did.uri,
keyRelationship: 'authentication'
})

// Generate a signature using the key that we just looked up.
const signature = key.sign(payload)

// Print the generated signature object.
console.log('Generated signature:')
console.log(Kilt.Utils.Crypto.u8aToHex(signature))

// Verify the validity of the signature using the DID's authentication public key.
// It throws if the signature cannot be verified.
await Kilt.Did.verifyDidSignature({
message: payload,
signature,
keyUri,
expectedVerificationMethod: 'authentication'
})
}
note

Notice that the snippet above takes a DidDocument instance to generate the signature. A DidDocument can represent either a light or a full DID. This means that both light and full DIDs can generate signatures, and the KILT SDK implements the right verification logic depending on whether the signer is a light or a full DID.