1 // Licensed to the .NET Foundation under one or more agreements.
2 // The .NET Foundation licenses this file to you under the MIT license.
3 // See the LICENSE file in the project root for more information.
6 using System.Collections.Generic;
9 using System.Threading.Tasks;
13 namespace System.Security.Cryptography.Xml.Tests
15 // Based on implementation of MSDN samples:
16 // Signing: https://msdn.microsoft.com/en-us/library/ms229745(v=vs.110).aspx
17 // Verifying: https://msdn.microsoft.com/en-us/library/ms229745(v=vs.110).aspx
18 public class SigningAndVerifyingWithCustomSignatureMethod
20 const string ExampleXml = @"<?xml version=""1.0""?>
22 <test>some text node</test>
25 private static bool SupportsSha2Algorithms =>
26 !PlatformDetection.IsFullFramework ||
27 CryptoConfig.CreateFromName("http://www.w3.org/2001/04/xmldsig-more#rsa-sha384") as SignatureDescription != null;
29 private static void SignXml(XmlDocument doc, RSA key, string signatureMethod, string digestMethod)
31 var signedXml = new SignedXml(doc)
36 signedXml.SignedInfo.SignatureMethod = signatureMethod;
38 var reference = new Reference();
41 reference.AddTransform(new XmlDsigEnvelopedSignatureTransform());
42 reference.DigestMethod = digestMethod;
44 signedXml.AddReference(reference);
46 signedXml.ComputeSignature();
47 XmlElement xmlDigitalSignature = signedXml.GetXml();
48 doc.DocumentElement.AppendChild(doc.ImportNode(xmlDigitalSignature, true));
51 private static bool VerifyXml(string signedXmlText, RSA key)
53 XmlDocument xmlDoc = new XmlDocument();
54 xmlDoc.PreserveWhitespace = true;
55 xmlDoc.LoadXml(signedXmlText);
57 SignedXml signedXml = new SignedXml(xmlDoc);
58 var signatureNode = (XmlElement)xmlDoc.GetElementsByTagName("Signature")[0];
59 signedXml.LoadXml(signatureNode);
60 return signedXml.CheckSignature(key);
63 // https://github.com/dotnet/corefx/issues/19269
64 [ConditionalTheory(nameof(SupportsSha2Algorithms))]
65 [InlineData("http://www.w3.org/2001/04/xmldsig-more#rsa-sha256", "http://www.w3.org/2001/04/xmlenc#sha256")]
66 [InlineData("http://www.w3.org/2001/04/xmldsig-more#rsa-sha384", "http://www.w3.org/2001/04/xmldsig-more#sha384")]
67 [InlineData("http://www.w3.org/2001/04/xmldsig-more#rsa-sha512", "http://www.w3.org/2001/04/xmlenc#sha512")]
68 [InlineData("http://www.w3.org/2001/04/xmldsig-more#rsa-sha256", "http://www.w3.org/2001/04/xmlenc#sha512")]
69 public void SignedXmlHasVerifiableSignature(string signatureMethod, string digestMethod)
71 using (RSA key = RSA.Create())
73 var xmlDoc = new XmlDocument();
74 xmlDoc.PreserveWhitespace = true;
75 xmlDoc.LoadXml(ExampleXml);
76 SignXml(xmlDoc, key, signatureMethod, digestMethod);
77 Assert.True(VerifyXml(xmlDoc.OuterXml, key));