本指南提供快速、逐步的教學,協助您開始使用 ocap-libs。在短短幾分鐘內,您將能安裝必要的套件、建立您的第一個去中心化身分(DID)、產生一個相容的加密錢包,並學會使用一些實用的工具程式。
步驟 1:安裝套件
首先,您需要安裝核心套件。您將需要用於 DID 建立、錢包管理、密碼學和通用工具的函式庫。
開啟您的終端機並執行以下指令:
Installation Command
pnpm install @arcblock/did @ocap/wallet @ocap/mcrypto @ocap/util此指令會安裝四個必要的套件:
@arcblock/did:用於建立和管理去中心化身分的主要函式庫。@ocap/wallet:用於建立和使用加密錢包進行簽署和驗證的工具。@ocap/mcrypto:處理底層的密碼學功能,例如金鑰產生。@ocap/util:提供用於資料編碼、轉換等的共享輔助函式。
步驟 2:建立錢包和 DID
套件安裝完成後,我們來建立一個錢包及其對應的 DID。錢包持有密碼學金鑰,而 DID 則是從這些金鑰衍生的公開識別碼。
建立一個新的 JavaScript 檔案(例如 create-did.js)並加入以下程式碼:
Create Wallet and DID
const { fromSecretKey: walletFromSecretKey } = require('@ocap/wallet');
const { fromSecretKey: didFromSecretKey } = require('@arcblock/did');
const Mcrypto = require('@ocap/mcrypto');
const assert = require('assert');
// 從 Mcrypto 解構所需的類型
const { types } = Mcrypto;
// 1. 使用 Ed25519 產生一個新的密碼學金鑰對
const keyPair = Mcrypto.Signer.Ed25519.genKeyPair();
console.log('Generated Secret Key (Buffer):', keyPair.secretKey);
// 2. 定義我們的 DID 和錢包的屬性
// 這確保它們使用相同的密碼學設定產生。
const spec = {
role: types.RoleType.ROLE_ACCOUNT, // 標準使用者帳戶的角色類型
pk: types.KeyType.ED25519, // 公鑰演算法
hash: types.HashType.SHA3, // 雜湊演算法
};
// 3. 從私鑰建立一個錢包實例
const wallet = walletFromSecretKey(keyPair.secretKey, spec);
console.log('\nWallet Address:', wallet.address);
// 4. 從相同的私鑰和規格建立一個 DID
const didAddress = didFromSecretKey(keyPair.secretKey, spec);
const did = `did:abt:${didAddress}`;
console.log('Generated DID:', did);
// 5. 驗證錢包地址和 DID 地址是否相同
assert.strictEqual(wallet.address, didAddress, 'Wallet address and DID address should match!');
console.log('\n✅ Success! Wallet address and DID are a match.');從您的終端機執行此腳本:
node create-did.js您將在主控台中看到新產生的私鑰、錢包地址和 DID。請注意,錢包地址是完整 DID 字串的核心組成部分。
步驟 3:簽署和驗證訊息
錢包的一個主要功能是透過簽署訊息來證明 DID 的所有權。這對於身分驗證和授權操作至關重要。
讓我們在腳本中加入簽署和驗證功能:
Sign and Verify
// ... (保留步驟 2 的程式碼) ...
// 6. 簽署一則訊息以證明錢包/DID 的所有權
const message = 'Hello, decentralized world!';
const signature = wallet.sign(message);
console.log('\nOriginal Message:', message);
console.log('Generated Signature:', signature);
// 7. 根據原始訊息驗證簽章
const isVerified = wallet.verify(message, signature);
assert.ok(isVerified, 'Signature should be verified successfully.');
console.log(`\nIs the signature valid? ${isVerified}`);
console.log('✅ Success! The signature has been verified.');當您執行更新後的腳本時,它會先建立錢包和 DID,然後簽署一則訊息並成功驗證簽章是否有效。
步驟 4:使用工具函式
@ocap/util 套件提供了許多實用的函式。例如,在步驟 2 中產生的私鑰是一個 Buffer。您可以使用工具程式將其轉換為更易讀的格式,如 Hex 或 Base58。
Using Utilities
// ... (保留步驟 3 的程式碼) ...
const { toHex } = require('@ocap/util');
// 8. 將私鑰緩衝區轉換為十六進位字串以便顯示或儲存
const secretKeyHex = toHex(keyPair.secretKey);
console.log('\nSecret Key (Hex Format):', secretKeyHex);
console.log('✅ Success! Used a utility to format the secret key.');這個簡單的範例展示了工具程式如何簡化常見的資料操作任務。
後續步驟
恭喜!您已成功建立去中心化身分、產生錢包、用它來簽署和驗證訊息,並利用了一個工具函式。您現在已經掌握將 DID 整合到應用程式中的基本建構模塊。
若要了解更多,請深入研究每個套件的核心概念和詳細的 API 參考資料: