예제 #1
2
파일: XML4PLOT.cs 프로젝트: usnistgov/DT4SM
        public override object EncodeCMS(X509Certificate2 certificate, string xmlFilePath)
        {
            XmlDocument Document = new XmlDocument();
            Document.PreserveWhitespace = true;
            XmlTextReader XmlFile = new XmlTextReader(xmlFilePath);
            Document.Load(XmlFile);
            XmlFile.Close();
            XmlNodeList SignaturesList = Document.GetElementsByTagName("Signature");
            // Remove existing signatures, this is not a countersigning.
            for (int i = 0; i < SignaturesList.Count; i++)
            {
                SignaturesList[i].ParentNode.RemoveChild(SignaturesList[i]);
                i--;
            }

            SignedXml SignedXml = new SignedXml(Document);
            SignedXml.SigningKey = certificate.PrivateKey;
            Reference Reference = new Reference();
            Reference.Uri = "";
            XmlDsigEnvelopedSignatureTransform EnvelopedSignatureTransform = new XmlDsigEnvelopedSignatureTransform();
            Reference.AddTransform(EnvelopedSignatureTransform);
            SignedXml.AddReference(Reference);
            KeyInfo Key = new KeyInfo();
            Key.AddClause(new KeyInfoX509Data(certificate));
            SignedXml.KeyInfo = Key;
            SignedXml.ComputeSignature();
            // Get the XML representation of the signature and save
            // it to an XmlElement object.
            XmlElement XmlDigitalSignature = SignedXml.GetXml();

            return XmlDigitalSignature;
        }
예제 #2
0
        private void Encrypt()
        {
            _encryptedStream.Position = 0;
            var algorithm = _credentials.Enc;

            var document = new XmlDocument();

            document.Load(_encryptedStream);

            var symmetric = Crypto.CreateSymmetricAlgorithm(algorithm);
            var xml       = new EncryptedXml();

            xml.Mode = symmetric.Mode;
            var cipherText = xml.EncryptData(document.DocumentElement, symmetric, false);

            var keyInfo = new KeyInfo();
            var data    = new EncryptedData
            {
                Type             = EncryptedXml.XmlEncElementUrl,
                EncryptionMethod = new EncryptionMethod(algorithm),
                CipherData       = new CipherData {
                    CipherValue = cipherText
                }
            };

            if (_credentials.Key is RsaSecurityKey rsa)
            {
                keyInfo.AddClause(CreateEncryptedKeyClause(symmetric.Key, rsa.Rsa, document));
            }
            else if (_credentials.Key is X509SecurityKey x509)
            {
                keyInfo.AddClause(CreateEncryptedKeyClause(symmetric.Key, x509.Certificate, document));
            }
            else if (!string.IsNullOrEmpty(_credentials.Key.KeyId))
            {
                keyInfo.AddClause(new KeyInfoName(_credentials.Key.KeyId));
            }

            if (keyInfo.Cast <KeyInfoClause>().Any())
            {
                data.KeyInfo = keyInfo;
            }

            var element = data.GetXml();

            //element = AddDigestMethodToEncryptionMethod(element, "http://www.w3.org/2000/09/xmldsig#sha1");

            WriteNode(element.CreateNavigator(), true);

            Crypto.ReleaseSymmetricAlgorithm(symmetric);
        }
        public static string Sign(string xml, X509Certificate2 certificate)
        {
            if (xml == null) throw new ArgumentNullException("xml");
            if (certificate == null) throw new ArgumentNullException("certificate");
            if (!certificate.HasPrivateKey) throw new ArgumentException("certificate", "Certificate should have a private key");

            XmlDocument doc = new XmlDocument();

            doc.PreserveWhitespace = true;
            doc.LoadXml(xml);

            SignedXml signedXml = new SignedXml(doc);
            signedXml.SigningKey = certificate.PrivateKey;

            // Attach certificate KeyInfo
            KeyInfoX509Data keyInfoData = new KeyInfoX509Data(certificate);
            KeyInfo keyInfo = new KeyInfo();
            keyInfo.AddClause(keyInfoData);
            signedXml.KeyInfo = keyInfo;

            // Attach transforms
            var reference = new Reference("");
            reference.AddTransform(new XmlDsigEnvelopedSignatureTransform(includeComments: false));
            reference.AddTransform(new XmlDsigExcC14NTransform(includeComments: false));
            signedXml.AddReference(reference);

            // Compute signature
            signedXml.ComputeSignature();
            var signatureElement = signedXml.GetXml();

            // Add signature to bundle
            doc.DocumentElement.AppendChild(doc.ImportNode(signatureElement, true));

            return doc.OuterXml;
        }
예제 #4
0
        /// <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);
        }
        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 };

            // Установка ссылки на узел
            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;
        }
        /// <summary>
        /// Creates the necessary key descriptors for the metadata based on the certificate in the IDPConfig class.
        /// </summary>
        /// <returns></returns>
        private static KeyDescriptor[] CreateKeyDescriptors()
        {
            List<KeyDescriptor> keys = new List<KeyDescriptor>();

            // Pack the certificate.
            KeyInfo keyinfo = new KeyInfo();
            KeyInfoX509Data keyClause = new KeyInfoX509Data(IDPConfig.IDPCertificate, X509IncludeOption.EndCertOnly);
            keyinfo.AddClause(keyClause);

            { // Create signing key element.
                KeyDescriptor key = new KeyDescriptor();
                keys.Add(key);
                key.use = KeyTypes.signing;
                key.useSpecified = true;
                key.KeyInfo = Serialization.DeserializeFromXmlString<dk.nita.saml20.Schema.XmlDSig.KeyInfo>(keyinfo.GetXml().OuterXml);
            }

            { // Create encryption key element
                KeyDescriptor key = new KeyDescriptor();
                keys.Add(key);
                key.use = KeyTypes.encryption;
                key.useSpecified = true;
                key.KeyInfo = Serialization.DeserializeFromXmlString<dk.nita.saml20.Schema.XmlDSig.KeyInfo>(keyinfo.GetXml().OuterXml);
            }

            return keys.ToArray();
        }
예제 #7
0
        private KeyInfoClause CreateEncryptedKeyClause(byte[] key, X509Certificate2 certificate, XmlDocument document)
        {
            var keyInfo = new KeyInfo();

            keyInfo.AddClause(CreateKeyInfoClause(certificate, document, out _));
            return(CreateEncryptedKeyClause(key, keyInfo));
        }
예제 #8
0
        private KeyInfoClause CreateEncryptedKeyClause(byte[] key, RSA rsa, XmlDocument document)
        {
            var keyInfo = new KeyInfo();

            keyInfo.AddClause(CreateKeyInfoClause(rsa));
            return(CreateEncryptedKeyClause(key, keyInfo));
        }
예제 #9
0
        static SignedXmlHelper()
        {
            var keyInfo = new KeyInfo();
            keyInfo.AddClause(new KeyInfoX509Data(TestCert));

            KeyInfoXml = keyInfo.GetXml().OuterXml;
        }
예제 #10
0
파일: Program.cs 프로젝트: zhshen/HuaweiAMS
        private static XmlDocument SignXml()
        {
            XmlDocument xmlDoc = new XmlDocument();

            xmlDoc.PreserveWhitespace = true;
            xmlDoc.Load(".\\certificates\\samlRequestTemplate.xml");
            X509Certificate2 certificate = CertificateHelper.GetCertificate(".\\certificates\\HuaweiCA.p12", "Pr0d1234");

            //AsymmetricAlgorithm key = certificate.PrivateKey;
            AsymmetricAlgorithm key = certificate.PrivateKey;

            XmlNamespaceManager ns = new XmlNamespaceManager(xmlDoc.NameTable);
            ns.AddNamespace("saml", "urn:oasis:names:tc:SAML:2.0:assertion");
            ns.AddNamespace("samlp", "urn:oasis:names:tc:SAML:2.0:protocol");

            XmlElement issuerNode = (XmlElement)xmlDoc.DocumentElement.SelectSingleNode("saml:Issuer", ns);

            SignedXml signedXml = new SignedXml(xmlDoc.DocumentElement);
            signedXml.SigningKey = key;
            signedXml.SignedInfo.CanonicalizationMethod = SignedXml.XmlDsigExcC14NTransformUrl;

            KeyInfo keyInfo = new KeyInfo();

            //XmlDocument keyDoc = new XmlDocument();

            //keyDoc.LoadXml(certificate.PublicKey.Key.ToXmlString(false));
            //keyInfo.LoadXml(keyDoc.DocumentElement);
            keyInfo.AddClause(new KeyInfoX509Data(certificate));
            signedXml.KeyInfo = keyInfo;

            string refId = xmlDoc.DocumentElement.GetAttribute("ID");

            Reference reference = new Reference();
            reference.Uri = "#" + refId;

            XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform();

            reference.AddTransform(env);

            XmlDsigExcC14NTransform env2 = new XmlDsigExcC14NTransform();
            env2.InclusiveNamespacesPrefixList = "#default code ds kind rw saml samlp typens";
            reference.AddTransform(env2);

            signedXml.AddReference(reference);

            signedXml.ComputeSignature();
            XmlElement xmlDigitalSignature = signedXml.GetXml();
            xmlDoc.DocumentElement.InsertAfter(xmlDoc.ImportNode(xmlDigitalSignature, true), issuerNode);

            //xmlDoc.NameTable.Add("samlp");
            //XmlElement nameIDPolicyElem = xmlDoc.CreateElement("samlp", "NameIDPolicy", "urn:oasis:names:tc:SAML:2.0:protocol");
            //nameIDPolicyElem.SetAttribute("AllowCreate", "False");

            //xmlDoc.DocumentElement.AppendChild(nameIDPolicyElem);

            xmlDoc.Save("samleRequestCSharp.xml");

            return xmlDoc;
        }
