Easy-Go-Web3
知识图谱Go 教程React Web3智能合约
需求分析系统设计设计模式Go 微服务
项目实战DevOps
Go 生态React 生态智能合约生态Web3 生态AI × Web3工具箱Web3 公司远程Web3求职
🎯 AA 工程师面试手册博客
GitHub
返回系统设计
高级

安全设计

Security Architecture

构建安全的 Web3 后端,掌握认证授权、加密存储、审计日志。

1认证与授权

Web3 后端的认证体系: **钱包签名认证 (Sign-In with Ethereum)**: 1. 后端生成随机 nonce 2. 用户用私钥签名 nonce 3. 后端验证签名恢复地址 4. 签发 JWT token
example.go
go
1// SIWE (Sign-In with Ethereum) 实现
2type SIWEAuth struct {
3 nonceStore NonceStore
4 jwtSecret []byte
5}
6
7func (s *SIWEAuth) GenerateNonce(address common.Address) (string, error) {
8 nonce := uuid.New().String()
9 if err := s.nonceStore.Set(address, nonce, 5*time.Minute); err != nil {
10 return "", err
11 }
12 return nonce, nil
13}
14
15func (s *SIWEAuth) Verify(address common.Address, message, signature string) (string, error) {
16 // 验证 nonce
17 expectedNonce, err := s.nonceStore.Get(address)
18 if err != nil {
19 return "", ErrNonceExpired
20 }
21
22 // 解析签名
23 sig, err := hexutil.Decode(signature)
24 if err != nil {
25 return "", ErrInvalidSignature
26 }
27
28 // 恢复签名者地址
29 msgHash := accounts.TextHash([]byte(message))
30 sig[64] -= 27 // 调整 V 值
31
32 pubKey, err := crypto.SigToPub(msgHash, sig)
33 if err != nil {
34 return "", ErrInvalidSignature
35 }
36
37 recoveredAddr := crypto.PubkeyToAddress(*pubKey)
38 if recoveredAddr != address {
39 return "", ErrAddressMismatch
40 }
41
42 // 签发 JWT
43 token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
44 "address": address.Hex(),
45 "exp": time.Now().Add(24 * time.Hour).Unix(),
46 })
47
48 return token.SignedString(s.jwtSecret)
49}

2私钥安全存储

热钱包私钥的安全存储方案:
example.go
go
1// 使用 KMS 加密私钥
2type SecureKeyStore struct {
3 kmsClient *kms.Client
4 keyID string
5}
6
7func (s *SecureKeyStore) StorePrivateKey(ctx context.Context, address string, privateKey []byte) error {
8 // 使用 KMS 加密
9 encrypted, err := s.kmsClient.Encrypt(ctx, &kms.EncryptInput{
10 KeyId: aws.String(s.keyID),
11 Plaintext: privateKey,
12 })
13 if err != nil {
14 return err
15 }
16
17 // 存储加密后的私钥
18 return s.db.StoreEncryptedKey(address, encrypted.CiphertextBlob)
19}
20
21func (s *SecureKeyStore) SignTransaction(ctx context.Context, address string, tx *types.Transaction) (*types.Transaction, error) {
22 // 获取加密私钥
23 encryptedKey, err := s.db.GetEncryptedKey(address)
24 if err != nil {
25 return nil, err
26 }
27
28 // KMS 解密
29 decrypted, err := s.kmsClient.Decrypt(ctx, &kms.DecryptInput{
30 CiphertextBlob: encryptedKey,
31 })
32 if err != nil {
33 return nil, err
34 }
35
36 // 签名后立即清除内存中的私钥
37 defer func() {
38 for i := range decrypted.Plaintext {
39 decrypted.Plaintext[i] = 0
40 }
41 }()
42
43 privateKey, err := crypto.ToECDSA(decrypted.Plaintext)
44 if err != nil {
45 return nil, err
46 }
47
48 return types.SignTx(tx, types.LatestSignerForChainID(tx.ChainId()), privateKey)
49}

3审计日志

关键操作的审计追踪:
example.go
go
1type AuditLog struct {
2 ID string
3 Timestamp time.Time
4 Actor string // 操作者地址
5 Action string // 操作类型
6 Resource string // 操作对象
7 Details JSON // 详细信息
8 IPAddress string
9 UserAgent string
10 Result string // success/failure
11 Signature string // 日志签名防篡改
12}
13
14func (s *AuditService) Log(ctx context.Context, log *AuditLog) error {
15 // 生成日志签名
16 log.Signature = s.signLog(log)
17
18 // 写入不可变存储(可选上链)
19 if err := s.store.Append(log); err != nil {
20 return err
21 }
22
23 // 发送到 SIEM 系统
24 s.siem.Send(log)
25
26 return nil
27}

核心要点

  • •私钥永不明文存储,使用 KMS 加密
  • •采用钱包签名认证替代密码
  • •关键操作必须有审计日志
  • •实现速率限制防止攻击

真实案例

  • →Coinbase:HSM 硬件安全模块
  • →MetaMask:本地加密存储
  • →Fireblocks:MPC 多方计算
分布式系统继续学习:设计模式
Easy-Go-Web3

构建 Go 后端与 Web3 的学习之路。从基础到进阶,从理论到实践,助你成为全栈区块链开发者。

学习路径

  • 知识图谱
  • Go 教程
  • Go 微服务
  • 面试手册

资源中心

  • 工具箱
  • DevOps 工具
  • Web3 生态
  • 博客

© 2025 Easy-Go-Web3. All rights reserved.

Created withbyhardybao