C# 密码学库

C# 密码学库

...

C# 与 .NET 中的密码学

  • Bouncy Castle .NET 与 Nethereum:哈希、ECC 和 ECDSA

.NET 密码学与 Bouncy Castle .NET

  • C# 与 .NET 中的密码学基于:
  • Nethereum——面向以太坊和 secp256k1 的简化库

C# 中的 ECDSA:初始化应用程序

NuGet 安装 "Nethereum.Signer" 包

dotnet add package Nethereum.Signer

导入 Nethereum Signer 命名空间:

using Nethereum.Signer;
using Nethereum.Signer.Crypto;
using Nethereum.Util;
using Nethereum.Hex.HexConvertors.Extensions;

此时也可以使用 Bouncy Castle 命名空间,例如:

Org.BouncyCastle.Math.EC.ECPoint p = …;

C# 中的 ECDSA:生成或加载密钥

// var privKey = EthECKey.GenerateKey(); // Random private key
var privKey = new EthECKey( "97ddae0f3a25b92268175400149d65d6887b9cefaf28ea2c078e05cdc15a3c0a");
byte[] pubKeyCompressed = new ECKey(
  privKey.GetPrivateKeyAsBytes(), true).GetPubKey(true);
Console.WriteLine("Private key: {0}",
  privKey.GetPrivateKey().Substring(4));
Console.WriteLine("Public key: {0}",
  privKey.GetPubKey().ToHex().Substring(2));
Console.WriteLine("Public key (compressed): {0}",
  pubKeyCompressed.ToHex());

完整示例:https://gist.github.com/nakov/f2a579eb9893b29338b11e063d6f80c2

C# 中的 ECDSA:为消息签名

string msg = "Message for signing";
byte[] msgBytes = Encoding.UTF8.GetBytes(msg);
byte[] msgHash = new Sha3Keccack().CalculateHash(msgBytes);
var signature = privKey.SignAndCalculateV(msgHash);

Console.WriteLine("Msg: {0}", msg);
Console.WriteLine("Msg hash: {0}", msgHash.ToHex());
Console.WriteLine("Signature: [v = {0}, r = {1}, s = {2}]",
  signature.V[0] - 27,
  signature.R.ToHex(),
  signature.S.ToHex());

完整示例:https://gist.github.com/nakov/f2a579eb9893b29338b11e063d6f80c2

C# 中的 ECDSA:验证消息

var pubKeyRecovered =
  EthECKey.RecoverFromSignature(signature, msgHash);
Console.WriteLine("Recovered pubKey: {0}",
  pubKeyRecovered.GetPubKey().ToHex().Substring(2));

bool validSig = pubKeyRecovered.Verify(msgHash, signature);
Console.WriteLine("Signature valid? {0}", validSig);

完整示例:https://gist.github.com/nakov/f2a579eb9893b29338b11e063d6f80c2

results matching ""

    No results matching ""