예제 #11
0
		/// <summary>
		///		Obtiene la información de la firma asociada al certificado digital
		/// </summary>
		private KeyInfo GetKeyInfoFromCertificate(X509Certificate2 objCertificate)
		{	KeyInfo objKeyInfo = new KeyInfo();

				// Añade la cláusula con el certificado
					objKeyInfo.AddClause(new KeyInfoX509Data(objCertificate));
				// Devuelve la información
					return objKeyInfo;
		}
예제 #12
0
파일: xmlEnvio.cs 프로젝트: rnmoge/nfce-Sat
        public XmlDocument assinaturaXmlEnviar(XmlDocument _xml)
        {
            XmlDocument xmlDocAss = _xml;

            try
            {


                if (cert == null)
                    throw new Exception("Nao foi encontrado o certificado: " + config.configNFCe.NomeCertificadoDigital);

                Reference reference = new Reference();
                SignedXml docXML = new SignedXml(xmlDocAss);

                docXML.SigningKey = cert.PrivateKey;
                XmlAttributeCollection uri = xmlDocAss.GetElementsByTagName("infNFe").Item(0).Attributes;
                foreach (XmlAttribute atributo in uri)
                {
                    if (atributo.Name == "Id")
                        reference.Uri = "#" + atributo.InnerText;
                }

                XmlDsigEnvelopedSignatureTransform envelopedSigntature = new XmlDsigEnvelopedSignatureTransform();
                reference.AddTransform(envelopedSigntature);

                XmlDsigC14NTransform c14Transform = new XmlDsigC14NTransform();
                reference.AddTransform(c14Transform);
                docXML.AddReference(reference);

                KeyInfo keyInfo = new KeyInfo();
                keyInfo.AddClause(new KeyInfoX509Data(cert));

                docXML.KeyInfo = keyInfo;
                docXML.ComputeSignature();

                XmlElement xmlDigitalSignature = docXML.GetXml();

                foreach (var _nfe in xmlDocAss.GetElementsByTagName("NFe").Cast<XmlElement>())
                    _nfe.AppendChild(xmlDocAss.ImportNode(xmlDigitalSignature, true));


                xmlDocAss.PreserveWhitespace = true;
                return xmlDocAss;
            }

            catch (Exception e)
            {
                Utils.Logger.getInstance.error(e);
                return null;
                throw new Exception(e.ToString());
            }


        }
예제 #13
0
        private void CreateMetadataDocument(HttpContext context, bool sign)
        {
            SAML20FederationConfig configuration = ConfigurationReader.GetConfig<SAML20FederationConfig>();

            KeyInfo keyinfo = new KeyInfo();
            KeyInfoX509Data keyClause = new KeyInfoX509Data(ConfigurationReader.GetConfig<FederationConfig>().SigningCertificate.GetCertificate(), X509IncludeOption.EndCertOnly);
            keyinfo.AddClause(keyClause);

            Saml20MetadataDocument doc = new Saml20MetadataDocument(configuration, keyinfo, sign);

            context.Response.Write(doc.ToXml( context.Response.ContentEncoding ));
        }
예제 #14
0
        private XmlElement CreateEncryptedSymmetricKeyInfo(byte[] key, EncryptingCredentials credentials, XmlDocument document)
        {
            var digestMethod = null as string;
            var clause       = null as Legacy.KeyInfoClause;

            if (credentials.Key is X509SecurityKey x509)
            {
                digestMethod = "http://www.w3.org/2000/09/xmldsig#sha1";
                var securityTokenReference = document.CreateElement(WsSecurityConstants.WsSecurity10.Prefix, "SecurityTokenReference", WsSecurityConstants.WsSecurity10.Namespace);
                var keyIdentifier          = document.CreateElement(WsSecurityConstants.WsSecurity10.Prefix, "KeyIdentifier", WsSecurityConstants.WsSecurity10.Namespace);
                keyIdentifier.SetAttribute("ValueType", "http://docs.oasis-open.org/wss/oasis-wss-soap-message-security-1.1#ThumbprintSHA1");
                keyIdentifier.InnerText = x509.X5t;
                securityTokenReference.AppendChild(keyIdentifier);

                using (var rsa = x509.Certificate.GetRSAPublicKey())
                    clause = EncryptKey(key, rsa, credentials.Alg, new Legacy.KeyInfoNode(securityTokenReference));
            }
            else if (credentials.Key is RsaSecurityKey rsa)
            {
                clause = EncryptKey(key, rsa.Rsa, credentials.Alg, CreateKeyInfoClause(rsa));
            }
            else
            {
                throw new NotSupportedException($"Encryption key type '{credentials?.Key.GetType()?.Name}' not supported.");
            }

            var keyInfo = new Legacy.KeyInfo();

            keyInfo.AddClause(clause);
            var element = keyInfo.GetXml();

            if (digestMethod != null)
            {
                var encryptionMethods = element
                                        .SelectNodes("//*")
                                        .OfType <XmlElement>()
                                        .Where(e => e.LocalName == "EncryptionMethod")
                                        .Where(e =>
                {
                    var algorithm = e.GetAttribute("Algorithm");
                    return(algorithm == Legacy.EncryptedXml.XmlEncRSAOAEPUrl);
                })
                ;
                foreach (var encryptionMethod in encryptionMethods)
                {
                    var digest = element.OwnerDocument.CreateElement("DigestMethod", "http://www.w3.org/2000/09/xmldsig#");
                    digest.SetAttribute("Algorithm", digestMethod);
                    encryptionMethod.AppendChild(digest);
                }
            }

            return(element);
        }
        /// <summary>
        /// Creates a KeyInfo object based on information from specified certificate
        /// </summary>
        /// <param name="certificate">The certificate used to create the KeyInfo from</param>
        /// <returns>KeyInfo object</returns>
        private static KeyInfo CreateKeyInfoFromCertificate(X509Certificate2 certificate)
        {
            // create KeyInfoX509Data object & include certificate subject
            KeyInfoX509Data kiData = new KeyInfoX509Data(certificate);
            kiData.AddSubjectName(certificate.Subject);

            // create KeyInfo object with specified KeyInfoX509Data
            KeyInfo keyInfo = new KeyInfo();
            keyInfo.AddClause(kiData);

            return keyInfo;
        }
예제 #16
0
        public static string firmarDocumento(string documento, X509Certificate2 certificado)
        {
            XmlDocument doc = new XmlDocument();
            doc.PreserveWhitespace = true;
            String documento2 = documento;

            doc.LoadXml(documento);
            SignedXml signedXml = new SignedXml(doc);

            signedXml.SigningKey = certificado.PrivateKey;

            Signature XMLSignature = signedXml.Signature;

            Reference reference = new Reference("");

            XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform();
            reference.AddTransform(env);

            XMLSignature.SignedInfo.AddReference(reference);

            KeyInfo keyInfo = new KeyInfo();
            keyInfo.AddClause(new RSAKeyValue((RSA)certificado.PrivateKey));

            keyInfo.AddClause(new KeyInfoX509Data(certificado));

            XMLSignature.KeyInfo = keyInfo;

            signedXml.ComputeSignature();

            XmlElement xmlDigitalSignature = signedXml.GetXml();

            doc.DocumentElement.AppendChild(doc.ImportNode(xmlDigitalSignature, true));

            if (doc.FirstChild is XmlDeclaration)
            {
                doc.RemoveChild(doc.FirstChild);
            }

            return doc.InnerXml;
        }
