Free 30-min Web3 Consultation
Book Consultation
Smart Contract Security Audits
View Audit Services
Custom DeFi Protocol Development
Explore DeFi
Full-Stack Web3 dApp Development
View App Services
Free 30-min Web3 Consultation
Book Consultation
Smart Contract Security Audits
View Audit Services
Custom DeFi Protocol Development
Explore DeFi
Full-Stack Web3 dApp Development
View App Services
Free 30-min Web3 Consultation
Book Consultation
Smart Contract Security Audits
View Audit Services
Custom DeFi Protocol Development
Explore DeFi
Full-Stack Web3 dApp Development
View App Services
Free 30-min Web3 Consultation
Book Consultation
Smart Contract Security Audits
View Audit Services
Custom DeFi Protocol Development
Explore DeFi
Full-Stack Web3 dApp Development
View App Services
LABS
Guides

How to Implement a Decentralized Identity (DID) Solution for Patients

A technical tutorial for developers to build a patient-controlled identity system using W3C standards, enabling secure sharing of medical credentials without a central authority.
Chainscore © 2026
introduction
DEVELOPER TUTORIAL

How to Implement a Decentralized Identity (DID) Solution for Patients

A technical guide for developers building self-sovereign patient identity systems using W3C Decentralized Identifiers (DIDs) and Verifiable Credentials (VCs).

Decentralized Identity (DID) systems empower patients with self-sovereign control over their health data. Unlike centralized models where hospitals manage identity silos, a DID is a cryptographically verifiable identifier anchored on a public ledger like Ethereum or Polygon. The core components are the DID Document, which contains public keys and service endpoints, and Verifiable Credentials, which are tamper-proof digital attestations (e.g., a vaccination record) issued by a trusted entity like a clinic. This architecture enables secure, patient-centric data sharing without a central authority.

To implement a basic patient DID system, you first need to choose a DID method and a supporting blockchain. For Ethereum-based systems, the did:ethr method is common. You can create a DID for a patient by generating a cryptographic key pair. The following JavaScript snippet using the ethr-did library demonstrates creation and registration:

javascript
import { EthrDID } from 'ethr-did';
import { ethers } from 'ethers';

const provider = new ethers.providers.JsonRpcProvider('RPC_URL');
const wallet = new ethers.Wallet('PRIVATE_KEY', provider);

// Create an EthrDID identity
const patientDID = new EthrDID({
  identifier: wallet.address,
  chainNameOrId: 'sepolia', // Testnet
  provider,
  signer: wallet,
});

console.log(`Patient DID: ${patientDID.did}`);
// Example Output: did:ethr:sepolia:0xAbC123...

The DID is derived from the wallet's public address and is immediately usable.

The next step is issuing Verifiable Credentials. A clinic (the issuer) signs a JSON-LD credential with its private key, binding it to the patient's DID. Use a library like did-jwt-vc. Here's a simplified example of creating a credential:

javascript
import { createVerifiableCredentialJwt } from 'did-jwt-vc';
const issuerDID = new EthrDID({...}); // Clinic's DID

const vcPayload = {
  sub: patientDID.did, // Subject is the patient
  vc: {
    '@context': ['https://www.w3.org/2018/credentials/v1'],
    type: ['VerifiableCredential', 'ImmunizationCredential'],
    credentialSubject: {
      id: patientDID.did,
      vaccineCode: '207', // COVID-19, mRNA, spike protein
      lotNumber: '123ABC',
      dateAdministered: '2023-10-01',
    },
  },
};

const vcJwt = await createVerifiableCredentialJwt(vcPayload, issuerDID);
// Patient now holds this signed JWT as their credential.

The patient stores this JWT in their digital wallet, a secure app that holds their keys and credentials.

Verification is the final, critical phase. Any third party, like a pharmacy, can verify the credential's authenticity without contacting the issuing clinic. They check the cryptographic signature against the issuer's public key in its DID Document and ensure the credential hasn't been revoked—often by checking a revocation registry on-chain. The verification code is straightforward:

javascript
import { verifyCredential } from 'did-jwt-vc';
const verificationResult = await verifyCredential(vcJwt, { resolver });
// `resolver` fetches the issuer's DID Document from the blockchain
if (verificationResult.verified) {
  console.log('Credential is valid and issued by:', verificationResult.issuer);
}

