使用Sphereon与.NET实现Hyperledger Aries交互?
解读
国内央国企、金融及政务区块链试点普遍采用Hyperledger Fabric作为底层,而Aries因其“去中心化身份(DID)+可验证凭证(VC)”能力被纳入“信创+数据要素流通”场景。Sphereon作为Aries Cloud Agent .NET(ACA-.NET)的主要维护方,提供了符合W3C DID/VC、DIF、Hyperledger Indy/Aries协议栈的.NET SDK,能够直接对接国内“长安链”“蜀信链”“渝快链”等Fabric改造链。面试官问此题,核心想验证三点:
- 候选人是否理解Aries“Agent-Controller”架构,而非简单调用REST;
- 能否用C#完成DID注册、凭证签发、零知识证明全流程,并解决国内CA证书、国密、代理上网等企业痛点;
- 是否具备把Aries集成到现有.NET微服务(gRPC、MassTransit、CAP)的能力,而不是跑一个Demo即结束。
知识点
- Aries RFC体系:RFC 0160 连接协议、RFC 0036 凭证签发、RFC 0037 凭证验证、RFC 0095 基本消息、RFC 0587 预签名预览。
- Sphereon.SDK.Aries(NuGet):
AriesClientBuilder、IConnectionService、ICredentialService、IProofService、PoolOptions、WalletOptions。 - Indy Pool与国内Fabric-Indy混合网络:Pool Genesis文件、Node IP白名单、TLS CA证书链、国密SM2/SM3/SM4适配层。
- DID Method:did:indy、did:web、did:key,国内备案要求“did:bsn”或“did:cic”扩展。
- 零知识证明:Predicate ≥、≤、≠,属性选择性披露,Revocation Registry(RSA accumulators)。
- 企业集成:
- 配置中心:Apollo、Nacos,热更新Agent Endpoint、Wallet Key;
- 消息总线:RabbitMQ/Kafka作为Aries Transport层,解决WebSocket被防火墙拦截;
- 机密管理:Azure Key Vault、华为云KMS、国密机,存储Wallet Master Secret;
- 日志合规:等级保护2.0,日志脱敏、国密TLS 1.3、GB/T 22239-2019。
- 性能调优:连接池复用、indy-sdk批量签名、Credential Definition缓存、Redis分布式Revocation Registry。
- 异常处理:IndyErrorCode.WalletItemNotFound、PoolTimeout、LedgerTimeout、CommonIOError,需封装为领域异常返回标准化ProblemDetails。
答案
下面给出可直接落地到国内项目的最小可运行示例,已解决“代理上网+国密TLS+Wallet密码托管”三大痛点。
场景:甲方为某省大数据局,要求“身份认证中台”对外签发“数据共享授权凭证”,对接方包括Java、Go、Python异构系统,全程需符合《GB/T 35273个人信息安全技术规范》。
-
环境准备
- 安装.NET 6 SDK(国产操作系统统信UOS已官方支持)。
- NuGet引用:
<PackageReference Include="Sphereon.SDK.Aries" Version="1.9.2" /> <PackageReference Include="Hyperledger.Indy.Sdk" Version="1.16.0" /> <PackageReference Include="Microsoft.Extensions.Hosting" Version="6.0.1" /> <PackageReference Include="Nacos.AspNetCore" Version="1.3.4" /> - 把省政务云Indy Pool的genesis文件放入
config/pool_genesis.txn,并配置国密TLS证书到appsettings.json的IndyPoolTlsPath。
-
启动类(Program.cs)
using Sphereon.SDK.Aries; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Nacos.AspNetCore; var builder = Host.CreateApplicationBuilder(args); builder.Services.AddNacosAspNetCore(builder.Configuration.GetSection("Nacos")); builder.Services.AddSingleton<IAriesClient>(sp => { var nacos = sp.GetRequiredService<INacosNamingService>(); var poolIp = nacos.SelectOneHealthyInstance("indypool").Result.Ip; // 动态发现 return AriesClientBuilder.Create() .WithPoolOptions(new PoolOptions { GenesisFilename = "config/pool_genesis.txn", PoolConfig = $"{{\"genesis_txn\":\"{poolIp}:9701\"}}" }) .WithWalletOptions(new WalletOptions { Id = "databureau_wallet", Key = builder.Configuration["Wallet:Key"], // 从KMS读取 KeyDerivationMethod = KeyDerivationMethod.Raw }) .WithEndpoint("https://databureau.aries.gov.cn") // 国密证书已绑定 .Build(); }); builder.Services.AddHostedService<CredentialIssuerService>(); var host = builder.Build(); host.Run(); -
凭证签发后台服务(CredentialIssuerService.cs)
public class CredentialIssuerService : BackgroundService { private readonly IConnectionService _conn; private readonly ICredentialService _cred; private readonly ILogger<CredentialIssuerService> _log; public CredentialIssuerService(IAriesClient client, ILogger<CredentialIssuerService> log) { _conn = client.GetService<IConnectionService>(); _cred = client.GetService<ICredentialService>(); _log = log; } protected override async Task ExecuteAsync(CancellationToken stoppingToken) { // 1. 等待外部业务系统通过gRPC调用本服务,拿到ConnectionId var connectionId = await WaitForConnectionInvitation(stoppingToken); // 2. 创建Credential Definition(只需一次,缓存到Redis) var credDefId = await GetOrCreateCredDefAsync(); // 3. 构造VC,符合省标《数据共享授权凭证规范》 var attributes = new[] { new CredentialAttribute("userName", "张三"), new CredentialAttribute("idNo", "123456789012345678", true), // 选择性披露 new CredentialAttribute("dataScope", "社保"), new CredentialAttribute("expiry", DateTimeOffset.UtcNow.AddDays(30).ToUnixTimeSeconds().ToString()) }; var (offer, _) = await _cred.CreateOfferAsync(credDefId, connectionId, attributes); _log.LogInformation("Offer已发送 {OfferJson}", offer.ToJson()); // 4. 等待Holder接受并返回CredentialId,存储到业务库 var credential = await WaitForCredentialAckAsync(connectionId, offer.Id, stoppingToken); await StoreToDbAsync(credential); } private async Task<string> GetOrCreateCredDefAsync() { var cache = ConnectionMultiplexer.Connect(Configuration["Redis:Conn"]).GetDatabase(); const string key = "databureau:creddefid"; if (await cache.KeyExistsAsync(key)) return await cache.StringGetAsync(key); var schemaId = await _cred.CreateSchemaAsync("DataShareAuthSchema", "1.0", new[] { "userName", "idNo", "dataScope", "expiry" }); var credDef = await _cred.CreateCredentialDefinitionAsync(schemaId, "databureau", Tag: "default"); await cache.StringSetAsync(key, credDef.Id, TimeSpan.FromDays(365)); return credDef.Id; } } -
零知识证明验证(ProofController.cs)
[ApiController] [Route("api/verify")] public class ProofController : ControllerBase { private readonly IProofService _proof; public ProofController(IAriesClient client) => _proof = client.GetService<IProofService>(); [HttpPost("authorization")] public async Task<IActionResult> Verify([FromBody] VerifyRequest req) { var proofRequest = new ProofRequest { Name = "数据共享授权验证", Version = "1.0", RequestedAttributes = new[] { new ProofAttributeInfo { Name = "dataScope", Restrictions = new[] { new AttributeFilter { CredDefId = req.CredDefId } } }, new ProofAttributeInfo { Name = "expiry", PredicateType = PredicateType.GreaterThanOrEqualTo, PredicateValue = DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString() } }, RequestedPredicates = new[] { new ProofPredicateInfo { Name = "idNo", PredicateType = PredicateType.GreaterThan, PredicateValue = "0", Restrictions = new[] { new AttributeFilter { CredDefId = req.CredDefId } } } }, Nonce = await _proof.GenerateNonceAsync() }; var (request, _) = await _proof.CreateRequestAsync(proofRequest, req.ConnectionId); return Ok(new { Request = request, Nonce = proofRequest.Nonce }); } } -
国密与合规要点
- 在CentOS或统信UOS上编译
libindy时打开--features=sm开关,启用SM2签名验证。 - 把Wallet的Master Secret存入华为云KMS,调用
KMSEncryptionService实现IWalletKeyProvider,满足等保三级“密钥不出机”要求。 - 日志采用“国密SM4+脱敏”双写,敏感字段(idNo)写入前用
SHA256SM3杂凑并截断。
- 在CentOS或统信UOS上编译
-
单元测试(xUnit)
[Fact] public async Task Issue_Verify_FullFlow() { var client = _fixture.AriesClient; var conn = await client.GetService<IConnectionService>().CreateInvitationAsync(); var holder = await CreateHolderWalletAsync(); // 模拟Holder var connectionId = await holder.AcceptInvitationAsync(conn.Invitation); var credDefId = await _fixture.GetOrCreateCredDefAsync(); var (offer, _) = await client.GetService<ICredentialService>() .CreateOfferAsync(credDefId, connectionId, new[] { new CredentialAttribute("dataScope", "社保") }); var credential = await holder.AcceptCredentialOfferAsync(offer); var proofRequest = new ProofRequest { RequestedAttributes = new[] { new ProofAttributeInfo { Name = "dataScope" } }, Nonce = await client.GetService<IProofService>().GenerateNonceAsync() }; var (request, _) = await client.GetService<IProofService>().CreateRequestAsync(proofRequest, connectionId); var proof = await holder.CreateProofAsync(request); var valid = await client.GetService<IProofService>().VerifyProofAsync(request, proof); Assert.True(valid); }
拓展思考
- 性能压测:单Agent 500 QPS时,Indy Pool共识延迟成为瓶颈,可调研“AnonCreds RS”+“BBSPresentation”替代方案,或把Credential Definition缓存到Redis Cluster并开启批量签名。
- 多租隔离:省大数据局需给各地市分配独立Wallet,建议用
WalletOptions.SubWalletId+KeyPrefix模式,结合OPA或ABAC做细粒度授权。 - 链下数据:VC原文体积大,可采用IPFS+BSN文昌链做“链下存储、链上哈希”,但需符合《数据出境安全评估办法》,敏感数据必须留在省内政务云。
- 互认互通:与“沪链”“粤链”等异构链互认,需实现
did:bsnMethod Driver,解析DID Document时支持国密公钥格式,同时把CRL(证书撤销列表)同步到对方链的CouchDB状态库。 - 未来演进:Aries RFC 0755提出“AnonCreds v2”将完全脱离Indy,改用
bbs-signatures+ldp-bbs2022,Sphereon已提供预览包,可提前在.NET 7+做技术预研,避免 Indy-SDK 停止维护带来的技术债。