예제 #17
0
        public  string SignXml(XDocument xml)
        {
          using (MemoryStream streamIn = new MemoryStream())
          {
            xml.Save(streamIn);
            streamIn.Position = 0;
          //  var rsaKey = (RSACryptoServiceProvider)_privateCertificate.PrivateKey; // Create rsa crypto provider from private key contained in certificate, weirdest cast ever!;



           // string sCertFileLocation = @"C:\plugins\idealtest\bin\Debug\certficate.pfx";
           // X509Certificate2 certificate = new X509Certificate2(sCertFileLocation, "D3M@ast3rsR0cks");
            RSA rsaKey = (RSACryptoServiceProvider)_privateCertificate.PrivateKey;

            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.PreserveWhitespace = true;
            xmlDoc.Load(streamIn);

            SignedXml signedXml = new SignedXml(xmlDoc);
            signedXml.SigningKey = rsaKey;

            Reference reference = new Reference();
            reference.Uri = "";
            XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform();
            reference.AddTransform(env);
            signedXml.AddReference(reference);


            KeyInfo keyInfo = new KeyInfo();
            KeyInfoName kin = new KeyInfoName();
            kin.Value = _privateCertificate.Thumbprint;
            keyInfo.AddClause(kin);
            signedXml.KeyInfo = keyInfo;

            signedXml.ComputeSignature();
            XmlElement xmlDigitalSignature = signedXml.GetXml();
            xmlDoc.DocumentElement.AppendChild(xmlDoc.ImportNode(xmlDigitalSignature, true));


            using (MemoryStream sout = new MemoryStream())
            {
              xmlDoc.Save(sout);
              sout.Position = 0;
              using (StreamReader reader = new StreamReader(sout))
              {
                string xmlOut = reader.ReadToEnd();
                return xmlOut;
              }
            }
          }

        }
예제 #18
0
    private KeyInfo getKeyInfo()
    {
      X509Extension extension = this.settings.Certificate.Extensions[1];
      AsnEncodedData asndata = new AsnEncodedData(extension.Oid, extension.RawData);

      KeyInfoX509Data keyInfoData = new KeyInfoX509Data();
      keyInfoData.AddIssuerSerial(this.settings.Certificate.Issuer, this.settings.Certificate.SerialNumber);
      keyInfoData.AddSubjectName(this.settings.Certificate.SubjectName.Name);

      KeyInfo keyInfo = new KeyInfo();
      keyInfo.AddClause(keyInfoData);
      return keyInfo;
    }
        public string AssinarComCertificado(string textXML, X509Certificate2 certificado)
        {
            try
            {
                string xmlString = textXML;

                XmlDocument doc = new XmlDocument();
                doc.PreserveWhitespace = false;
                doc.LoadXml(xmlString);

                Reference reference = new Reference();
                reference.Uri = "";

                XmlDocument documentoNovo = new XmlDocument();
                documentoNovo.LoadXml(doc.OuterXml);

                SignedXml signedXml = new SignedXml(documentoNovo);

                signedXml.SigningKey = certificado.PrivateKey;

                XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform();
                reference.AddTransform(env);

                XmlDsigC14NTransform c14 = new XmlDsigC14NTransform();
                reference.AddTransform(c14);

                signedXml.AddReference(reference);

                KeyInfo keyInfo = new KeyInfo();

                keyInfo.AddClause(new KeyInfoX509Data(certificado));

                signedXml.KeyInfo = keyInfo;
                signedXml.ComputeSignature();

                XmlElement xmlDigitalSignature = signedXml.GetXml();

                XmlNode sign = doc.ImportNode(xmlDigitalSignature, true);
                doc.ChildNodes.Item(0).AppendChild(sign);

                XmlDocument XMLDoc = new XmlDocument();
                XMLDoc.PreserveWhitespace = false;
                XMLDoc = doc;

                return XMLDoc.OuterXml;

            } catch (Exception error)
            {
                throw new Exception(error.Message);
            }
        }
예제 #20
0
        public static Signature ObterAssinatura <T>(T objeto, string id, X509Certificate2 certificadoDigital,
                                                    string signatureMethod = "http://www.w3.org/2000/09/xmldsig#rsa-sha1",
                                                    string digestMethod    = "http://www.w3.org/2000/09/xmldsig#sha1") where T : class
        {
            if (id == null)
            {
                throw new Exception("Não é possível assinar um objeto evento sem sua respectiva Id!");
            }

            var documento = new XmlDocument {
                PreserveWhitespace = true
            };

            var xml = XmlUtils.ClasseParaXmlString(objeto);

            documento.LoadXml(xml);

            var docXml = new SignedXml(documento)
            {
                SigningKey = certificadoDigital.PrivateKey
            };

            docXml.SignedInfo.SignatureMethod = signatureMethod;

            var reference = new Reference {
                Uri = "#" + id, DigestMethod = digestMethod
            };

            var envelopedSigntature = new XmlDsigEnvelopedSignatureTransform();

            reference.AddTransform(envelopedSigntature);

            var c14Transform = new XmlDsigC14NTransform();

            reference.AddTransform(c14Transform);

            docXml.AddReference(reference);

            var keyInfo = new KeyInfo();

            keyInfo.AddClause(new KeyInfoX509Data(certificadoDigital));

            docXml.KeyInfo = keyInfo;
            docXml.ComputeSignature();

            var xmlDigitalSignature = docXml.GetXml();
            var assinatura          = XmlUtils.XmlStringParaClasse <Signature>(xmlDigitalSignature.OuterXml);

            return(assinatura);
        }
예제 #21
0
        public static void SignDetachedResource(string inputFile, string outputSignatureXML, string certFile, String certPassword)
        {
            X509Certificate2 certxml = new X509Certificate2(certFile, certPassword);

            RSACryptoServiceProvider Key = (RSACryptoServiceProvider)certxml.PrivateKey;

            String XmlSigFileName = outputSignatureXML;

            // Sign the detached resourceand save the signature in an XML file.
            // Create a SignedXml object.
            SignedXml signedXml = new SignedXml();

            // Assign the key to the SignedXml object.
            signedXml.SigningKey = Key;

            // Create a reference to be signed.
            Reference reference = new Reference();

            // Add the passed Refrence to the reference object.
            reference.Uri = inputFile;

            // Add the reference to the SignedXml object.
            signedXml.AddReference(reference);

            // Add an RSAKeyValue KeyInfo (optional; helps recipient find key to validate).
            KeyInfo keyInfo = new KeyInfo();
            keyInfo.AddClause(new RSAKeyValue((RSA)Key));
            if (certxml != null)
            {
                KeyInfoX509Data kinfox509 = new KeyInfoX509Data(certxml, X509IncludeOption.WholeChain);
                kinfox509.AddIssuerSerial(certxml.Issuer, certxml.SerialNumber);
                kinfox509.AddSubjectName(certxml.Subject);
                keyInfo.AddClause(kinfox509);
            }
            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();

            // Save the signed XML document to a file specified
            // using the passed string.
            XmlTextWriter xmltw = new XmlTextWriter(XmlSigFileName, new UTF8Encoding(false));
            xmlDigitalSignature.WriteTo(xmltw);
            xmltw.Close();
        }
예제 #22
0
		public static KeyInfo GetKeyInfoFromXml(string xml)
		{
			// Use machine key store
			CspParameters cspParams = new CspParameters();
			cspParams.Flags = CspProviderFlags.UseMachineKeyStore;

			RSA rsa = new RSACryptoServiceProvider(cspParams);

			rsa.FromXmlString(xml);

			KeyInfo keyInfo = new KeyInfo();
			keyInfo.AddClause(new RSAKeyValue(rsa));

			return keyInfo;
		}
예제 #23
0
        public bool Execute()
        {
            Console.Out.WriteLine("Signing xml file");
            Console.Out.WriteLine("input file = {0}", _inputFile);
            Console.Out.WriteLine("output file = {0}", _signatureFile);
            Console.Out.WriteLine("key file = {0}", _keyFile);

            using (var key = new RSACryptoServiceProvider())
            {
                key.FromXmlString(File.ReadAllText(_keyFile));

                var doc = new XmlDocument {PreserveWhitespace = true};
                doc.Load(new XmlTextReader(_inputFile));

                var signedXml = new SignedXml(doc) {SigningKey = key};
                var xmlSignature = signedXml.Signature;

                var reference = new Reference("");
                var env = new XmlDsigEnvelopedSignatureTransform();
                reference.AddTransform(env);

                xmlSignature.SignedInfo.AddReference(reference);
                var keyInfo = new KeyInfo();
                keyInfo.AddClause(new RSAKeyValue(key));
                xmlSignature.KeyInfo = keyInfo;

                signedXml.ComputeSignature();

                var xmlDigitalSignature = signedXml.GetXml();

                using (var writer = new XmlTextWriter(_signatureFile, new UTF8Encoding(false)))
                {
                    var signatureDocument = new XmlDocument();
                    var importNode = signatureDocument.ImportNode(xmlDigitalSignature, true);

                    signatureDocument.AppendChild(importNode);

                    signatureDocument.WriteTo(writer);
                    writer.Close();
                }
            }

            Console.Out.WriteLine("done");

            return true;
        }
        public override string SignXml(XmlDocument Document)
        {
            SignedXmlWithId signedXml = new SignedXmlWithId(Document);
            signedXml.SigningKey = manager.Certificate.PrivateKey;

            KeyInfo keyInfo = new KeyInfo();
            KeyInfoX509Data keyInfoData = new KeyInfoX509Data(manager.Certificate);
            keyInfo.AddClause(keyInfoData);
            signedXml.KeyInfo = keyInfo;

            // the DataObject has to point to a XmlNodeList
            DataObject dataObject = new DataObject();
            dataObject.Id = "MyObjectID1";
            dataObject.Data =
               new CustomXmlNodeList(new[] { Document.DocumentElement });
            signedXml.AddObject(dataObject);

            // Add the reference to the SignedXml object.
            Reference reference = new Reference();
            reference.Uri = "#MyObjectID1";
            signedXml.AddReference(reference);

            // Create a reference to be signed.
            if (c14)
            {
                XmlDsigC14NTransform env = new XmlDsigC14NTransform();
                reference.AddTransform(env);
            }

            // Compute the signature.
            signedXml.ComputeSignature();

            // Get the XML representation of the signature and save
            // it to an XmlElement object.
            XmlElement xmlDigitalSignature = signedXml.GetXml();

            // create detached envelope
            XmlDocument envelope = new XmlDocument();
            envelope.AppendChild(envelope.CreateElement("Envelope"));

            envelope.DocumentElement.AppendChild(
               envelope.ImportNode(xmlDigitalSignature, true));

            return envelope.OuterXml;
        }
예제 #25
0
        public override string SignXml(XmlDocument Document)
        {
            // create detached envelope
            XmlDocument envelope = new XmlDocument();
            envelope.PreserveWhitespace = true;
            envelope.AppendChild(envelope.CreateElement("Envelope"));

            XmlElement message = envelope.CreateElement("Message");
            message.InnerXml = Document.DocumentElement.OuterXml;
            message.SetAttribute("Id", "MyObjectID");
            envelope.DocumentElement.AppendChild(message);

            SignedXmlWithId signedXml = new SignedXmlWithId(envelope);
            signedXml.SigningKey = manager.Certificate.PrivateKey;

            // Create a reference to be signed.
            Reference reference = new Reference();
            reference.Uri = "#MyObjectID";

            if (c14)
            {
                XmlDsigC14NTransform env = new XmlDsigC14NTransform();
                reference.AddTransform(env);
            }

            KeyInfo keyInfo = new KeyInfo();
            KeyInfoX509Data keyInfoData = new KeyInfoX509Data(manager.Certificate);
            keyInfo.AddClause(keyInfoData);
            signedXml.KeyInfo = keyInfo;

            // Add the reference to the SignedXml object.
            signedXml.AddReference(reference);

            // Compute the signature.
            signedXml.ComputeSignature();

            // Get the XML representation of the signature and save
            // it to an XmlElement object.
            XmlElement xmlDigitalSignature = signedXml.GetXml();

            envelope.DocumentElement.AppendChild(
               envelope.ImportNode(xmlDigitalSignature, true));

            return envelope.OuterXml;
        }
예제 #26
0
        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));
        }
예제 #27
0
        private static XmlElement GerarAssinatura(XmlDocument doc, string infoElement, string signAtribute,
                                                  X509Certificate2 certificado, bool comments = false, SignDigest digest = SignDigest.SHA1)
        {
            Guard.Against <ArgumentException>(!infoElement.IsEmpty() && doc.GetElementsByTagName(infoElement).Count != 1, "Referencia invalida ou não é unica.");

            //Adiciona Certificado ao Key Info
            var keyInfo = new KeyInfo();

            keyInfo.AddClause(new KeyInfoX509Data(certificado));

            //Seta chaves
            var signedDocument = new SignedXml(doc)
            {
                SigningKey = certificado.PrivateKey,
                KeyInfo    = keyInfo,
                SignedInfo =
                {
                    SignatureMethod = GetSignatureMethod(digest)
                }
            };

            var uri = infoElement.IsEmpty() || signAtribute.IsEmpty() ? "" :
                      $"#{doc.GetElementsByTagName(infoElement)[0].Attributes?[signAtribute]?.InnerText}";

            // Cria referencia
            var reference = new Reference
            {
                Uri          = uri,
                DigestMethod = GetDigestMethod(digest)
            };

            // Adiciona transformação a referencia
            reference.AddTransform(new XmlDsigEnvelopedSignatureTransform());
            reference.AddTransform(new XmlDsigC14NTransform(comments));

            // Adiciona referencia ao xml
            signedDocument.AddReference(reference);

            // Calcula Assinatura
            signedDocument.ComputeSignature();

            // Pega representação da assinatura
            return(signedDocument.GetXml());
        }
예제 #28
0
        private Legacy.KeyInfoEncryptedKey EncryptKey(byte[] key, RSA encryptionKey, string method, Legacy.KeyInfoClause encryptionKeyInfoClause)
        {
            var encryptionKeyInfo = new Legacy.KeyInfo();

            encryptionKeyInfo.AddClause(encryptionKeyInfoClause);
            var cipherValue  = Legacy.EncryptedXml.EncryptKey(key, encryptionKey, true);
            var encryptedKey = new Legacy.EncryptedKey
            {
                CipherData = new Legacy.CipherData {
                    CipherValue = cipherValue
                },
                EncryptionMethod = new Legacy.EncryptionMethod(method),
                KeyInfo          = encryptionKeyInfo
            };

            return(new Legacy.KeyInfoEncryptedKey {
                EncryptedKey = encryptedKey
            });
        }
예제 #29
0
        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);
        }
예제 #30
0
        public static void Sign(this XmlDocument xmlDocument, X509Certificate2 cert, bool includeKeyInfo)
        {
            if (xmlDocument == null)
            {
                throw new ArgumentNullException("xmlDocument");
            }

            if (cert == null)
            {
                throw new ArgumentNullException("cert");
            }

            var signedXml = new SignedXml(xmlDocument);

            // The transform XmlDsigExcC14NTransform and canonicalization method XmlDsigExcC14NTransformUrl is important for partially signed XML files
            // see: http://msdn.microsoft.com/en-us/library/system.security.cryptography.xml.signedxml.xmldsigexcc14ntransformurl(v=vs.110).aspx
            // The reference URI has to be set correctly to avoid assertion injections
            // For both, the ID/Reference and the Transform/Canonicalization see as well:
            // https://www.oasis-open.org/committees/download.php/35711/sstc-saml-core-errata-2.0-wd-06-diff.pdf section 5.4.2 and 5.4.3

            signedXml.SigningKey = (RSACryptoServiceProvider)cert.PrivateKey;
            signedXml.SignedInfo.CanonicalizationMethod = SignedXml.XmlDsigExcC14NTransformUrl;

            var reference = new Reference { Uri = "#" + xmlDocument.DocumentElement.GetAttribute("ID") };
            reference.AddTransform(new XmlDsigEnvelopedSignatureTransform());
            reference.AddTransform(new XmlDsigExcC14NTransform());

            signedXml.AddReference(reference);
            signedXml.ComputeSignature();

            if (includeKeyInfo)
            {
                var keyInfo = new KeyInfo();
                keyInfo.AddClause(new KeyInfoX509Data(cert));
                signedXml.KeyInfo = keyInfo;
            }

            xmlDocument.DocumentElement.InsertAfter(
                xmlDocument.ImportNode(signedXml.GetXml(), true),
                xmlDocument.DocumentElement["Issuer", Saml2Namespaces.Saml2Name]);
        }
