Skip to content

Instantly share code, notes, and snippets.

@chongkan
Last active March 30, 2024 04:55
Show Gist options
  • Save chongkan/a78803c61211ee592fec1666316191ac to your computer and use it in GitHub Desktop.
Save chongkan/a78803c61211ee592fec1666316191ac to your computer and use it in GitHub Desktop.
Generates a DID identifier using the owner's public key, method, and program ID.
/**
* Generates a DID identifier using the owner's public key, method, and program ID.
* @param {string} authorityPublicKey - The owner's public key.
* @returns {string} - The generated DID identifier.
* https://g.identity.com/sol-did/#identifier-generation-method
*/
import bs58 from 'bs58';
async function generateDIDIdentifier(authorityPublicKey) {
let seed = 256;
let hashedData;
const didMethod = 'sol';
const programID = 'didso1Dpqpm4CsiCjzP766BGY89CAdD6ZBL68cRhFPc';
while (true) {
seed -= 1;
let dataToHash = authorityPublicKey + didMethod + seed + programID;
let ArrayBufferData = new TextEncoder().encode(dataToHash);
const buffer = await crypto.subtle.digest('SHA-256', ArrayBufferData);
hashedData = new Uint8Array(buffer);
if ((hashedData[0] & 0xF8) == 0) {
break;
}
}
if (!hashedData) {
throw new Error('Failed to generate hashed data');
}
return bs58.encode(Buffer.from(hashedData));
}
// -- Testing
const didRegex = /^[1-9A-HJ-NP-Za-km-z]{40,48}$/;
const isValidDID = didRegex.test(didIdentifier);
console.log('Is valid DID:', isValidDID);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment