有没有人知道如何使用充气城堡在c#中签名数据的简单教程或示例代码。在Java中有大量的教程和示例。我在c#中找不到一个例子。有谁知道怎么做?
答案 0 :(得分:32)
好的,我找不到任何关于如何做到这一点的文档。但我最终搞清楚了。 我在这里粘贴完整的代码,希望它可以在将来帮助某人。
此类将为提供的字符串计算带有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);
}
}
}
答案 1 :(得分:4)
看看Bouncy Castle网站。存档包含源和示例。 http://www.bouncycastle.org/csharp/download/bccrypto-net-1.7-src-ext.zip
作为示例,有许多NUnit测试。 下面是使用RSA算法作为样本加密数据字节数组的方法代码,但在Bouncy Castle的源代码和测试中,您可以找到更多样本。
public static byte[] Encrypt(byte[] data, AsymmetricKeyParameter key)
{
RsaEngine e = new RsaEngine();
e.Init(true, key);
int blockSize = e.GetInputBlockSize();
List<byte> output = new List<byte>();
for (int chunkPosition = 0; chunkPosition < data.Length; chunkPosition += blockSize)
{
int chunkSize = Math.Min(blockSize, data.Length - (chunkPosition * blockSize));
output.AddRange(e.ProcessBlock(data, chunkPosition, chunkSize));
}
return output.ToArray();
}
答案 2 :(得分:0)
答案 3 :(得分:0)
.NET不会公开加密算法以供选择。 RSA有很多教程。