예제 #31
0
        public static void SignSingleEntity(
            this GisGmp.Message message,
            X509Certificate2 certificate,
            XmlNode entityXml)
        {
            XmlDocument signingDoc = new XmlDocument();
            signingDoc.LoadXml(entityXml.OuterXml);

            SmevSignedXml signedXml = new SmevSignedXml(signingDoc);
            signedXml.SigningKey = certificate.PrivateKey;

            Reference reference = new Reference();
            reference.Uri = "";
            reference.DigestMethod = CryptoPro.Sharpei.Xml.CPSignedXml.XmlDsigGost3411UrlObsolete;

            XmlDsigEnvelopedSignatureTransform envelopedSignature = new XmlDsigEnvelopedSignatureTransform();
            reference.AddTransform(envelopedSignature);
            XmlDsigExcC14NTransform c14 = new XmlDsigExcC14NTransform();
            reference.AddTransform(c14);

            KeyInfo ki = new KeyInfo();
            ki.AddClause(new KeyInfoX509Data(certificate));

            signedXml.KeyInfo = ki;
            signedXml.SignedInfo.CanonicalizationMethod = SignedXml.XmlDsigExcC14NTransformUrl;
            signedXml.SignedInfo.SignatureMethod = CryptoPro.Sharpei.Xml.CPSignedXml.XmlDsigGost3410UrlObsolete;
            signedXml.AddReference(reference);

            signedXml.ComputeSignature();

            XmlElement xmlDigitalSignature = signedXml.GetXml();

            signingDoc.DocumentElement.AppendChild(xmlDigitalSignature);

            XmlDocumentFragment signedFinalPayment = message.Xml.CreateDocumentFragment();
            signedFinalPayment.InnerXml = signingDoc.OuterXml;

            var documentNode = entityXml.ParentNode;
            documentNode.RemoveChild(entityXml);
            documentNode.AppendChild(signedFinalPayment);
        }
예제 #32
0
        public override string SignXml(XmlDocument Document)
        {
            SignedXmlWithId signedXml = new SignedXmlWithId(Document);
            signedXml.SigningKey = manager.Certificate.PrivateKey;

            // Create a reference to be signed.
            Reference reference = new Reference();
            reference.Uri = "";

            // Add an enveloped transformation to the reference.
            XmlDsigEnvelopedSignatureTransform env =
               new XmlDsigEnvelopedSignatureTransform(true);
            reference.AddTransform(env);

            if (c14)
            {
                XmlDsigC14NTransform c14t = new XmlDsigC14NTransform();
                reference.AddTransform(c14t);
            }

            KeyInfo keyInfo = new KeyInfo();
            KeyInfoX509Data keyInfoData = new KeyInfoX509Data(manager.Certificate);
            keyInfo.AddClause(keyInfoData);
            signedXml.KeyInfo = keyInfo;

            // Add the reference to the SignedXml object.
            signedXml.AddReference(reference);

            // Compute the signature.
            signedXml.ComputeSignature();

            // Get the XML representation of the signature and save
            // it to an XmlElement object.
            XmlElement xmlDigitalSignature = signedXml.GetXml();

            Document.DocumentElement.AppendChild(
                Document.ImportNode(xmlDigitalSignature, true));

            return Document.OuterXml;
        }
예제 #33
0
        public static void SignXmlDocument(Stream sourceXmlFile,
            Stream destinationXmlFile, X509Certificate2 certificate)
        {
            // Carico il documento XML
            XmlDocument doc = new XmlDocument();
            doc.Load(sourceXmlFile);

            // Preparo un DOMDocument che conterrà il risultato
            XmlDocument outputDocument = new XmlDocument();

            // Recupero un riferimento all'intero contenuto del documento XML
            XmlNodeList elementsToSign = doc.SelectNodes(String.Format("/{0}", doc.DocumentElement.Name));

            // Costruisco la firma
            SignedXml signedXml = new SignedXml();
            System.Security.Cryptography.Xml.DataObject dataSignature =
                new System.Security.Cryptography.Xml.DataObject();
            dataSignature.Data = elementsToSign;
            dataSignature.Id = doc.DocumentElement.Name;
            signedXml.AddObject(dataSignature);
            Reference reference = new Reference();
            reference.Uri = String.Format("#{0}", dataSignature.Id);
            signedXml.AddReference(reference);

            if ((certificate != null) && (certificate.HasPrivateKey))
            {
                signedXml.SigningKey = certificate.PrivateKey;

                KeyInfo keyInfo = new KeyInfo();
                keyInfo.AddClause(new KeyInfoX509Data(certificate));
                signedXml.KeyInfo = keyInfo;
                signedXml.ComputeSignature();

                // Aggiungo la firma al nuovo documento di output
                outputDocument.AppendChild(
                    outputDocument.ImportNode(signedXml.GetXml(), true));

                outputDocument.Save(destinationXmlFile);
            }
        }
예제 #34
0
        /// <summary>
        /// Signs an XML Document for a Saml Response
        /// </summary>
        /// <param name="xml"></param>
        /// <param name="cert2"></param>
        /// <param name="referenceId"></param>
        /// <returns></returns>
        public static XmlElement SignDoc(XmlDocument doc, X509Certificate2 cert2, string referenceId, string referenceValue)
        {
            SamlSignedXml sig = new SamlSignedXml(doc, referenceId);
            // Add the key to the SignedXml xmlDocument.
            sig.SigningKey = cert2.PrivateKey;

            // Create a reference to be signed.
            Reference reference = new Reference();

            reference.Uri = String.Empty;
            // reference.Uri = "#" + referenceValue;

            // Add an enveloped transformation to the reference.
            XmlDsigEnvelopedSignatureTransform env = new
                XmlDsigEnvelopedSignatureTransform();
            XmlDsigExcC14NTransform env2 = new XmlDsigExcC14NTransform();

            reference.AddTransform(env);
            reference.AddTransform(env2);

            // Add the reference to the SignedXml object.
            sig.AddReference(reference);

            // Add an RSAKeyValue KeyInfo (optional; helps recipient find key to validate).
            KeyInfo keyInfo = new KeyInfo();
            KeyInfoX509Data keyData = new KeyInfoX509Data(cert2);

            keyInfo.AddClause(keyData);

            sig.KeyInfo = keyInfo;

            // Compute the signature.
            sig.ComputeSignature();

            // Get the XML representation of the signature and save it to an XmlElement object.
            XmlElement xmlDigitalSignature = sig.GetXml();

            return xmlDigitalSignature;
        }
