kmvi / bc-xml-security

XML Signature and XML Encryption using Bouncy Castle (C#)
MIT License
13 stars 9 forks source link
bouncy-castle cryptography csharp ws-security xml-encryption xml-security xml-signature xmldsig xmlenc

bc-xml-security

Implementation of the XML Security standards using Bouncy Castle:

Adapted from .NET Core sources.

Example

See samples folder

// Load certificate and private key form PKCS12 container
Pkcs12Store store = new Pkcs12StoreBuilder().Build();
using (FileStream strm = File.OpenRead(@"d:\123.pfx"))
    store.Load(strm, new [] { '1' });
string alias = store.Aliases.First();
X509Certificate cert = store.GetCertificate(alias).Certificate;
AsymmetricKeyParameter privKey = store.GetKey(alias).Key;

// Element to sign
var doc = new XmlDocument();
doc.LoadXml("<a id=\"test\">some test node</a>");

var sgn = new SignedXml(doc);
var rf = new Reference();
rf.AddTransform(new XmlDsigEnvelopedSignatureTransform());
rf.AddTransform(new XmlDsigC14NTransform());
rf.DigestMethod = SignedXml.XmlDsigSHA1Url;
rf.Uri = "#test";

sgn.SignedInfo.CanonicalizationMethod = SignedXml.XmlDsigExcC14NTransformUrl;
sgn.AddReference(rf);
sgn.KeyInfo = new KeyInfo();
sgn.KeyInfo.AddClause(new KeyInfoX509Data(cert));
sgn.SignedInfo.SignatureMethod = SignedXml.XmlDsigRSASHA1Url;
sgn.SigningKey = privKey;

sgn.ComputeSignature();
XmlElement signature = sgn.GetXml(); // <Signature xmlns="http://www.w3.org/2000/09/xmldsig#"> ...

// Check signature
var sgn2 = new SignedXml(doc);
sgn2.LoadXml(signature);
sgn2.CheckSignature(cert, true);