[英]Bouncy Castle Sign and Verify SHA256 Certificate With C#
我已經通過大量示例說明人們如何使用 Bouncy Castle 動態生成 RSA 密鑰對,然后在一個代碼塊中對所有內容進行簽名和驗證。 這些答案很棒,真的幫助我快速上手!
也就是說,我需要創建一個客戶端,該客戶端可以通過 WCF JSON 調用公鑰,以便稍后用於簽名驗證,但我似乎無法使其正常工作。 首先是我用來生成證書的代碼:
public System.Security.Cryptography.X509Certificates.X509Certificate2 LoadCertificate()
{
System.Security.Cryptography.X509Certificates.X509Certificate2 returnX509 = null;
//X509Certificate returnCert = null;
try
{
returnX509 = new System.Security.Cryptography.X509Certificates.X509Certificate2(CertificateName, CertificatePassword);
//returnCert = DotNetUtilities.FromX509Certificate(returnX509);
}
catch
{
Console.WriteLine("Failed to obtain cert - trying to make one now.");
try
{
Guid nameGuid = Guid.NewGuid();
AsymmetricCipherKeyPair kp;
var x509 = GenerateCertificate("CN=Server-CertA-" + nameGuid.ToString(), out kp);
SaveCertificateToFile(x509, kp, CertificateName, CertificateAlias, CertificatePassword);
returnX509 = new System.Security.Cryptography.X509Certificates.X509Certificate2(CertificateName, CertificatePassword);
//returnCert = DotNetUtilities.FromX509Certificate(returnX509);
Console.WriteLine("Successfully wrote and retrieved cert!");
}
catch (Exception exc)
{
Console.WriteLine("Failed to create cert - exception was: " + exc.ToString());
}
}
return returnX509;
}
完成后,我然后使用以下代碼對消息進行簽名:
public string SignData(string Message, string PrivateKey)
{
try
{
byte[] orgBytes = UnicodeEncoding.ASCII.GetBytes(Message);
byte[] privateKey = UnicodeEncoding.ASCII.GetBytes(PrivateKey);
string curveName = "P-521";
X9ECParameters ecP = NistNamedCurves.GetByName(curveName);
ECDomainParameters ecSpec = new ECDomainParameters(ecP.Curve, ecP.G, ecP.N, ecP.H, ecP.GetSeed());
ISigner signer = SignerUtilities.GetSigner("SHA-256withECDSA");
BigInteger biPrivateKey = new BigInteger(privateKey);
ECPrivateKeyParameters keyParameters = new ECPrivateKeyParameters(biPrivateKey, ecSpec);
signer.Init(true, keyParameters);
signer.BlockUpdate(orgBytes, 0, orgBytes.Length);
byte[] data = signer.GenerateSignature();
//Base64 Encode
byte[] encodedBytes;
using (MemoryStream encStream = new MemoryStream())
{
base64.Encode(orgBytes, 0, orgBytes.Length, encStream);
encodedBytes = encStream.ToArray();
}
if (encodedBytes.Length > 0)
return UnicodeEncoding.ASCII.GetString(encodedBytes);
else
return "";
}
catch (Exception exc)
{
Console.WriteLine("Signing Failed: " + exc.ToString());
return "";
}
}
最后,我試圖驗證:
public bool VerifySignature(string PublicKey, string Signature, string Message)
{
try
{
AsymmetricKeyParameter pubKey = new AsymmetricKeyParameter(false);
var publicKey = PublicKeyFactory.CreateKey(Convert.FromBase64String(PublicKey));
ISigner signer = SignerUtilities.GetSigner("SHA-256withECDSA");
byte[] orgBytes = UnicodeEncoding.ASCII.GetBytes(Message);
signer.Init(false, publicKey);
signer.BlockUpdate(orgBytes, 0, orgBytes.Length);
//Base64 Decode
byte[] encodeBytes = UnicodeEncoding.ASCII.GetBytes(Signature);
byte[] decodeBytes;
using (MemoryStream decStream = new MemoryStream())
{
base64.Decode(encodeBytes, 0, encodeBytes.Length, decStream);
decodeBytes = decStream.ToArray();
}
return signer.VerifySignature(decodeBytes);
}
catch (Exception exc)
{
Console.WriteLine("Verification failed with the error: " + exc.ToString());
return false;
}
}
這是我的測試應用程序:
Console.WriteLine("Attempting to load cert...");
System.Security.Cryptography.X509Certificates.X509Certificate2 thisCert = LoadCertificate();
if (thisCert != null)
{
Console.WriteLine(thisCert.IssuerName.Name);
Console.WriteLine("Signing the text - Mary had a nuclear bomb");
string signature = SignData("Mary had a nuclear bomb", thisCert.PublicKey.Key.ToXmlString(true));
Console.WriteLine("Signature: " + signature);
Console.WriteLine("Verifying Signature");
if (VerifySignature(thisCert.PublicKey.Key.ToXmlString(false), signature, "Mary had a nuclear bomb."))
Console.WriteLine("Valid Signature!");
else
Console.WriteLine("Signature NOT valid!");
}
當我嘗試運行測試應用程序時,我收到錯誤“密鑰在指定狀態下無效。” 在線上:
string signature = SignData("Mary had a nuclear bomb", thisCert.PublicKey.Key.ToXmlString(true));
我嘗試用“PrivateKey”替換“PublicKey.Key”,但這並沒有什么區別。 我也嘗試使用 BounceyCastle X509Certificate,但我不知道如何提取密鑰。 有任何想法嗎?
謝謝!
更新:我確實想出了如何僅使用 .NET 進行簽名和驗證,但這對我來說並不是很有用,因為我需要跨平台,而且事實上,我們的主要客戶端應用程序是用 Java 編寫的。 有人知道相當於以下代碼的充氣城堡嗎?
public string SignDataAsXml(string Message, X509Certificate2 ThisCert)
{
XmlDocument doc = new XmlDocument();
doc.PreserveWhitespace = false;
doc.LoadXml("<core>" + Message + "</core>");
// Create a SignedXml object.
SignedXml signedXml = new SignedXml(doc);
// Add the key to the SignedXml document.
signedXml.SigningKey = ThisCert.PrivateKey;
// Create a reference to be signed.
Reference reference = new Reference();
reference.Uri = "";
// Add an enveloped transformation to the reference.
XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform();
reference.AddTransform(env);
// Add the reference to the SignedXml object.
signedXml.AddReference(reference);
// Create a new KeyInfo object.
KeyInfo keyInfo = new KeyInfo();
// Load the certificate into a KeyInfoX509Data object
// and add it to the KeyInfo object.
keyInfo.AddClause(new KeyInfoX509Data(ThisCert));
// Add the KeyInfo object to the SignedXml object.
signedXml.KeyInfo = keyInfo;
// Compute the signature.
signedXml.ComputeSignature();
// Get the XML representation of the signature and save
// it to an XmlElement object.
XmlElement xmlDigitalSignature = signedXml.GetXml();
// Append the element to the XML document.
doc.DocumentElement.AppendChild(doc.ImportNode(xmlDigitalSignature, true));
if (doc.FirstChild is XmlDeclaration)
{
doc.RemoveChild(doc.FirstChild);
}
using (var stringWriter = new StringWriter())
{
using (var xmlTextWriter = XmlWriter.Create(stringWriter))
{
doc.WriteTo(xmlTextWriter);
xmlTextWriter.Flush();
return stringWriter.GetStringBuilder().ToString();
}
}
}
public bool VerifyXmlSignature(string XmlMessage, X509Certificate2 ThisCert)
{
// Create a new XML document.
XmlDocument xmlDocument = new XmlDocument();
// Load the passed XML file into the document.
xmlDocument.LoadXml(XmlMessage);
// Create a new SignedXml object and pass it the XML document class.
SignedXml signedXml = new SignedXml(xmlDocument);
// Find the "Signature" node and create a new XmlNodeList object.
XmlNodeList nodeList = xmlDocument.GetElementsByTagName("Signature");
// Load the signature node.
signedXml.LoadXml((XmlElement)nodeList[0]);
// Check the signature and return the result.
return signedXml.CheckSignature(ThisCert, true);
}
Bouncy Castle 根本不支持 XML 格式。 除非您的用例嚴格要求它,否則您會發現僅使用 Base64 編碼更容易,證書 (X.509) 和私鑰 (PKCS#8) 以 PEM 格式存儲。 這些都是字符串格式,因此應該可以直接與 JSON 一起使用。
代碼示例中還有其他問題:簽名應該使用私鑰,簽名不應該被視為 ASCII 字符串,可能您的消息實際上是 UTF8。 我希望內部符號/驗證例程可能看起來像這樣:
public string SignData(string msg, ECPrivateKeyParameters privKey)
{
try
{
byte[] msgBytes = Encoding.UTF8.GetBytes(msg);
ISigner signer = SignerUtilities.GetSigner("SHA-256withECDSA");
signer.Init(true, privKey);
signer.BlockUpdate(msgBytes, 0, msgBytes.Length);
byte[] sigBytes = signer.GenerateSignature();
return Convert.ToBase64String(sigBytes);
}
catch (Exception exc)
{
Console.WriteLine("Signing Failed: " + exc.ToString());
return null;
}
}
public bool VerifySignature(ECPublicKeyParameters pubKey, string signature, string msg)
{
try
{
byte[] msgBytes = Encoding.UTF8.GetBytes(msg);
byte[] sigBytes = Convert.FromBase64String(signature);
ISigner signer = SignerUtilities.GetSigner("SHA-256withECDSA");
signer.Init(false, pubKey);
signer.BlockUpdate(msgBytes, 0, msgBytes.Length);
return signer.VerifySignature(sigBytes);
}
catch (Exception exc)
{
Console.WriteLine("Verification failed with the error: " + exc.ToString());
return false;
}
}
另一個問題是,我認為 .NET 直到 .NET 3.5 才獲得 ECDSA 支持,無論如何,.NET 1.1 中沒有 ECDsa 類(這是 BC 即將發布的 1.8 版本的目標 - 我們將在此之后“現代化” ),所以 DotNetUtilities 不支持 ECDSA。 但是,我們可以導出到 PKCS#12 並導入到 BC。 一個示例程序:
public void Program()
{
Console.WriteLine("Attempting to load cert...");
System.Security.Cryptography.X509Certificates.X509Certificate2 thisCert = LoadCertificate();
Console.WriteLine(thisCert.IssuerName.Name);
Console.WriteLine("Signing the text - Mary had a nuclear bomb");
byte[] pkcs12Bytes = thisCert.Export(X509ContentType.Pkcs12, "dummy");
Pkcs12Store pkcs12 = new Pkcs12StoreBuilder().Build();
pkcs12.Load(new MemoryStream(pkcs12Bytes, false), "dummy".ToCharArray());
ECPrivateKeyParameters privKey = null;
foreach (string alias in pkcs12.Aliases)
{
if (pkcs12.IsKeyEntry(alias))
{
privKey = (ECPrivateKeyParameters)pkcs12.GetKey(alias).Key;
break;
}
}
string signature = SignData("Mary had a nuclear bomb", privKey);
Console.WriteLine("Signature: " + signature);
Console.WriteLine("Verifying Signature");
var bcCert = DotNetUtilities.FromX509Certificate(thisCert);
if (VerifySignature((ECPublicKeyParameters)bcCert.GetPublicKey(), signature, "Mary had a nuclear bomb."))
Console.WriteLine("Valid Signature!");
else
Console.WriteLine("Signature NOT valid!");
}
我還沒有真正測試過上面的任何代碼,但它應該給你一些東西。 請注意,BC 也有密鑰和證書生成器,因此您可以選擇將 BC 用於所有內容(XML 除外!),並僅在必要時向/從 .NET 區域導出/導入。
感謝 Petters 的回答,我想添加代碼以使用 RSA 算法驗證簽名。
public bool VerifySignature(AsymmetricKeyParameter pubKey, string signature, string msg)
{
try
{
byte[] msgBytes = Encoding.UTF8.GetBytes(msg);
byte[] sigBytes = Convert.FromBase64String(signature);
ISigner signer = SignerUtilities.GetSigner("SHA-256withRSA");
signer.Init(false, pubKey);
signer.BlockUpdate(msgBytes, 0, msgBytes.Length);
return signer.VerifySignature(sigBytes);
}
catch (Exception exc)
{
Console.WriteLine("Verification failed with the error: " + exc.ToString());
return false;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.