예제 #35
0
        /// <summary>
        /// Takes the configuration class and converts it to a SAML2.0 metadata document.
        /// </summary>
        /// <param name="config">The config.</param>
        /// <param name="keyInfo">The keyInfo.</param>
        private void ConvertToMetadata(Saml2Configuration config)
        {
            var entity = CreateDefaultEntity();

            entity.EntityId = config.ServiceProvider.Id;
            if (config.ServiceProvider.UseValidUntil)
            {
                entity.ValidUntil = DateTime.Now.AddDays(7);
            }

            var serviceProviderDescriptor = new SpSsoDescriptor
            {
                ProtocolSupportEnumeration = new[] { Saml20Constants.Protocol },
                AuthnRequestsSigned        = XmlConvert.ToString(config.ServiceProvider.AuthNRequestsSigned),
                WantAssertionsSigned       = XmlConvert.ToString(config.ServiceProvider.WantAssertionsSigned)
            };

            if (config.ServiceProvider.NameIdFormats.Count > 0)
            {
                serviceProviderDescriptor.NameIdFormat = new string[config.ServiceProvider.NameIdFormats.Count];
                var count = 0;
                foreach (var elem in config.ServiceProvider.NameIdFormats)
                {
                    serviceProviderDescriptor.NameIdFormat[count++] = elem.Format;
                }
            }

            var baseUrl = new Uri(config.ServiceProvider.Server);
            var logoutServiceEndpoints = new List <Endpoint>();
            var signonServiceEndpoints = new List <IndexedEndpoint>();

            var artifactResolutionEndpoints = new List <IndexedEndpoint>(2);

            // Include endpoints.
            foreach (var endpoint in config.ServiceProvider.Endpoints)
            {
                if (endpoint.Type == EndpointType.SignOn)
                {
                    var loginEndpoint = new IndexedEndpoint
                    {
                        Index     = endpoint.Index,
                        IsDefault = endpoint.Default,
                        Location  = new Uri(baseUrl, endpoint.LocalPath).ToString(),
                        Binding   = GetBinding(endpoint.Binding, Saml20Constants.ProtocolBindings.HttpPost)
                    };
                    signonServiceEndpoints.Add(loginEndpoint);

                    if (config.ServiceProvider.IncludeArtifactResolutionEndpoints)
                    {
                        var artifactSignonEndpoint = new IndexedEndpoint
                        {
                            Binding  = Saml20Constants.ProtocolBindings.HttpSoap,
                            Index    = loginEndpoint.Index,
                            Location = loginEndpoint.Location
                        };
                        artifactResolutionEndpoints.Add(artifactSignonEndpoint);
                    }

                    continue;
                }

                if (endpoint.Type == EndpointType.Logout)
                {
                    var location       = new Uri(baseUrl, endpoint.LocalPath).ToString();
                    var logoutEndpoint = new Endpoint
                    {
                        Location         = location,
                        ResponseLocation = location,
                        Binding          = GetBinding(endpoint.Binding, Saml20Constants.ProtocolBindings.HttpPost)
                    };
                    logoutServiceEndpoints.Add(logoutEndpoint);

                    if (config.ServiceProvider.IncludeArtifactResolutionEndpoints)
                    {
                        var artifactLogoutEndpoint = new IndexedEndpoint
                        {
                            Binding  = Saml20Constants.ProtocolBindings.HttpSoap,
                            Index    = endpoint.Index,
                            Location = logoutEndpoint.Location
                        };
                        artifactResolutionEndpoints.Add(artifactLogoutEndpoint);
                    }
                    continue;
                }
            }

            serviceProviderDescriptor.SingleLogoutService      = logoutServiceEndpoints.ToArray();
            serviceProviderDescriptor.AssertionConsumerService = signonServiceEndpoints.ToArray();

            // Attribute consuming service.
            if (config.Metadata.RequestedAttributes.Count > 0)
            {
                var attConsumingService = new AttributeConsumingService();
                serviceProviderDescriptor.AttributeConsumingService = new[] { attConsumingService };
                attConsumingService.Index       = signonServiceEndpoints[0].Index;
                attConsumingService.IsDefault   = true;
                attConsumingService.ServiceName = new[] { new LocalizedName("SP", "en") };

                attConsumingService.RequestedAttribute = new RequestedAttribute[config.Metadata.RequestedAttributes.Count];

                for (var i = 0; i < config.Metadata.RequestedAttributes.Count; i++)
                {
                    attConsumingService.RequestedAttribute[i] = new RequestedAttribute
                    {
                        Name       = config.Metadata.RequestedAttributes[i].Name,
                        NameFormat = SamlAttribute.NameformatBasic
                    };

                    if (config.Metadata.RequestedAttributes[i].IsRequired)
                    {
                        attConsumingService.RequestedAttribute[i].IsRequired = true;
                    }
                }
            }
            else
            {
                serviceProviderDescriptor.AttributeConsumingService = new AttributeConsumingService[0];
            }

            if (config.Metadata == null || !config.Metadata.ExcludeArtifactEndpoints)
            {
                serviceProviderDescriptor.ArtifactResolutionService = artifactResolutionEndpoints.ToArray();
            }

            entity.Items = new object[] { serviceProviderDescriptor };

            // Keyinfo
            var keySigning    = new KeyDescriptor();
            var keyEncryption = new KeyDescriptor();

            serviceProviderDescriptor.KeyDescriptor = new[] { keySigning, keyEncryption };

            keySigning.Use          = KeyTypes.Signing;
            keySigning.UseSpecified = true;

            keyEncryption.Use          = KeyTypes.Encryption;
            keyEncryption.UseSpecified = true;

            var keyinfo   = new System.Security.Cryptography.Xml.KeyInfo();
            var keyClause = new System.Security.Cryptography.Xml.KeyInfoX509Data(config.ServiceProvider.SigningCertificate, X509IncludeOption.EndCertOnly);

            keyinfo.AddClause(keyClause);

            // Ugly conversion between the .Net framework classes and our classes ... avert your eyes!!
            keySigning.KeyInfo    = Serialization.DeserializeFromXmlString <Schema.XmlDSig.KeyInfo>(keyinfo.GetXml().OuterXml);
            keyEncryption.KeyInfo = keySigning.KeyInfo;

            // apply the <Organization> element
            if (config.Metadata.Organization != null)
            {
                entity.Organization = new Schema.Metadata.Organization
                {
                    OrganizationName = new[] { new LocalizedName {
                                                   Value = config.Metadata.Organization.Name, Language = "en"
                                               } },
                    OrganizationDisplayName = new[] { new LocalizedName {
                                                          Value = config.Metadata.Organization.DisplayName, Language = "en"
                                                      } },
                    OrganizationURL = new[] { new LocalizedURI {
                                                  Value = config.Metadata.Organization.Url, Language = "en"
                                              } }
                };
            }

            if (config.Metadata.Contacts != null && config.Metadata.Contacts.Any())
            {
                entity.ContactPerson = config.Metadata.Contacts.Select(x => new Schema.Metadata.Contact
                {
                    ContactType =
                        (Schema.Metadata.ContactType)
                            ((int)x.Type),
                    Company         = x.Company,
                    GivenName       = x.GivenName,
                    SurName         = x.SurName,
                    EmailAddress    = new[] { x.Email },
                    TelephoneNumber = new[] { x.Phone }
                }).ToArray();
            }
        }
예제 #36
0
		// creates a signed XML document with two certificates in the X509Data 
		// element, with the second being the one that should be used to verify
		// the signature
		static XmlDocument CreateSignedXml (X509Certificate2 cert, string canonicalizationMethod, string lineFeed)
		{
			XmlDocument doc = CreateSomeXml (lineFeed);

			SignedXml signedXml = new SignedXml (doc);
			signedXml.SigningKey = cert.PrivateKey;
			signedXml.SignedInfo.CanonicalizationMethod = canonicalizationMethod;

			Reference reference = new Reference ();
			reference.Uri = "";

			XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform ();
			reference.AddTransform (env);
			signedXml.AddReference (reference);

			KeyInfo keyInfo = new KeyInfo ();
			KeyInfoX509Data x509KeyInfo = new KeyInfoX509Data ();
			x509KeyInfo.AddCertificate (new X509Certificate2 (_cert));
			x509KeyInfo.AddCertificate (cert);
			keyInfo.AddClause (x509KeyInfo);
			signedXml.KeyInfo = keyInfo;

			signedXml.ComputeSignature ();
			XmlElement xmlDigitalSignature = signedXml.GetXml ();

			doc.DocumentElement.AppendChild (doc.ImportNode (xmlDigitalSignature, true));
			return doc;
		}
