public void GetXmlWithSetProperty() { XmlDocument doc = new XmlDocument(); doc.LoadXml(xmlForGetXml); SignedInfo sig = new SignedInfo(); sig.LoadXml((XmlElement)doc.SelectSingleNode("//*[local-name()='SignedInfo']")); sig.CanonicalizationMethod = "urn:foo"; XmlElement el = sig.GetXml(); Assert.True(doc != el.OwnerDocument, "#GetXmlWithSetProperty.document"); }
[Test] // never fails public void EmptyReferenceWithoutSetProperty() { XmlDocument doc = new XmlDocument(); doc.LoadXml(xmlForGetXml); XmlNode n = doc.SelectSingleNode("//*[local-name()='Reference']"); n.ParentNode.RemoveChild(n); SignedInfo sig = new SignedInfo(); sig.LoadXml((XmlElement)doc.SelectSingleNode("//*[local-name()='SignedInfo']")); XmlElement el = sig.GetXml(); }
public void GetXmlWithoutSetProperty() { string result = @"<dsig:SignedInfo xmlns:dsig=""http://www.w3.org/2000/09/xmldsig#""><dsig:CanonicalizationMethod Algorithm=""http://www.w3.org/TR/2001/REC-xml-c14n-withcomments-20010315"" /><dsig:SignatureMethod Algorithm=""http://www.w3.org/2000/09/xmldsig#rsa-sha1"" /><dsig:Reference URI=""""><dsig:Transforms><dsig:Transform Algorithm=""http://www.w3.org/2000/09/xmldsig#enveloped-signature"" /></dsig:Transforms><dsig:DigestMethod Algorithm=""http://www.w3.org/2000/09/xmldsig#sha1"" /><dsig:DigestValue>nDF2V/bzRd0VE3EwShWtsBzTEDc=</dsig:DigestValue></dsig:Reference></dsig:SignedInfo>"; XmlDocument doc = new XmlDocument(); doc.LoadXml(xmlForGetXml); SignedInfo sig = new SignedInfo(); sig.LoadXml((XmlElement)doc.SelectSingleNode("//*[local-name()='SignedInfo']")); XmlElement el = sig.GetXml(); Assert.Equal(doc, el.OwnerDocument); Assert.Equal(result, el.OuterXml); }
public void CompareSignedInfo() { TestUtilities.WriteHeader($"{this}.CompareSignedInfo", true); var context = new CompareContext($"{this}.CompareSignedInfo"); var signedInfo1 = new SignedInfo { SignatureMethod = Guid.NewGuid().ToString() }; var signedInfo2 = new SignedInfo { SignatureMethod = Guid.NewGuid().ToString() }; IdentityComparer.AreEqual(signedInfo1, signedInfo2, context); Assert.True(context.Diffs.Count(s => s == "SignatureMethod:") == 1); }
private byte[] GetC14NDigest(HashAlgorithm hash, string prefix) { var xmlDocument = new XmlDocument { PreserveWhitespace = true }; var xml = SignedInfo.GetXml(); xmlDocument.AppendChild(xmlDocument.ImportNode(xml, true)); var canonicalizationMethodObject = SignedInfo.CanonicalizationMethodObject; SetPrefix(prefix, xmlDocument.DocumentElement); canonicalizationMethodObject.LoadInput(xmlDocument); return(canonicalizationMethodObject.GetDigestedOutput(hash)); }
public void EmptyReferenceWithSetProperty() { XmlDocument doc = new XmlDocument(); doc.LoadXml(xmlForGetXml); XmlNode n = doc.SelectSingleNode("//*[local-name()='Reference']"); n.ParentNode.RemoveChild(n); SignedInfo sig = new SignedInfo(); sig.LoadXml((XmlElement)doc.SelectSingleNode("//*[local-name()='SignedInfo']")); sig.CanonicalizationMethod = "urn:foo"; Assert.Throws <CryptographicException>(() => sig.GetXml()); }
public static byte[] GenerateSignatureBytes(SignedInfo signedInfo, SecurityKey key) { using (var stream = new MemoryStream()) { var serailizer = new DSigSerializer(); var writer = XmlDictionaryWriter.CreateTextWriter(Stream.Null); var includeComments = signedInfo.CanonicalizationMethod == SecurityAlgorithms.ExclusiveC14nWithComments; writer.StartCanonicalization(stream, includeComments, null); serailizer.WriteSignedInfo(writer, signedInfo); writer.EndCanonicalization(); writer.Flush(); stream.Position = 0; var provider = key.CryptoProviderFactory.CreateForSigning(key, signedInfo.SignatureMethod); return(provider.Sign(stream.ToArray())); } }
private void GetC14NDigest(HashAlgorithm hash, string prefix) { var document = new XmlDocument(); document.PreserveWhitespace = true; var e = SignedInfo.GetXml(); document.AppendChild(document.ImportNode(e, true)); var canonicalizationMethodObject = SignedInfo.CanonicalizationMethodObject; SetPrefix(prefix, document.DocumentElement); canonicalizationMethodObject.LoadInput(document); canonicalizationMethodObject.GetDigestedOutput(hash); }
protected override ISignatureValueSecurityElement CreateSupportingSignature(SecurityToken token, SecurityKeyIdentifier identifier, ISecurityElement elementToSign) { string signatureAlgorithm; XmlDictionaryString signatureAlgorithmDictionaryString; SecurityKey signatureKey; AlgorithmSuite.GetSignatureAlgorithmAndKey(token, out signatureAlgorithm, out signatureKey, out signatureAlgorithmDictionaryString); SignedXml signedXml = new SignedXml(); SignedInfo signedInfo = signedXml.SignedInfo; signedInfo.CanonicalizationMethod = AlgorithmSuite.DefaultCanonicalizationAlgorithm; signedInfo.SignatureMethod = signatureAlgorithm; if (elementToSign.Id == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.ElementToSignMustHaveId)); } MemoryStream stream = new MemoryStream(); XmlDictionaryWriter utf8Writer = TakeUtf8Writer(); utf8Writer.StartCanonicalization(stream, false, null); elementToSign.WriteTo(utf8Writer, ServiceModelDictionaryManager.Instance); utf8Writer.EndCanonicalization(); stream.Position = 0; AddReference("#" + elementToSign.Id, stream); AsymmetricAlgorithm asymmetricAlgorithm = null; KeyedHashAlgorithm keyedHashAlgorithm = null; GetSigningAlgorithm(signatureKey, signatureAlgorithm, out keyedHashAlgorithm, out asymmetricAlgorithm); if (keyedHashAlgorithm != null) { signedXml.ComputeSignature(keyedHashAlgorithm); } else { signedXml.SigningKey = asymmetricAlgorithm; signedXml.ComputeSignature(); } SetKeyInfo(signedXml, identifier); return(new SignatureValue(signedXml.Signature)); }
private byte[] GetC14NDigest(HashAlgorithm hash, string prefix) { XmlDocument doc = new XmlDocument { PreserveWhitespace = false }; XmlElement e = SignedInfo.GetXml(); doc.AppendChild(doc.ImportNode(e, true)); List <XmlAttribute> namespaces = Utils.GetPropagatedAttributes(_xmlElement); Utils.AddNamespaces(doc.DocumentElement, namespaces); Transform canonicalizationMethodObject = SignedInfo.CanonicalizationMethodObject; SetPrefix(prefix, doc.DocumentElement); canonicalizationMethodObject.LoadInput(doc); return(canonicalizationMethodObject.GetDigestedOutput(hash)); }
public void SignatureLength() { SignedInfo si = new SignedInfo(); si.SignatureLength = "128"; Assert.Equal("128", si.SignatureLength); Assert.Null(si.SignatureMethod); si.SignatureMethod = "http://www.w3.org/2000/09/xmldsig#rsa-sha1"; si.SignatureLength = "0"; Assert.Equal("0", si.SignatureLength); Assert.Equal("http://www.w3.org/2000/09/xmldsig#rsa-sha1", si.SignatureMethod); si.SignatureLength = "http://www.w3.org/2000/09/xmldsig#rsa-sha1"; si.SignatureMethod = "0"; Assert.Equal("http://www.w3.org/2000/09/xmldsig#rsa-sha1", si.SignatureLength); Assert.Equal("0", si.SignatureMethod); }
public void SignatureLength() { // we can set the length before the algorithm SignedInfo si = new SignedInfo(); si.SignatureLength = "128"; Assert.Equal("128", si.SignatureLength); Assert.Null(si.SignatureMethod); // zero si.SignatureMethod = "http://www.w3.org/2000/09/xmldsig#rsa-sha1"; si.SignatureLength = "0"; Assert.Equal("0", si.SignatureLength); Assert.Equal("http://www.w3.org/2000/09/xmldsig#rsa-sha1", si.SignatureMethod); // mixup length and method si.SignatureLength = "http://www.w3.org/2000/09/xmldsig#rsa-sha1"; si.SignatureMethod = "0"; Assert.Equal("http://www.w3.org/2000/09/xmldsig#rsa-sha1", si.SignatureLength); Assert.Equal("0", si.SignatureMethod); }
private byte[] GetC14NDigest(HashAlgorithm hash, string prefix) { //string securityUrl = (this.m_containingDocument == null) ? null : this.m_containingDocument.BaseURI; //XmlResolver xmlResolver = new XmlSecureResolver(new XmlUrlResolver(), securityUrl); var document = new XmlDocument(); document.PreserveWhitespace = true; var e = SignedInfo.GetXml(); document.AppendChild(document.ImportNode(e, true)); //CanonicalXmlNodeList namespaces = (this.m_context == null) ? null : Utils.GetPropagatedAttributes(this.m_context); //Utils.AddNamespaces(document.DocumentElement, namespaces); var canonicalizationMethodObject = SignedInfo.CanonicalizationMethodObject; //canonicalizationMethodObject.Resolver = xmlResolver; //canonicalizationMethodObject.BaseURI = securityUrl; SetPrefix(prefix, document.DocumentElement); //establecemos el prefijo antes de se que calcule el hash (o de lo contrario la firma no será válida) canonicalizationMethodObject.LoadInput(document); return(canonicalizationMethodObject.GetDigestedOutput(hash)); }
public SignedInfoTest() { info = new SignedInfo(); }
public override void MarkElements(ReceiveSecurityHeaderElementManager elementManager, bool messageSecurityMode) { bool primarySignatureFound = false; for (int position = 0; position < elementManager.Count; position++) { ReceiveSecurityHeaderEntry entry; elementManager.GetElementEntry(position, out entry); if (entry.elementCategory == ReceiveSecurityHeaderElementCategory.Signature) { if (!messageSecurityMode) { elementManager.SetBindingMode(position, ReceiveSecurityHeaderBindingModes.Endorsing); continue; } SignedXml signedXml = (SignedXml)entry.element; SignedInfo signedInfo = signedXml.Signature.SignedInfo; bool targetsSignature = false; if (signedInfo.References.Count == 1) { Reference signedXmlReference = (Reference)signedInfo.References[0]; string uri = signedXmlReference.Uri; string id; if (uri != null && uri.Length > 1 && uri[0] == '#') { id = uri.Substring(1); } else { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new MessageSecurityException(SR.Format(SR.UnableToResolveReferenceUriForSignature, uri))); } for (int j = 0; j < elementManager.Count; j++) { ReceiveSecurityHeaderEntry inner; elementManager.GetElementEntry(j, out inner); if (j != position && inner.elementCategory == ReceiveSecurityHeaderElementCategory.Signature && inner.id == id) { targetsSignature = true; break; } } } if (targetsSignature) { elementManager.SetBindingMode(position, ReceiveSecurityHeaderBindingModes.Endorsing); continue; } else { if (primarySignatureFound) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(SR.Format(SR.AtMostOnePrimarySignatureInReceiveSecurityHeader))); } primarySignatureFound = true; elementManager.SetBindingMode(position, ReceiveSecurityHeaderBindingModes.Primary); continue; } } } }
protected override void ExecuteMessageProtectionPass(bool hasAtLeastOneSupportingTokenExpectedToBeSigned) { bool flag8; bool flag9; SignatureTargetIdManager idManager = base.StandardsManager.IdManager; MessagePartSpecification specification = base.RequiredEncryptionParts ?? MessagePartSpecification.NoParts; MessagePartSpecification signatureParts = base.RequiredSignatureParts ?? MessagePartSpecification.NoParts; bool checkForTokensAtHeaders = hasAtLeastOneSupportingTokenExpectedToBeSigned; bool doSoapAttributeChecks = !signatureParts.IsBodyIncluded; bool encryptBeforeSignMode = base.EncryptBeforeSignMode; SignedInfo signedInfo = (this.pendingSignature != null) ? this.pendingSignature.Signature.SignedInfo : null; SignatureConfirmations sentSignatureConfirmations = base.GetSentSignatureConfirmations(); if (((sentSignatureConfirmations != null) && (sentSignatureConfirmations.Count > 0)) && sentSignatureConfirmations.IsMarkedForEncryption) { base.VerifySignatureEncryption(); } MessageHeaders headers = base.SecurityVerifiedMessage.Headers; XmlDictionaryReader readerAtFirstHeader = base.SecurityVerifiedMessage.GetReaderAtFirstHeader(); bool atLeastOneHeaderOrBodyEncrypted = false; for (int i = 0; i < headers.Count; i++) { if (readerAtFirstHeader.NodeType != XmlNodeType.Element) { readerAtFirstHeader.MoveToContent(); } if (i == base.HeaderIndex) { readerAtFirstHeader.Skip(); } else { bool flag6; bool flag5 = false; string str = idManager.ExtractId(readerAtFirstHeader); if (str != null) { flag5 = this.TryDeleteReferenceListEntry(str); } if (!flag5 && readerAtFirstHeader.IsStartElement("EncryptedHeader", "http://docs.oasis-open.org/wss/oasis-wss-wssecurity-secext-1.1.xsd")) { XmlDictionaryReader readerAtHeader = headers.GetReaderAtHeader(i); readerAtHeader.ReadStartElement("EncryptedHeader", "http://docs.oasis-open.org/wss/oasis-wss-wssecurity-secext-1.1.xsd"); if (readerAtHeader.IsStartElement(EncryptedData.ElementName, System.ServiceModel.XD.XmlEncryptionDictionary.Namespace)) { string attribute = readerAtHeader.GetAttribute(System.ServiceModel.XD.XmlEncryptionDictionary.Id, null); if ((attribute != null) && this.TryDeleteReferenceListEntry(attribute)) { flag5 = true; } } } base.ElementManager.VerifyUniquenessAndSetHeaderId(str, i); MessageHeaderInfo info = headers[i]; if (!flag5 && specification.IsHeaderIncluded(info.Name, info.Namespace)) { base.SecurityVerifiedMessage.OnUnencryptedPart(info.Name, info.Namespace); } if ((!flag5 || encryptBeforeSignMode) && (str != null)) { flag6 = this.EnsureDigestValidityIfIdMatches(signedInfo, str, readerAtFirstHeader, doSoapAttributeChecks, signatureParts, info, checkForTokensAtHeaders); } else { flag6 = false; } if (flag5) { XmlDictionaryReader reader = flag6 ? headers.GetReaderAtHeader(i) : readerAtFirstHeader; DecryptedHeader header = this.DecryptHeader(reader, this.pendingDecryptionToken); info = header; str = header.Id; base.ElementManager.VerifyUniquenessAndSetDecryptedHeaderId(str, i); headers.ReplaceAt(i, header); if (!object.ReferenceEquals(reader, readerAtFirstHeader)) { reader.Close(); } if (!encryptBeforeSignMode && (str != null)) { XmlDictionaryReader headerReader = header.GetHeaderReader(); flag6 = this.EnsureDigestValidityIfIdMatches(signedInfo, str, headerReader, doSoapAttributeChecks, signatureParts, info, checkForTokensAtHeaders); headerReader.Close(); } } if (!flag6 && signatureParts.IsHeaderIncluded(info.Name, info.Namespace)) { base.SecurityVerifiedMessage.OnUnsignedPart(info.Name, info.Namespace); } if (flag6 && flag5) { base.VerifySignatureEncryption(); } if (flag5 && !flag6) { throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(System.ServiceModel.SR.GetString("EncryptedHeaderNotSigned", new object[] { info.Name, info.Namespace }))); } if (!flag6 && !flag5) { readerAtFirstHeader.Skip(); } atLeastOneHeaderOrBodyEncrypted |= flag5; } } readerAtFirstHeader.ReadEndElement(); if (readerAtFirstHeader.NodeType != XmlNodeType.Element) { readerAtFirstHeader.MoveToContent(); } string id = idManager.ExtractId(readerAtFirstHeader); base.ElementManager.VerifyUniquenessAndSetBodyId(id); base.SecurityVerifiedMessage.SetBodyPrefixAndAttributes(readerAtFirstHeader); bool flag7 = specification.IsBodyIncluded || this.HasPendingDecryptionItem(); if ((!flag7 || encryptBeforeSignMode) && (id != null)) { flag8 = this.EnsureDigestValidityIfIdMatches(signedInfo, id, readerAtFirstHeader, false, null, null, false); } else { flag8 = false; } if (flag7) { XmlDictionaryReader reader5 = flag8 ? base.SecurityVerifiedMessage.CreateFullBodyReader() : readerAtFirstHeader; reader5.ReadStartElement(); string str4 = idManager.ExtractId(reader5); base.ElementManager.VerifyUniquenessAndSetBodyContentId(str4); flag9 = (str4 != null) && this.TryDeleteReferenceListEntry(str4); if (flag9) { this.DecryptBody(reader5, this.pendingDecryptionToken); } if (!object.ReferenceEquals(reader5, readerAtFirstHeader)) { reader5.Close(); } if ((!encryptBeforeSignMode && (signedInfo != null)) && signedInfo.HasUnverifiedReference(id)) { reader5 = base.SecurityVerifiedMessage.CreateFullBodyReader(); flag8 = this.EnsureDigestValidityIfIdMatches(signedInfo, id, reader5, false, null, null, false); reader5.Close(); } } else { flag9 = false; } if (flag8 && flag9) { base.VerifySignatureEncryption(); } readerAtFirstHeader.Close(); if (this.pendingSignature != null) { this.pendingSignature.CompleteSignatureVerification(); this.pendingSignature = null; } this.pendingDecryptionToken = null; atLeastOneHeaderOrBodyEncrypted |= flag9; if (!flag8 && signatureParts.IsBodyIncluded) { base.SecurityVerifiedMessage.OnUnsignedPart(System.ServiceModel.XD.MessageDictionary.Body.Value, base.Version.Envelope.Namespace); } if (!flag9 && specification.IsBodyIncluded) { base.SecurityVerifiedMessage.OnUnencryptedPart(System.ServiceModel.XD.MessageDictionary.Body.Value, base.Version.Envelope.Namespace); } base.SecurityVerifiedMessage.OnMessageProtectionPassComplete(atLeastOneHeaderOrBodyEncrypted); }
/** * Creates an <code>XMLSignature</code> and initializes it with the * specified parameters. * * @param si the signed info * @param ki the key info (may be <code>null</code>) * @param objects a list of {@link XMLObject}s (may be empty or * <code>null</code>) * @param id the Id (may be <code>null</code>) * @param signatureValueId the SignatureValue Id (may be <code>null</code>) * @return an <code>XMLSignature</code> * @throws NullPointerException if <code>si</code> is <code>null</code> * @throws ClassCastException if any of the <code>objects</code> are not of * type <code>XMLObject</code> */ public abstract XMLSignature newXMLSignature(SignedInfo si, javax.xml.crypto.dsig.keyinfo.KeyInfo ki, java.util.List<Object> objects, String id, String signatureValueId);
protected void SetUp() { info = new SignedInfo(); }
/** * Creates an <code>XMLSignature</code> and initializes it with the * specified parameters. * * @param si the signed info * @param ki the key info (may be <code>null</code>) * @param objects a list of {@link XMLObject}s (may be empty or * <code>null</code>) * @param id the Id (may be <code>null</code>) * @param signatureValueId the SignatureValue Id (may be <code>null</code>) * @return an <code>XMLSignature</code> * @throws NullPointerException if <code>si</code> is <code>null</code> * @throws ClassCastException if any of the <code>objects</code> are not of * type <code>XMLObject</code> */ public abstract XMLSignature newXMLSignature(SignedInfo si, javax.xml.crypto.dsig.keyinfo.KeyInfo ki, java.util.List <Object> objects, String id, String signatureValueId);
/** * Creates an <code>XMLSignature</code> and initializes it with the contents * of the specified <code>SignedInfo</code> and <code>KeyInfo</code> * objects. * * @param si the signed info * @param ki the key info (may be <code>null</code>) * @return an <code>XMLSignature</code> * @throws NullPointerException if <code>si</code> is <code>null</code> */ public abstract XMLSignature newXMLSignature(SignedInfo si, javax.xml.crypto.dsig.keyinfo.KeyInfo ki);
private Reference GetReferenceByUri(SignedInfo signedInfo, string uri) { return(signedInfo.References.Cast <Reference>().FirstOrDefault(reference => reference.Uri == uri)); }
static void DumpSignedInfo (SignedInfo s) { Console.WriteLine ("*** SignedInfo ***"); Console.WriteLine ("CanonicalizationMethod: " + s.CanonicalizationMethod); Console.WriteLine ("Id: " + s.Id); Console.WriteLine ("References: " + s.References); Console.WriteLine ("SignatureLength: " + s.SignatureLength); Console.WriteLine ("SignatureMethod: " + s.SignatureMethod); }