This trustless verification enables interoperable proof of health status across different organizations.

For production systems, consider key management, revocation mechanisms like Ethereum-based registries, and selective disclosure protocols such as BBS+ signatures to allow patients to reveal only specific credential attributes. Privacy-preserving zero-knowledge proofs (ZKPs) can be integrated for advanced use cases. Always audit smart contracts for DID methods and follow the W3C Verifiable Credentials Data Model specification for interoperability. Frameworks like Microsoft's ION (Bitcoin) or SpruceID's didkit can accelerate development for more complex identity networks.

prerequisites
IMPLEMENTATION GUIDE

Prerequisites and System Architecture

This guide outlines the technical foundation required to build a decentralized identity (DID) system for patient data, covering core components, technology choices, and architectural patterns.

A patient-centric DID system requires a trustless, verifiable data layer separate from any single institution. The core prerequisites are: a blockchain for anchoring decentralized identifiers and public keys, a verifiable data registry (like a blockchain or IPFS) to store credential schemas and revocation lists, and W3C-compliant software libraries for creating and verifying Verifiable Credentials (VCs). For patient use, you must also integrate with existing healthcare data sources via secure APIs, often using the FHIR (Fast Healthcare Interoperability Resources) standard to map clinical data to credential claims.

The system architecture typically follows a three-tier model. The Issuer Layer consists of trusted entities like hospitals or labs that sign VCs (e.g., a vaccination record). The Holder Layer is the patient's wallet (e.g., a mobile app) that stores these VCs in a secure, private vault. The Verifier Layer includes any service needing proof, such as a pharmacy, which requests specific credentials and checks their cryptographic signatures and revocation status against the public registry. All interactions are governed by DIDComm for secure, peer-to-peer messaging or OpenID Connect (OIDC) with SIOPv2 for web-based authentication.

For development, select a DID method suited for healthcare's regulatory needs. The did:ethr method (Ethereum) offers broad tooling, while did:ion (Bitcoin/Sidetree) provides scalable, public key management. Use libraries like Veramo (TypeScript) or Aries Framework JavaScript to handle DID operations, credential issuance, and presentation. A reference architecture might use Ethereum's Sepolia testnet for DID anchoring, Ceramic Network as the data registry for schemas, and IPFS for storing encrypted, patient-held credential data, ensuring portability and user sovereignty.

Key design decisions involve privacy and selective disclosure. Implement BBS+ signatures to allow patients to prove specific claims from a credential without revealing the entire document (e.g., proving they are over 18 without showing their birthdate). Revocation strategies are critical; consider status list 2021 credentials or smart contract-based registries. The architecture must also plan for key recovery mechanisms, such as social recovery or guardian protocols, to prevent permanent data loss, which is a non-negotiable requirement in a healthcare context.

Finally, the front-end and integration layer must provide a seamless user experience. Develop a cross-platform mobile wallet using React Native or Flutter, integrating biometric security for the private key store. For healthcare providers, build verifier plugins for existing Electronic Health Record (EHR) systems using standard APIs. All components should be designed to comply with regulations like HIPAA and GDPR, ensuring that personally identifiable information (PII) is never stored on-chain and that patient consent is cryptographically captured for every data exchange.

key-concepts-text
CORE CONCEPTS: DIDS, VCS, AND HIPAA CONSIDERATIONS

How to Implement a Decentralized Identity (DID) Solution for Patients

A technical guide for developers on building a patient-centric identity system using decentralized identifiers and verifiable credentials while navigating healthcare compliance.

A Decentralized Identifier (DID) is a new type of globally unique identifier that an individual or entity can create and control without a central registry. For patients, this means owning a portable, self-sovereign identity anchored on a blockchain or other decentralized network. Unlike a traditional medical record number tied to a single institution, a patient's DID can be used to request and receive Verifiable Credentials (VCs) from any healthcare provider. These VCs are tamper-evident, cryptographically signed attestations—like a digital version of a vaccination record or lab result—that can be presented to prove specific claims without revealing the underlying data.