예제 #37
0
파일: Generar.cs 프로젝트: RSEANCAS/bilecom
        //public static string RetornarXmlFirmado(string xmlString, string rutaCertificado, string claveCertificado, out string hash)
        //{
        //    hash = null;

        //    XmlDocument documentXml = new XmlDocument();

        //    documentXml.PreserveWhitespace = true;
        //    documentXml.LoadXml(xmlString);
        //    var nodoExtension = documentXml.GetElementsByTagName("ExtensionContent", "urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2").Item(0);

        //    if (nodoExtension == null)
        //    {
        //        throw new InvalidOperationException("No se pudo encontrar el nodo ExtensionContent en el XML");
        //    }

        //    nodoExtension.RemoveAll();

        //    SignedXml firmado = new SignedXml(documentXml);

        //    var xmlSignature = firmado.Signature;

        //    byte[] certificadoByte = File.ReadAllBytes(rutaCertificado);
        //    X509Certificate2 certificado = new X509Certificate2();
        //    //certificado.Import(certificadoByte, claveCertificado, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable);
        //    certificado.Import(certificadoByte, claveCertificado, X509KeyStorageFlags.Exportable);
        //    firmado.SigningKey = certificado.GetRSAPrivateKey();
        //    //firmado.SigningKey = (RSA)certificado.PrivateKey;
        //    //firmado.SigningKey = certificado.PrivateKey;

        //    //digest info agregada en la seccion firma
        //    var env = new XmlDsigEnvelopedSignatureTransform();
        //    Reference reference = new Reference();
        //    reference.AddTransform(env);

        //    reference.Uri = "";
        //    firmado.AddReference(reference);
        //    firmado.SignedInfo.SignatureMethod = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256";

        //    reference.DigestMethod = "http://www.w3.org/2001/04/xmlenc#sha256";

        //    var keyInfoData = new KeyInfoX509Data(certificado);
        //    keyInfoData.AddSubjectName(certificado.Subject);

        //    // info para la llave publica
        //    KeyInfo keyInfo = new KeyInfo();
        //    keyInfo.AddClause(keyInfoData);
        //    //keyInfo.sub

        //    xmlSignature.KeyInfo = keyInfo;
        //    xmlSignature.Id = "signatureKG";
        //    firmado.ComputeSignature();


        //    // Recuperamos el valor Hash de la firma para este documento.
        //    if (reference.DigestValue != null)
        //    {
        //        hash = Convert.ToBase64String(reference.DigestValue);
        //    }

        //    XmlNode xmlNodeFirmado = firmado.GetXml();
        //    xmlNodeFirmado.Prefix = "ds";

        //    //XmlNode xmlNodeContent = documentXml.CreateElement("ext", "ExtensionContent", "urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2");
        //    //xmlNodeContent.AppendChild(xmlNodeFirmado);

        //    //XmlNode xmlNode = documentXml.CreateElement("ext", "UBLExtension", "urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2");
        //    //xmlNode.AppendChild(xmlNodeContent);

        //    nodoExtension.AppendChild(xmlNodeFirmado);

        //    var settings = new XmlWriterSettings()
        //    {
        //        Encoding = Encoding.UTF8,
        //        Indent = true,
        //        IndentChars = "\t",
        //        NewLineChars = Environment.NewLine

        //    };

        //    string resultado = String.Empty;
        //    using (var memDoc = new MemoryStream())
        //    {

        //        using (var writer = XmlWriter.Create(memDoc, settings))
        //        {
        //            //XDocument xDocument = XDocument.Parse(documentXml.OuterXml);
        //            //xDocument.WriteTo(writer);
        //            documentXml.WriteTo(writer);
        //        }

        //        //resultado = Encoding.Unicode.GetString(memDoc.ToArray());
        //        //resultado = Encoding.GetEncoding("ISO-8859-1").GetString(memDoc.ToArray());
        //        //resultado = Convert.ToBase64String(memDoc.ToArray());
        //        resultado = Encoding.UTF8.GetString(memDoc.ToArray());

        //    }
        //    return resultado;
        //}

        public static string RetornarXmlFirmado(string prefijoComprobanteBusqueda, string tnsString, string xmlString, string rutaCertificado, string claveCertificado, out string hash)
        {
            hash = null;

            XmlDocument xmlDocument = new XmlDocument();

            xmlDocument.PreserveWhitespace = true;
            xmlDocument.LoadXml(xmlString);

            X509Certificate2 certificado = new X509Certificate2(rutaCertificado, claveCertificado);

            XmlNamespaceManager nsMgr = new XmlNamespaceManager(xmlDocument.NameTable);

            nsMgr.AddNamespace("tns", tnsString);
            nsMgr.AddNamespace("ext", "urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2");

            XmlElement elem = xmlDocument.CreateElement("ext:ExtensionContent", "urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2");

            xmlDocument.SelectSingleNode($"{prefijoComprobanteBusqueda}/ext:UBLExtensions/ext:UBLExtension", nsMgr).AppendChild(elem);

            SignedXml signedXml = new SignedXml(xmlDocument);

            signedXml.SigningKey = certificado.GetRSAPrivateKey();
            System.Security.Cryptography.Xml.KeyInfo KeyInfo = new System.Security.Cryptography.Xml.KeyInfo();

            System.Security.Cryptography.Xml.Reference Reference = new System.Security.Cryptography.Xml.Reference();
            Reference.Uri = "";

            Reference.AddTransform(new XmlDsigEnvelopedSignatureTransform());
            signedXml.AddReference(Reference);

            X509Chain X509Chain = new X509Chain();

            X509Chain.Build(certificado);

            X509ChainElement local_element = X509Chain.ChainElements[0];
            KeyInfoX509Data  x509Data      = new KeyInfoX509Data(local_element.Certificate);

            string subjectName = local_element.Certificate.Subject;

            x509Data.AddSubjectName(subjectName);
            KeyInfo.AddClause(x509Data);
            signedXml.Signature.Id = "signatureKG";
            signedXml.KeyInfo      = KeyInfo;
            signedXml.ComputeSignature();
            XmlElement signature = signedXml.GetXml();
            XmlNode    dg        = signature.GetElementsByTagName("DigestValue", "http://www.w3.org/2000/09/xmldsig#")[0];
            XmlNode    sg        = signature.GetElementsByTagName("SignatureValue", "http://www.w3.org/2000/09/xmldsig#")[0];

            hash = dg.InnerText;
            //SignatureValue = sg.InnerText;

            signature.Prefix = "ds";
            //SetPrefix("ds", signature);

            elem.AppendChild(signature);

            MemoryStream msXMLFirmado = new MemoryStream();

            xmlDocument.Save(msXMLFirmado);

            //msXMLFirmado.Position = 1;

            return(Encoding.UTF8.GetString(msXMLFirmado.ToArray()).Substring(1));
        }
예제 #38
0
		public void DigestValue_LF ()
		{
			XmlDocument doc = CreateSomeXml ("\n");
			XmlDsigExcC14NTransform transform = new XmlDsigExcC14NTransform ();
			transform.LoadInput (doc);
			Stream s = (Stream) transform.GetOutput ();
			string output = Stream2String (s);
			Assert.AreEqual ("<person>\n  <birthplace>Brussels</birthplace>\n</person>", output, "#1");

			s.Position = 0;

			HashAlgorithm hash = HashAlgorithm.Create ("System.Security.Cryptography.SHA1CryptoServiceProvider");
			byte[] digest = hash.ComputeHash (s);
			Assert.AreEqual ("e3dsi1xK8FAx1vsug7J203JbEAU=", Convert.ToBase64String (digest), "#2");

			X509Certificate2 cert = new X509Certificate2 (_pkcs12, "mono");
			SignedXml signedXml = new SignedXml (doc);
			signedXml.SigningKey = cert.PrivateKey;
			signedXml.SignedInfo.CanonicalizationMethod = SignedXml.XmlDsigExcC14NTransformUrl;

			Reference reference = new Reference ();
			reference.Uri = "";

			XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform ();
			reference.AddTransform (env);
			signedXml.AddReference (reference);

			KeyInfo keyInfo = new KeyInfo ();
			KeyInfoX509Data x509KeyInfo = new KeyInfoX509Data ();
			x509KeyInfo.AddCertificate (new X509Certificate2 (_cert));
			x509KeyInfo.AddCertificate (cert);
			keyInfo.AddClause (x509KeyInfo);
			signedXml.KeyInfo = keyInfo;

			signedXml.ComputeSignature ();

			digest = reference.DigestValue;
			Assert.AreEqual ("e3dsi1xK8FAx1vsug7J203JbEAU=", Convert.ToBase64String (digest), "#3");

			Assert.AreEqual ("<SignedInfo xmlns=\"http://www.w3.org/2000/09/xmldsig#\">" 
				+ "<CanonicalizationMethod Algorithm=\"http://www.w3.org/2001/10/xml-exc-c14n#\" />"
				+ "<SignatureMethod Algorithm=\"http://www.w3.org/2000/09/xmldsig#rsa-sha1\" />"
				+ "<Reference URI=\"\">"
				+ "<Transforms>"
				+ "<Transform Algorithm=\"http://www.w3.org/2000/09/xmldsig#enveloped-signature\" />"
				+ "</Transforms>"
				+ "<DigestMethod Algorithm=\"http://www.w3.org/2000/09/xmldsig#sha1\" />"
				+ "<DigestValue>e3dsi1xK8FAx1vsug7J203JbEAU=</DigestValue>"
				+ "</Reference>"
				+ "</SignedInfo>", signedXml.SignedInfo.GetXml ().OuterXml, "#4");
		}
예제 #39
0
        public static void SignXmlFile(string fileName, ref string signedContent, RSA key)
        {
            // Check the arguments.
            if (fileName == null)
            {
                throw new ArgumentNullException("fileName");
            }
            if (signedContent == null)
            {
                throw new ArgumentNullException("signedFileName");
            }
            if (key == null)
            {
                throw new ArgumentNullException("key");
            }

            // Create a new XML document.
            XmlDocument doc = new XmlDocument();

            // Format the document to ignore white spaces.
            doc.PreserveWhitespace = false;
            // Load the passed XML file using it's name.
            //doc.Load(new XmlTextReader(FileName));
            doc.LoadXml(fileName);
            // Create a SignedXml object.
            SignedXml signedXml = new SignedXml(doc);

            // Add the key to the SignedXml document.
            signedXml.SigningKey = key;
            // Get the signature object from the SignedXml object.
            System.Security.Cryptography.Xml.Signature XMLSignature = signedXml.Signature;
            // Create a reference to be signed.  Pass ""
            // to specify that all of the current XML
            // document should be signed.
            System.Security.Cryptography.Xml.Reference reference = new System.Security.Cryptography.Xml.Reference("");
            // Add an enveloped transformation to the reference.
            XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform();

            reference.AddTransform(env);
            // Add the Reference object to the Signature object.
            XMLSignature.SignedInfo.AddReference(reference);
            // Add an RSAKeyValue KeyInfo (optional; helps recipient find key to validate).
            System.Security.Cryptography.Xml.KeyInfo keyInfo = new System.Security.Cryptography.Xml.KeyInfo();
            keyInfo.AddClause(new RSAKeyValue((RSA)key));
            // Add the KeyInfo object to the Reference object.
            XMLSignature.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);
            }

            signedContent = doc.InnerXml;
        }
