本文整理汇总了C#中System.Security.Cryptography.Xml.Reference类的典型用法代码示例。如果您正苦于以下问题:C# Reference类的具体用法?C# Reference怎么用?C# Reference使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
Reference类属于System.Security.Cryptography.Xml命名空间,在下文中一共展示了Reference类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: SignXmlDocument
private static XmlDocument SignXmlDocument(XmlDocument xmlDocument, X509Certificate2 signingCertificate)
{
// Создание подписчика XML-документа
var signedXml = new GostSignedXml(xmlDocument);
// Установка ключа для создания подписи
signedXml.SetSigningCertificate(signingCertificate);
// Ссылка на узел, который нужно подписать, с указанием алгоритма хэширования
var dataReference = new Reference { Uri = "#Id1", DigestMethod = GostSignedXml.XmlDsigGost3411Url };
// Метод преобразования, применяемый к данным перед их подписью
var dataTransform = CreateDataTransform();
dataReference.AddTransform(dataTransform);
// Установка ссылки на узел
signedXml.AddReference(dataReference);
// Установка информации о сертификате, который использовался для создания подписи
var keyInfo = new KeyInfo();
keyInfo.AddClause(new KeyInfoX509Data(signingCertificate));
signedXml.KeyInfo = keyInfo;
// Вычисление подписи
signedXml.ComputeSignature();
// Получение XML-представления подписи
var signatureXml = signedXml.GetXml();
// Добавление подписи в исходный документ
xmlDocument.DocumentElement.AppendChild(xmlDocument.ImportNode(signatureXml, true));
return xmlDocument;
}
示例2: SignRequestXml
/// <summary>
/// Adds a digital signature to the outgoing request message, before sending it to Acquirer.
/// </summary>
/// <param name="requestXml">
/// The unsigned request XML message.
/// </param>
/// <returns>
/// The request message, including digital signature.
/// </returns>
public string SignRequestXml(XDocument requestXml)
{
XmlDocument document = ToXmlDocument(requestXml);
RSACryptoServiceProvider key = ExtractPrivateKeyFrom(acceptantPrivateCertificate);
var signedXml = new SignedXml(document) { SigningKey = key };
signedXml.SignedInfo.SignatureMethod = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256";
signedXml.SignedInfo.CanonicalizationMethod = "http://www.w3.org/2001/10/xml-exc-c14n#";
// Add a signing reference, the uri is empty and so the whole document is signed.
var reference = new Reference { DigestMethod = @"http://www.w3.org/2001/04/xmlenc#sha256" };
reference.AddTransform(new XmlDsigEnvelopedSignatureTransform());
reference.Uri = "";
signedXml.AddReference(reference);
// Add the certificate as key info. Because of this, the certificate
// with the public key will be added in the signature part.
var keyInfo = new KeyInfo();
keyInfo.AddClause(new KeyInfoName(acceptantPrivateCertificate.Thumbprint));
signedXml.KeyInfo = keyInfo;
// Generate the signature.
signedXml.ComputeSignature();
XmlElement xmlSignature = signedXml.GetXml();
document.DocumentElement.AppendChild(document.ImportNode(xmlSignature, true));
// Check that outgoing signature is valid. Private certificate also contains public part.
VerifyDocumentSignature(document, acceptantPrivateCertificate);
return GetContentsFrom(document);
}
示例3: getReference
private Reference getReference(XmlNode mainNode)
{
Reference reference = new Reference();
string mainNodeID = mainNode.Attributes["Id"].InnerText;
reference.Uri = "#" + mainNodeID;
reference.DigestMethod = @"http://www.w3.org/2001/04/xmlenc#sha256";
reference.AddTransform(new XmlDsigEnvelopedSignatureTransform());
return reference;
}
示例4: GenerateSignature
public static XmlElement GenerateSignature(XmlDocument licenseDocument, IPrivateCryptoKey privateKey)
{
using (var privateKeyProvider = new RsaPrivateKeyProvider())
{
var reference = new Reference { Uri = string.Empty };
reference.AddTransform(new XmlDsigEnvelopedSignatureTransform());
var signedXml = new SignedXml(licenseDocument) { SigningKey = privateKeyProvider.Recreate(privateKey) };
signedXml.AddReference(reference);
signedXml.ComputeSignature();
return signedXml.GetXml();
}
}
示例5: ComputeSignature
public void ComputeSignature(X509Certificate2 certificate, X509IncludeOption includeOption, string id)
{
SigningKey = (RSACryptoServiceProvider)certificate.PrivateKey;
SignedInfo.CanonicalizationMethod = Saml2SignedXml.XmlDsigExcC14NTransformUrl;
//SignedInfo.SignatureMethod = SecurityAlgorithms.RsaSha256Signature;
var reference = new Reference("#" + id);
// reference.DigestMethod = SecurityAlgorithms.Sha1Digest;
reference.AddTransform(new XmlDsigEnvelopedSignatureTransform());
reference.AddTransform(new XmlDsigExcC14NTransform());
AddReference(reference);
ComputeSignature();
KeyInfo = new KeyInfo();
KeyInfo.AddClause(new KeyInfoX509Data(certificate, includeOption));
}
示例6: Sign
// code outline borrowed from: http://blogs.msdn.com/shawnfa/archive/2003/11/12/57030.aspx
public static void Sign(XmlDocument doc, RSA key)
{
SignedXml signer = new SignedXml(doc);
// setup the key used to sign
signer.KeyInfo = new KeyInfo();
signer.KeyInfo.AddClause(new RSAKeyValue(key));
signer.SigningKey = key;
// create a reference to the root of the document
Reference orderRef = new Reference("");
orderRef.AddTransform(new XmlDsigEnvelopedSignatureTransform());
signer.AddReference(orderRef);
// add transforms that only select the order items, type, and
// compute the signature, and add it to the document
signer.ComputeSignature();
doc.DocumentElement.PrependChild(signer.GetXml());
}
示例7: Sign
/// <summary>
/// Sign
/// </summary>
/// <param name="input">The input.</param>
/// <param name="output">The output.</param>
/// <param name="certificate">The certificate.</param>
public override void Sign(Stream input, Stream output, X509Certificate2 certificate)
{
CheckInputOutputAndCertificate(input, output, certificate);
using (var rsaKey = (RSACryptoServiceProvider)certificate.PrivateKey)
{
var xmlDoc = new XmlDocument { PreserveWhitespace = true };
xmlDoc.Load(input);
var signedXml = new SignedXml(xmlDoc) {SigningKey = rsaKey};
var envelope = new XmlDsigEnvelopedSignatureTransform();
var reference = new Reference {Uri = ""};
reference.AddTransform(envelope);
signedXml.AddReference(reference);
signedXml.ComputeSignature();
var xmlDigitalSignature = signedXml.GetXml();
xmlDoc.DocumentElement.AppendChild(xmlDoc.ImportNode(xmlDigitalSignature, true));
xmlDoc.Save(output);
}
}
示例8: ApplySignature
public void ApplySignature(SamlResponse response, X509Certificate2 certificate, XmlDocument document)
{
var keyInfo = new KeyInfo();
keyInfo.AddClause(new KeyInfoX509Data(certificate));
var signedXml = new SignedXml(document)
{
SigningKey = certificate.PrivateKey,
KeyInfo = keyInfo
};
var reference = new Reference(AssertionIdPrefix + response.Id);
reference.AddTransform(new XmlDsigEnvelopedSignatureTransform());
signedXml.AddReference(reference);
signedXml.ComputeSignature();
var xml = signedXml.GetXml();
document.FindChild(AssertionElem).AppendChild(xml);
}
示例9: CreateSignature
public static XmlElement CreateSignature(XmlDocument document, X509Certificate2 certificate, string referenceId, string referenceValue)
{
var samlSignedXml = new SamlSignedXml(document, referenceId);
// Add the key to the SignedXml xmlDocument.
samlSignedXml.SigningKey = certificate.PrivateKey;
// Create a reference to be signed.
var reference = new Reference();
reference.Uri = string.Empty;
reference.Uri = "#" + referenceValue;
// Add an enveloped transformation to the reference.
var env = new XmlDsigEnvelopedSignatureTransform();
var env2 = new XmlDsigC14NTransform();
reference.AddTransform(env);
reference.AddTransform(env2);
// Add the reference to the SignedXml object.
samlSignedXml.AddReference(reference);
// Add an RSAKeyValue KeyInfo (optional; helps recipient find key to validate).
var keyInfo = new KeyInfo();
var keyData = new KeyInfoX509Data(certificate);
keyInfo.AddClause(keyData);
samlSignedXml.KeyInfo = keyInfo;
// Compute the signature.
samlSignedXml.ComputeSignature();
// Get the XML representation of the signature and save it to an XmlElement object.
var xmlDigitalSignature = samlSignedXml.GetXml();
return xmlDigitalSignature;
}
示例10: SignDocument
/// <summary>
/// Signs the document given as an argument.
/// </summary>
/// <param name="doc">The doc.</param>
private static void SignDocument(XmlDocument doc)
{
var signedXml = new SignedXml(doc);
signedXml.SignedInfo.CanonicalizationMethod = SignedXml.XmlDsigExcC14NTransformUrl;
// TODO Dynamically dig out the correct ID attribute from the XmlDocument.
var reference = new Reference("#_b8977dc86cda41493fba68b32ae9291d");
var envelope = new XmlDsigEnvelopedSignatureTransform();
reference.AddTransform(envelope);
// NOTE: C14n may require the following list of namespace prefixes. Seems to work without it, though.
// List<string> prefixes = new List<string>();
// prefixes.Add(doc.DocumentElement.GetPrefixOfNamespace("http://www.w3.org/2000/09/xmldsig#"));
// prefixes.Add(doc.DocumentElement.GetPrefixOfNamespace("http://www.w3.org/2001/XMLSchema-instance"));
// prefixes.Add(doc.DocumentElement.GetPrefixOfNamespace("http://www.w3.org/2001/XMLSchema"));
// prefixes.Add(doc.DocumentElement.GetPrefixOfNamespace("urn:oasis:names:tc:SAML:2.0:assertion"));
// XmlDsigExcC14NTransform C14NTransformer = new XmlDsigExcC14NTransform(string.Join(" ", prefixes.ToArray()).Trim());
var c14NTransformer = new XmlDsigExcC14NTransform();
reference.AddTransform(c14NTransformer);
signedXml.AddReference(reference);
// Add the key to the signature, so the assertion can be verified by itself.
signedXml.KeyInfo = new KeyInfo();
// Use RSA key for signing.
// CspParameters parameters = new CspParameters();
// parameters.KeyContainerName = "XML_DSIG_RSA_KEY";
// RSACryptoServiceProvider rsaKey = new RSACryptoServiceProvider(parameters);
// signedXml.SigningKey = rsaKey;
// signedXml.KeyInfo.AddClause(new RSAKeyValue(rsaKey));
// Use X509 Certificate for signing.
var cert = new X509Certificate2(@"Certificates\sts_dev_certificate.pfx", "test1234");
Assert.That(cert.HasPrivateKey);
signedXml.SigningKey = cert.PrivateKey;
signedXml.KeyInfo.AddClause(new KeyInfoX509Data(cert, X509IncludeOption.EndCertOnly));
// Information on the these and other "key info clause" types can be found at:
// ms-help://MS.MSDNQTR.v80.en/MS.MSDN.v80/MS.NETDEVFX.v20.en/CPref18/html/T_System_Security_Cryptography_Xml_KeyInfoClause_DerivedTypes.htm
// Do it!
signedXml.ComputeSignature();
var nodes = doc.DocumentElement.GetElementsByTagName("Issuer", Saml20Constants.Assertion);
Assert.That(nodes.Count == 1);
var node = nodes[0];
doc.DocumentElement.InsertAfter(doc.ImportNode(signedXml.GetXml(), true), node);
}
示例11: GetReferenceHash
private byte[] GetReferenceHash (Reference r, bool check_hmac)
{
Stream s = null;
XmlDocument doc = null;
if (r.Uri == String.Empty) {
doc = envdoc;
}
else if (r.Type == XmlSignature.Uri.Manifest) {
doc = GetManifest (r);
}
else {
doc = new XmlDocument ();
doc.PreserveWhitespace = true;
string objectName = null;
if (r.Uri.StartsWith ("#xpointer")) {
string uri = string.Join ("", r.Uri.Substring (9).Split (whitespaceChars));
if (uri.Length < 2 || uri [0] != '(' || uri [uri.Length - 1] != ')')
// FIXME: how to handle invalid xpointer?
uri = String.Empty;
else
uri = uri.Substring (1, uri.Length - 2);
if (uri == "/")
doc = envdoc;
else if (uri.Length > 6 && uri.StartsWith ("id(") && uri [uri.Length - 1] == ')')
// id('foo'), id("foo")
objectName = uri.Substring (4, uri.Length - 6);
}
else if (r.Uri [0] == '#') {
objectName = r.Uri.Substring (1);
}
else if (xmlResolver != null) {
// TODO: test but doc says that Resolver = null -> no access
try {
// no way to know if valid without throwing an exception
Uri uri = new Uri (r.Uri);
s = (Stream) xmlResolver.GetEntity (uri, null, typeof (Stream));
}
catch {
// may still be a local file (and maybe not xml)
s = File.OpenRead (r.Uri);
}
}
if (objectName != null) {
XmlElement found = null;
foreach (DataObject obj in m_signature.ObjectList) {
if (obj.Id == objectName) {
found = obj.GetXml ();
found.SetAttribute ("xmlns", SignedXml.XmlDsigNamespaceUrl);
doc.AppendChild (doc.ImportNode (found, true));
// FIXME: there should be theoretical justification of copying namespace declaration nodes this way.
foreach (XmlNode n in found.ChildNodes)
// Do not copy default namespace as it must be xmldsig namespace for "Object" element.
if (n.NodeType == XmlNodeType.Element)
FixupNamespaceNodes (n as XmlElement, doc.DocumentElement, true);
break;
}
}
if (found == null && envdoc != null) {
found = GetIdElement (envdoc, objectName);
if (found != null) {
doc.AppendChild (doc.ImportNode (found, true));
FixupNamespaceNodes (found, doc.DocumentElement, false);
}
}
if (found == null)
throw new CryptographicException (String.Format ("Malformed reference object: {0}", objectName));
}
}
if (r.TransformChain.Count > 0) {
foreach (Transform t in r.TransformChain) {
if (s == null) {
s = ApplyTransform (t, doc);
}
else {
t.LoadInput (s);
object o = t.GetOutput ();
if (o is Stream)
s = (Stream) o;
else
s = CanonicalizeOutput (o);
}
}
}
else if (s == null) {
// we must not C14N references from outside the document
// e.g. non-xml documents
if (r.Uri [0] != '#') {
s = new MemoryStream ();
doc.Save (s);
}
else {
// apply default C14N transformation
s = ApplyTransform (new XmlDsigC14NTransform (), doc);
}
}
HashAlgorithm digest = GetHash (r.DigestMethod, check_hmac);
return (digest == null) ? null : digest.ComputeHash (s);
}
示例12: GetManifest
private XmlDocument GetManifest (Reference r)
{
XmlDocument doc = new XmlDocument ();
doc.PreserveWhitespace = true;
if (r.Uri [0] == '#') {
// local manifest
if (signatureElement != null) {
XmlElement xel = GetIdElement (signatureElement.OwnerDocument, r.Uri.Substring (1));
if (xel == null)
throw new CryptographicException ("Manifest targeted by Reference was not found: " + r.Uri.Substring (1));
doc.AppendChild (doc.ImportNode (xel, true));
FixupNamespaceNodes (xel, doc.DocumentElement, false);
}
}
else if (xmlResolver != null) {
// TODO: need testing
Stream s = (Stream) xmlResolver.GetEntity (new Uri (r.Uri), null, typeof (Stream));
doc.Load (s);
}
if (doc.FirstChild != null) {
// keep a copy of the manifests to check their references later
if (manifests == null)
manifests = new ArrayList ();
manifests.Add (doc);
return doc;
}
return null;
}
示例13: AddReference
public void AddReference (Reference reference)
{
if (reference == null)
throw new ArgumentNullException ("reference");
m_signature.SignedInfo.AddReference (reference);
}
示例14: SignXmlFile
public static string SignXmlFile(string xml, RSA Key)
{
// Create a new XML document.
var doc = new XmlDocument();
// Format the document to ignore white spaces.
doc.PreserveWhitespace = false;
using (var textReader = new StringReader(xml))
{
doc.Load(new XmlTextReader(textReader));
}
// Create a SignedXml object.
var signedXml = new SignedXmlWithId(doc);
// Add the key to the SignedXml document.
signedXml.SigningKey = Key;
// Specify a canonicalization method.
signedXml.SignedInfo.CanonicalizationMethod = SignedXml.XmlDsigExcC14NTransformUrl;
// Set the InclusiveNamespacesPrefixList property.
var canMethod = (XmlDsigExcC14NTransform)signedXml.SignedInfo.CanonicalizationMethodObject;
var ref1 = new Reference("#Body52be6364-045f-1550-625d-b20b0390691e");
var ref2 = new Reference("#Timestamp5257ab43-882c-4937-3835-6763e9a2d700");
// Add an enveloped transformation to the reference.
var env = new XmlDsigEnvelopedSignatureTransform();
ref1.AddTransform(canMethod);
ref2.AddTransform(canMethod);
// Add the reference to the SignedXml object.
signedXml.AddReference(ref1);
signedXml.AddReference(ref2);
string keyInfoStr = "<KeyInfo><wsse:SecurityTokenReference xmlns:wsse=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\"><wsse:Reference URI=\"#holderOfKeyCertificate\" ValueType=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509v3\"/></wsse:SecurityTokenReference></KeyInfo>";
var xd = new XmlDocument();
xd.LoadXml(keyInfoStr);
var ki = new KeyInfo();
ki.LoadXml(xd.DocumentElement);
signedXml.KeyInfo = ki;
// Compute the signature.
//signedXml.ComputeSignature(KeyedHashAlgorithm.Create("HMACSHA256"));
signedXml.ComputeSignature();
// Get the XML representation of the signature and save
// it to an XmlElement object.
XmlElement xmlDigitalSignature = signedXml.GetXml();
xmlDigitalSignature.SetAttribute("Id", "holderOfKeyProofSignature");
var sb = new StringBuilder();
using (var sw = new StringWriter(sb))
{
using (var writer = new XmlTextWriter(sw))
{
xmlDigitalSignature.WriteTo(writer);
}
}
return sb.ToString();
}
示例15: LoadXml
public void LoadXml (XmlElement value)
{
if (value == null)
throw new ArgumentNullException ("value");
if ((value.LocalName != XmlSignature.ElementNames.SignedInfo) || (value.NamespaceURI != XmlSignature.NamespaceURI))
throw new CryptographicException ();
id = GetAttribute (value, XmlSignature.AttributeNames.Id);
c14nMethod = XmlSignature.GetAttributeFromElement (value, XmlSignature.AttributeNames.Algorithm, XmlSignature.ElementNames.CanonicalizationMethod);
XmlElement sm = XmlSignature.GetChildElement (value, XmlSignature.ElementNames.SignatureMethod, XmlSignature.NamespaceURI);
if (sm != null) {
signatureMethod = sm.GetAttribute (XmlSignature.AttributeNames.Algorithm);
XmlElement length = XmlSignature.GetChildElement (sm, XmlSignature.ElementNames.HMACOutputLength, XmlSignature.NamespaceURI);
if (length != null) {
signatureLength = length.InnerText;
}
}
for (int i = 0; i < value.ChildNodes.Count; i++) {
XmlNode n = value.ChildNodes [i];
if (n.NodeType == XmlNodeType.Element &&
n.LocalName == XmlSignature.ElementNames.Reference &&
n.NamespaceURI == XmlSignature.NamespaceURI) {
Reference r = new Reference ();
r.LoadXml ((XmlElement) n);
AddReference (r);
}
}
element = value;
}