Implementing a DID solution begins with selecting a DID method, which defines the creation, resolution, and management of DIDs on a specific network. For healthcare, consider privacy-focused methods like did:key for simple, offline use or did:ion (Sidetree on Bitcoin) for scalable, public anchoring. A patient's DID document, resolved from their DID, contains public keys and service endpoints for interaction. In practice, a patient app generates a DID, and a healthcare provider's system issues a VC—a JSON-LD or JWT-formatted document—signing it with their private key and embedding the patient's DID as the subject. The patient stores this VC in their secure digital wallet.

HIPAA compliance is paramount. A well-architected DID/VC system can enhance privacy by enabling selective disclosure and zero-knowledge proofs. Instead of sharing a full credential, a patient can generate a cryptographic proof that they are over 18 or had a negative test, without revealing their birthdate or the test result itself. The system must ensure that no Protected Health Information (PHI) is written to an immutable ledger; only DIDs and the cryptographic hashes of credentials should be anchored. All PHI remains encrypted in the VC, stored off-chain by the patient. Access control and audit logs for credential issuance must still adhere to HIPAA's Security Rule.

A reference architecture involves three core components: the Issuer (hospital EHR system), the Holder (patient mobile wallet), and the Verifier (pharmacy app). The issuer signs VCs using a W3C Verifiable Credentials Data Model standard. The holder wallet, like Trinsic or Sphereon, manages keys and presents proofs. The verifier checks the issuer's signature and the credential's status. Use libraries such as did-jwt-vc or aries-framework-javascript to handle the complex cryptography. Always conduct a formal Security Risk Assessment to map data flows against HIPAA requirements.

Key implementation steps include: 1) Choosing a DID method and VC format (JWT vs JSON-LD), 2) Building a secure key management system for patient wallets, 3) Integrating with existing EHR systems via FHIR APIs for credential issuance, 4) Implementing a revocation mechanism like credential status lists, and 5) Designing user consent flows for credential sharing. Testing should involve verifiable data registries like the ION network and compliance checks with frameworks such as HIPAA Safe Harbor for de-identification. The goal is to give patients portable control over their health data while interoperating with legacy healthcare infrastructure.

step-1-did-registry
FOUNDATION

Step 1: Deploy the DID Registry Smart Contract

The core of a patient-centric decentralized identity (DID) system is an immutable, on-chain registry. This step involves deploying the smart contract that will serve as the authoritative source for creating and resolving patient DIDs on the blockchain.

A Decentralized Identifier (DID) is a unique, persistent identifier that an individual controls without reliance on a central authority. For a patient identity system, this contract acts as the DID Registry—a public, tamper-proof ledger that maps a patient's DID (e.g., did:ethr:0x123...) to its associated DID Document (DIDDoc). The DIDDoc is a JSON-LD document containing public keys, service endpoints (like links to encrypted health records), and authentication methods. By anchoring this mapping on-chain, we establish a globally verifiable root of trust for patient identity.

We will deploy a registry using the ERC-1056 (Ethr-DID) standard, a widely adopted, non-transferable Ethereum standard for DIDs. This standard provides a simple, gas-efficient interface with key functions: setAttribute(bytes32 _did, bytes32 _name, bytes _value, uint256 _validity) to publish or update a DIDDoc attribute, and getAttribute(bytes32 _did, bytes32 _name) to resolve it. Using a known standard ensures interoperability with existing W3C DID resolvers and verifiable credential libraries, rather than building a proprietary system from scratch.

To deploy, you'll need a development environment like Hardhat or Foundry, and an Ethereum testnet (e.g., Sepolia). The core contract is minimal. Here is a simplified version of the key mapping:

solidity
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
contract DIDRegistry {
    mapping(bytes32 => mapping(bytes32 => Attribute)) public attributes;
    struct Attribute {
        bytes value;
        uint256 validTo;
        address issuer;
    }
    event DIDAttributeChanged(bytes32 indexed did, bytes32 name, bytes value, uint256 validTo);
    function setAttribute(bytes32 did, bytes32 name, bytes memory value, uint256 validity) public {
        attributes[did][name] = Attribute(value, block.timestamp + validity, msg.sender);
        emit DIDAttributeChanged(did, name, value, block.timestamp + validity);
    }
}

Deploy this contract using a script like npx hardhat run scripts/deploy.js --network sepolia. Save the deployed contract address; it is the system's root identifier.