예제 #40
0
        /// <summary>
        /// Gera assinatura Digital do XML
        /// </summary>
        /// <param name="XMLString"></param>
        /// <param name="RefUri"></param>
        /// <param name="X509Cert"></param>
        /// <returns></returns>
        public int Assinar(string XMLString, string RefUri, X509Certificate2 X509Cert)
        {


            int resultado = 0;
            msgResultado = "Assinatura realizada com sucesso";
            try
            {
                //   certificado para ser utilizado na assinatura
                //
                string _xnome = "";

                bool bX509Cert = false;

                if (X509Cert != null)
                {
                    _xnome = X509Cert.Subject.ToString();
                }
                else
                {
                    bX509Cert = true;
                }
                X509Certificate2 _X509Cert = new X509Certificate2();
                X509Store store = new X509Store("MY", StoreLocation.CurrentUser);
                store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);
                X509Certificate2Collection collection = (X509Certificate2Collection)store.Certificates;
                X509Certificate2Collection collection1 = (X509Certificate2Collection)collection.Find(X509FindType.FindBySubjectDistinguishedName, (object)_xnome, true);

                //if (collection1.Count == 0)
                if (bX509Cert)
                {
                    resultado = 2;
                    msgResultado = "Problemas no certificado digital";
                }
                else
                {
                    // certificado ok
                    //_X509Cert = collection1[0];

                    _X509Cert = X509Cert;
                    string x;
                    x = _X509Cert.GetKeyAlgorithm().ToString();
                    // Create a new XML document.

                    XmlDocument doc = new XmlDocument();

                    // Format the document to ignore white spaces.
                    doc.PreserveWhitespace = false;

                    // Load the passed XML file using it's name.
                    try
                    {
                        doc.LoadXml(XMLString);

                        // Verifica se a tag a ser assinada existe é única
                        int qtdeRefUri = doc.GetElementsByTagName(RefUri).Count;

                        if (qtdeRefUri == 0)
                        {
                            //  a URI indicada não existe
                            resultado = 4;
                            msgResultado = "A tag de assinatura " + RefUri.Trim() + " inexiste";
                        }
                        // Exsiste mais de uma tag a ser assinada
                        else
                        {

                            if (qtdeRefUri > 1)
                            {
                                // existe mais de uma URI indicada
                                resultado = 5;
                                msgResultado = "A tag de assinatura " + RefUri.Trim() + " não é unica";

                            }
                            else
                            {
                                try
                                {
                                    //Claudinei - o.s. 23615 - 10/08/2009
                                    //for (int i = 0; i < qtdeRefUri; i++)
                                    {
                                        //Fim - Claudinei - o.s. 23615 - 10/08/2009

                                        // Create a SignedXml object.
                                        SignedXml signedXml = new SignedXml(doc);

                                        //sTipoAssinatura = _X509Cert.PrivateKey.KeySize.ToString();
                                        // Add the key to the SignedXml document 
                                        signedXml.SigningKey = _X509Cert.PrivateKey;

                                        // Create a reference to be signed
                                        Reference reference = new Reference();
                                        // pega o uri que deve ser assinada
                                        XmlAttributeCollection _Uri = doc.GetElementsByTagName(RefUri).Item(0).Attributes; //Claudinei - o.s. 23615 - 10/08/2009
                                        foreach (XmlAttribute _atributo in _Uri)
                                        {
                                            if (_atributo.Name == "Id")
                                            {
                                                reference.Uri = "#" + _atributo.InnerText;
                                            }
                                        }

                                        // Add an enveloped transformation to the reference.
                                        XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform();
                                        reference.AddTransform(env);

                                        XmlDsigC14NTransform c14 = new XmlDsigC14NTransform();
                                        reference.AddTransform(c14);

                                        // 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(_X509Cert));

                                        // Add the KeyInfo object to the SignedXml object.
                                        signedXml.KeyInfo = keyInfo;

                                        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.

                                        //Claudinei - o.s. 23581 - 07/07/2009
                                        /*
                                        string teste = "";
                                        //XmlNode xmlno = new XmlNode();
                                        foreach (XmlNode xmlno in doc)
                                        {
                                            teste = xmlno.Name.ToString();
                                        }
                                         */
                                        //Fim - Claudinei - o.s. 23581 - 07/07/2009

                                        //Danner - o.s. 23732 - 11/11/2009
                                        doc.DocumentElement.AppendChild(doc.ImportNode(xmlDigitalSignature, true));
                                        //Fim - Danner - o.s. 23732 - 11/11/2009
                                        XMLDoc = new XmlDocument();
                                        XMLDoc.PreserveWhitespace = false;
                                        XMLDoc = doc;
                                    } //Claudinei - o.s. 23615 - 10/08/2009
                                }

                                catch (Exception caught)
                                {
                                    resultado = 7;
                                    msgResultado = "Erro: Ao assinar o documento - " + caught.Message;
                                }

                            }
                        }
                    }

                    catch (Exception caught)
                    {
                        resultado = 3;
                        msgResultado = "Erro: XML mal formado - " + caught.Message;
                    }
                }
            }
            catch (Exception caught)
            {
                resultado = 1;
                msgResultado = "Erro: Problema ao acessar o certificado digital" + caught.Message;
            }

            return resultado;
        }
예제 #41
0
        /// <summary>
        /// Message signing
        /// </summary>
        public virtual byte[] Sign(
            ISignableMessage message,
            X509Configuration x509Configuration)
        {
            if (message == null)
            {
                throw new ArgumentNullException("message");
            }
            if (x509Configuration == null ||
                x509Configuration.SignatureCertificate == null
                )
            {
                throw new ArgumentNullException("certificate");
            }

            // first, serialize to XML
            var messageBody = this.messageSerializer.Serialize(message, new MessageSerializationParameters()
            {
                ShouldBase64Encode = false,
                ShouldDeflate      = false
            });

            var xml = new XmlDocument();

            xml.LoadXml(messageBody);

            // sign the node with the id
            var reference = new Reference("#" + message.ID);
            var envelope  = new XmlDsigEnvelopedSignatureTransform(true);

            reference.AddTransform(envelope);

            // canonicalization
            var c14 = new XmlDsigExcC14NTransform();

            c14.Algorithm = SignedXml.XmlDsigExcC14NTransformUrl;
            reference.AddTransform(c14);

            // some more spells depending on SHA1 vs SHA256
            var signed = new SignedXml(xml);

            signed.SignedInfo.CanonicalizationMethod = SignedXml.XmlDsigExcC14NTransformUrl;
            switch (x509Configuration.SignatureAlgorithm)
            {
            case SignatureAlgorithm.SHA1:
                signed.SigningKey = x509Configuration.SignatureCertificate.PrivateKey;
                signed.SignedInfo.SignatureMethod = SignedXml.XmlDsigRSASHA1Url;
                reference.DigestMethod            = SignedXml.XmlDsigSHA1Url;
                break;

            case SignatureAlgorithm.SHA256:
                signed.SigningKey = x509Configuration.SignatureCertificate.ToSha256PrivateKey();
                signed.SignedInfo.SignatureMethod = SignedXml.XmlDsigRSASHA256Url;
                reference.DigestMethod            = SignedXml.XmlDsigSHA256Url;
                break;
            }

            if (x509Configuration.IncludeKeyInfo)
            {
                var key     = new System.Security.Cryptography.Xml.KeyInfo();
                var keyData = new KeyInfoX509Data(x509Configuration.SignatureCertificate);
                key.AddClause(keyData);
                signed.KeyInfo = key;
            }

            // show the reference
            signed.AddReference(reference);
            // create the signature
            signed.ComputeSignature();
            var signature = signed.GetXml();

            // insert the signature into the document
            var element = xml.DocumentElement.ChildNodes[0];

            xml.DocumentElement.InsertAfter(xml.ImportNode(signature, true), element);

            // log
            new LoggerFactory().For(this).Debug(Event.SignedMessage, xml.OuterXml);

            // convert
            return(this.encoding.GetBytes(xml.OuterXml));
        }