使用 Nethereum 建立以太坊錢包|錢包生成教學

by NickChi

以太坊錢包是與區塊鏈互動的入口,而錢包最基本的核心,就是由「私鑰 ➜ 公鑰 ➜ 地址」三個環節組成。這篇教學將帶你透過 .NET 上的 Nethereum 函式庫,手把手教你如何從零開始建立一個以太坊錢包,並解釋每個環節的意義與運作方式。


錢包產生流程簡介

┌─────────────────────────────┐
│        1. 私鑰(Private Key)                               │
│ 一組 256-bit 隨機數字(32 bytes)                  │
│ ⚠ 必須保密,不能洩漏                                     │
└────────────┬────────────────┘
             │
             ▼
🔐 使用橢圓曲線密碼學(SECP256k1)推導
             │
             ▼
┌─────────────────────────────┐
│        2. 公鑰(Public Key)                                 │
│ 由私鑰推導出的 512-bit(64 bytes)                │
│ 🧾 用於驗證簽章,理論上可公開                     │
└────────────┬────────────────┘
             │
             ▼
🔄 對公鑰做 Keccak-256 雜湊,再取最後 20 bytes
             │
             ▼
┌─────────────────────────────┐
│        3. 地址(Ethereum Address)                    │
│ 取雜湊值最後 20 bytes,變成 40 hex                │
│ 🏠 可公開,外部使用者與合約識別用              │
└─────────────────────────────┘

使用 Nethereum 建立錢包

📦 安裝 Nethereum 套件

使用 NuGet 安裝 Nethereum:

dotnet add package Nethereum.Web3
dotnet add package Nethereum.Signer

🛠 程式碼範例:建立新錢包

void Main()
{
	// 1. 產生助記詞(12 個單字)
	var wallet = new Wallet(Wordlist.English, WordCount.Twelve);
	var mnemonic = wallet.Words;
	"助記詞:".Dump();
	mnemonic.Dump();

	// 2. 取得第一個帳號(index 0)
	var account = wallet.GetAccount(0);
	string privateKey = account.PrivateKey;
	string address = account.Address;

	"帳戶資訊:".Dump();
	new
	{
		Address = address,
		PrivateKey = privateKey
	}.Dump();

	// 3. 從私鑰產生公鑰
	var key = new EthECKey(privateKey);
	var publicKeyBytes = key.GetPubKeyNoPrefix(); // 64 bytes
	var publicKeyHex = BitConverter.ToString(publicKeyBytes).Replace("-", "");

	"公鑰資訊:".Dump();
	new
	{
		PublicKeyHex = publicKeyHex
	}.Dump();
}


💡 補充說明

  • 私鑰 是錢包的靈魂,請妥善儲存,切勿公開
  • 公鑰 是從私鑰透過 SECP256k1 推導出來,用來驗證交易。
  • 地址 是對公鑰做 Keccak-256 雜湊後的最後 20 bytes,作為錢包的公開識別碼。

You may also like

Leave a Comment