After deployment, the next step is to initialize the registry with a controller. The deploying address becomes the first controller—an Ethereum account authorized to update DIDs. For a production health system, you would transfer control to a Decentralized Autonomous Organization (DAO) or a multi-signature wallet governed by healthcare providers and patient advocates. This ensures no single entity has unilateral control over the identity registry, aligning with the decentralized ethos. The contract address and initial controller setup complete the foundational layer upon which patient identities will be built and managed.

step-2-issuer-backend
IMPLEMENTATION

Step 2: Build the Credential Issuer Service

This step details how to create the backend service that issues W3C Verifiable Credentials to patients, using a decentralized identifier (DID) as the issuer.

The Credential Issuer Service is a secure backend component that acts as the trusted authority, minting and signing Verifiable Credentials (VCs) for patients. It must be associated with a Decentralized Identifier (DID) to prove its authenticity on-chain. For this guide, we'll use the did:ethr method on the Sepolia testnet, where the issuer's DID is derived from an Ethereum account controlled by the healthcare provider. The service's primary responsibilities are to authenticate patient requests, format credential data according to the W3C VC data model, and cryptographically sign the credential using the issuer's private key.

First, set up the core dependencies. You'll need libraries to create DIDs, sign VCs, and interact with the Ethereum blockchain. For a Node.js service, common packages include ethr-did, ethr-did-resolver, did-resolver, and vc-js. Initialize your issuer's DID by creating an Ethereum account (e.g., using ethers.js) and constructing the DID document. For example: const issuerDID = 'did:ethr:sepolia:0xYourIssuerAddress';. This DID will be embedded in every issued credential as the issuer property.

The credential's structure must comply with the W3C standard. A patient's COVID-19 Vaccination Credential would include claims like the patient's DID (credentialSubject.id), vaccine type, date, and lot number. These claims are packaged into a JSON-LD object with context, type, issuance date, and expiration. The critical step is generating the proof. Using the ethr-did library, you sign a cryptographic hash of the credential data with the issuer's private key, creating a JWT or EIP712Signature proof that links back to the issuer's DID on-chain.

Your service should expose a secure API endpoint (e.g., POST /issue-credential). It must first authenticate the requesting patient, often by verifying a signature from their wallet. After validating the request data, it constructs the VC payload, signs it, and returns the completed Verifiable Credential to the patient's wallet. The patient can then store this VC in their digital wallet (like a MetaMask Snap or Ceramic DataModel) for later presentation to verifiers, such as travel authorities or event venues.

For production, key management is paramount. The issuer's private key should never be hard-coded. Use a Hardware Security Module (HSM), a cloud KMS like AWS KMS, or a dedicated key management service. Furthermore, consider implementing credential status tracking using a revocation registry (e.g., using the Ethereum Attestation Service or a Smart Contract) to allow the issuer to invalidate credentials if needed, adding a crucial layer of security and control to your decentralized identity system.

step-3-patient-wallet
IMPLEMENTATION

Step 3: Create the Patient Wallet & Presentation Flow

This step builds the user-facing application where patients manage their credentials and share them with verifiers.

The patient wallet is a frontend application, typically a web or mobile app, that allows users to store their Verifiable Credentials (VCs) and generate Verifiable Presentations (VPs). Its core functions are to securely store private keys and the issued credentials, and to facilitate the presentation flow when a user needs to prove something. For development, you can use SDKs like Veramo or SpruceID's Credible to handle the underlying cryptography and DID operations, abstracting away the complexity of key management and signature generation.

