gpt4 book ai didi

C# 使用 BouncyCaSTLe 使用 RSA 对数据进行签名

转载 作者:可可西里 更新时间:2023-11-01 03:13:33 25 4
gpt4 key购买 nike

有谁知道如何使用充气城堡在 C# 中签署数据的简单教程或示例代码。在 Java 中有大量的教程和示例。我在 C# 中找不到一个示例。有谁知道如何做到这一点?

最佳答案

好吧,我找不到任何关于如何执行此操作的文档。但我最终弄明白了。我将完整的代码粘贴在这里,希望它能在未来帮助到某人。

此类将为提供的字符串计算带有 sha1 散列的 RSA 签名,并对其进行验证。

using System;
using System.IO;
using System.Text;
using Org.BouncyCastle.Asn1;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.OpenSsl;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Utilities.Encoders;

namespace API.Crypto
{
public class RsaSha1Signing
{
private RsaKeyParameters MakeKey(String modulusHexString, String exponentHexString, bool isPrivateKey)
{
var modulus = new Org.BouncyCastle.Math.BigInteger(modulusHexString, 16);
var exponent = new Org.BouncyCastle.Math.BigInteger(exponentHexString, 16);

return new RsaKeyParameters(isPrivateKey, modulus, exponent);
}

public String Sign(String data, String privateModulusHexString, String privateExponentHexString)
{
/* Make the key */
RsaKeyParameters key = MakeKey(privateModulusHexString, privateExponentHexString, true);

/* Init alg */
ISigner sig = SignerUtilities.GetSigner("SHA1withRSA");

/* Populate key */
sig.Init(true, key);

/* Get the bytes to be signed from the string */
var bytes = Encoding.UTF8.GetBytes(data);

/* Calc the signature */
sig.BlockUpdate(bytes, 0, bytes.Length);
byte[] signature = sig.GenerateSignature();

/* Base 64 encode the sig so its 8-bit clean */
var signedString = Convert.ToBase64String(signature);

return signedString;
}

public bool Verify(String data, String expectedSignature, String publicModulusHexString, String publicExponentHexString)
{
/* Make the key */
RsaKeyParameters key = MakeKey(publicModulusHexString, publicExponentHexString, false);

/* Init alg */
ISigner signer = SignerUtilities.GetSigner("SHA1withRSA");

/* Populate key */
signer.Init(false, key);

/* Get the signature into bytes */
var expectedSig = Convert.FromBase64String(expectedSignature);

/* Get the bytes to be signed from the string */
var msgBytes = Encoding.UTF8.GetBytes(data);

/* Calculate the signature and see if it matches */
signer.BlockUpdate(msgBytes, 0, msgBytes.Length);
return signer.VerifySignature(expectedSig);
}
}
}

关于C# 使用 BouncyCaSTLe 使用 RSA 对数据进行签名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8830510/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com