The presentation flow begins when a verifier (e.g., a clinic's website) requests specific data. It sends a Presentation Request, often formatted as a Presentation Exchange (PEX) specification or a W3C Verifiable Presentation Request. This request specifies exactly which credentials are needed (e.g., a vaccination credential from a specific issuer) and any constraints (e.g., the credential must not be expired). The wallet receives this request, matches it against the user's stored VCs, and prompts the user for consent to share.

Upon user consent, the wallet constructs a Verifiable Presentation. This is a wrapper around the selected credentials, signed with the patient's DID key to prove they are the legitimate holder. The presentation is sent back to the verifier. The verifier then performs three checks: verifying the signature on the presentation (patient's control), verifying the signatures on the enclosed credentials (issuer's authenticity), and checking that the credential data satisfies the original request's constraints. Only if all checks pass is the patient's claim accepted.

For a practical implementation, here is a simplified code snippet using a hypothetical wallet SDK to create a presentation:

javascript
// Patient's wallet receives a presentationRequest object
const matchedCredentials = wallet.queryCredentials(presentationRequest);
// User selects which credentials to share
const selectedCredentials = await wallet.ui.selectCredentials(matchedCredentials);
// Wallet creates and signs the Verifiable Presentation
const verifiablePresentation = await wallet.createPresentation({
  credentials: selectedCredentials,
  holderDid: patientDid,
  proofFormat: 'jwt' // or 'lds' for Linked Data Signatures
});
// Send the VP back to the verifier
await verifier.submitPresentation(verifiablePresentation);

Key security considerations for the wallet include local key storage (using secure enclaves or encrypted local storage instead of servers) to maintain true user sovereignty, and selective disclosure mechanisms. Technologies like BBS+ signatures allow users to reveal only specific attributes from a credential (e.g., proving they are over 18 without revealing their exact birth date), enhancing privacy. The wallet must also handle DID resolution to fetch the public keys needed for verification from the patient's and issuer's DID documents on their respective blockchains or networks.

Finally, integrate this flow into the verifier's application. The verifier's backend must be able to generate standard presentation requests and validate incoming presentations. Libraries like DIF's Presentation Exchange provide tools for this. The end result is a seamless, user-controlled experience where patients can instantly prove their qualifications without exposing unnecessary personal data or relying on a central database.

step-4-revocation
DID SOLUTION FOR PATIENTS

Step 4: Implement Credential Revocation

A robust revocation mechanism is essential for maintaining the integrity of a patient's digital identity, allowing for the secure invalidation of credentials when necessary.

Credential revocation is a critical security feature for any decentralized identity (DID) system. In a healthcare context, a patient's Verifiable Credential (VC)—such as a vaccination record or a specialist referral—may need to be revoked if it was issued in error, contains outdated information, or if the patient's consent is withdrawn. Unlike centralized systems where a database entry is simply deleted, revocation in a DID ecosystem must be managed in a privacy-preserving and interoperable way without relying on a single authority.

The World Wide Web Consortium (W3C) recommends several approaches for revocation. A common method is the status list credential, defined in the W3C Status List 2021 specification. In this model, a trusted issuer publishes a special, signed credential that contains a bitstring status list. Each bit corresponds to the revocation status of a specific issued credential. A verifier checks this status list credential to confirm if a patient's presented credential is still valid, ensuring the check is done without revealing which specific credential is being verified.

Here is a simplified example of how a status list credential is structured and referenced. The issuer's DID document declares a statusList2021 service endpoint, and each issued VC points to it.

Issuer's Status List Credential:

json
{
  "@context": ["https://www.w3.org/ns/credentials/v2"],
  "id": "https://health-issuer.example/status/1",
  "type": ["VerifiableCredential", "StatusList2021Credential"],
  "issuer": "did:example:health-issuer",
  "credentialSubject": {
    "id": "https://health-issuer.example/status/1#list",
    "type": "StatusList2021",
    "statusPurpose": "revocation",
    "encodedList": "H4sIAAAAAAAAA-3MMQ0AAAACIE3/nnN/CIqJqDkCAAAA"
  }
}

Patient's VC with Status Reference:

json
{
  "credentialStatus": {
    "id": "https://health-issuer.example/status/1#94567",
    "type": "StatusList2021Entry",
    "statusPurpose": "revocation",
    "statusListIndex": "94567",
    "statusListCredential": "https://health-issuer.example/status/1"
  }
}

To revoke a credential, the issuer updates the bit at the specified statusListIndex in the encodedList from 0 (valid) to 1 (revoked) and re-publishes the signed status list credential. Verifiers must fetch the latest status list. For high-frequency updates, consider using a revocation registry on a blockchain like Ethereum or Polygon, as implemented by protocols like Indy-AnonCreds or Hyperledger Aries. This uses a smart contract to manage the status, providing a tamper-proof and publicly auditable log of revocation actions.

When implementing revocation for patient credentials, key design decisions include: - Update Frequency: How often will status lists be published? - Verifier Caching: Should verifiers cache status lists, and for how long? - Privacy: The status list method preserves privacy for the holder, but the issuer knows the index. For stronger privacy, explore zero-knowledge proofs (ZKPs). - Patient Control: Consider mechanisms allowing patients to request revocation directly, perhaps by signing a message with their DID keys to prove consent for the action.

Effective revocation closes the security loop in your DID system. It ensures that trust is dynamic and can be withdrawn, which is non-negotiable for handling sensitive health data. The next step involves integrating these components into a complete flow for issuing, holding, and verifying patient credentials within your application.

TECHNICAL EVALUATION

DID Method Comparison for Healthcare

Comparison of major DID methods based on criteria critical for patient identity management, including regulatory compliance, interoperability, and technical maturity.

Feature / MetricSidetree (ION)did:ethrdid:key

Underlying Ledger

Bitcoin (Layer 2)

Ethereum / EVM

N/A (Key Material)

W3C Compliance

HIPAA Data Minimization Support

Estimated Issuance Cost

$0.10 - $1.00

$2 - $15 (Gas)

$0

Recovery / Revocation

Multi-key rotation

Smart contract control

Not natively supported

Production Readiness (2024)

High (Microsoft ION)

High (uPort, Veramo)

Medium (Experimental)

Interoperability (VC/DIDComm)

High

High

Limited

Typical Resolution Time

< 2 sec

< 1 sec

< 100 ms

DEVELOPER IMPLEMENTATION

Frequently Asked Questions

Common technical questions and solutions for building decentralized identity (DID) systems for healthcare applications.

A Decentralized Identifier (DID) is a user-owned, globally unique identifier that does not require a central registry, certificate authority, or identity provider. It is typically expressed as a URI (e.g., did:ethr:0xabc123...). This differs fundamentally from traditional logins (OAuth, SAML) where a central entity (Google, a hospital IDP) controls and can revoke your identity.

Key Technical Differences:

  • Control: The private key holder (patient) controls the DID, not an institution.
  • Portability: DIDs and their associated Verifiable Credentials (VCs) can be used across any compliant system, breaking vendor lock-in.
  • Verifiability: Claims are cryptographically signed, enabling trust without calling a central database. Implementation uses the W3C DID Core specification and JSON-LD or JWT formats for credentials.
conclusion
IMPLEMENTATION SUMMARY

Conclusion and Next Steps

This guide has outlined the core components for building a patient-centric decentralized identity (DID) system. The next steps involve integrating these concepts into a production-ready application.

You have now explored the foundational architecture for a patient-controlled DID system. The core workflow involves: issuing Verifiable Credentials (VCs) from trusted issuers like hospitals, storing them in a user's digital wallet, and presenting Verifiable Presentations (VPs) to verifiers such as clinics or pharmacies. This model shifts control from centralized databases to the individual, enabling selective disclosure of health data. The primary standards enabling this are W3C DIDs for identifiers and W3C Verifiable Credentials for the data format.

To move from concept to implementation, begin by selecting a DID method and VC data model suited for healthcare. The did:ethr method (using Ethereum) or did:key are common starting points for their developer tooling. For health data, align your credential schemas with established standards like FHIR (Fast Healthcare Interoperability Resources) to ensure semantic interoperability. A practical next step is to prototype issuing a simple VC, such as a vaccination record, using a library like did-jwt-vc or veramo.

The security and privacy of the system depend on robust key management. Patients' private keys, which control their DIDs, must be securely stored, often using Hardware Security Modules (HSMs) or secure enclaves in mobile wallets. Implement proper key recovery mechanisms, such as social recovery or sharded backups, to prevent permanent data loss. Furthermore, design your revocation strategy—using a revocation registry (like on-chain) or status lists—to invalidate credentials if a private key is compromised or data becomes outdated.

Finally, consider the user experience and legal compliance. The wallet interface must make complex concepts like signing presentations intuitive for non-technical users. Simultaneously, the system must be designed to comply with regulations like HIPAA in the US or GDPR in Europe. This involves ensuring data minimization in VPs and providing clear audit trails. Start small with a pilot program, gather feedback, and iterate. Resources like the Decentralized Identity Foundation and the W3C VC Implementation Guide are invaluable for ongoing development.

How to Implement a Decentralized Identity (DID) Solution for Patients | ChainScore Guides