public static void Test(X509IncludeOption include)
		{
		cert = EndCert ;
		X509Chain chain = new X509Chain() ; 
		chain.Build( cert ) ; 

		X509ChainElementCollection lmnts = chain.ChainElements ; 
		
		KeyInfoX509Data data = new KeyInfoX509Data( cert, include )  ; 	
		ArrayList al = data.Certificates ; 
		if( al == null ) return ; 
		for( int i = 0 ; i < al.Count ; i++ ) 
			{
			rv = lmnts[i].Certificate.ToString(true) == ((X509Certificate) al[i]).ToString(true) ;
			if( !rv ) 		
				Console.WriteLine( "i  = " + i.ToString() + " and include=" + include.ToString() ) ; 
			}
		Console.WriteLine( "*************************************************************" ) ; 
		}
	static void Test5()
		{
		data = new KeyInfoX509Data() ; 

		//add issuer serials
		data.AddIssuerSerial( TestCert.IssuerName.Name , TestCert.SerialNumber ) ; 
		data.AddIssuerSerial( EndCert.IssuerName.Name , EndCert.SerialNumber ) ; 
		rv = data.IssuerSerials.Count == 2; 

		byte[] b = { 100, 101 , 102 , 104 } ; 
		data = new KeyInfoX509Data() ; 
		data.CRL = b ;
		for( int i = 0 ; i < b.Length ; i++ ) 
			{
			rv = b[i] == data.CRL[i] ; 
			}
		}
	public static void Test4()
		{
		data = new KeyInfoX509Data() ; 
		data.AddSubjectKeyId( "SKI0" ) ; 
		data.AddSubjectKeyId( "SKI1" ) ; 
		rv = data.SubjectKeyIds.Count == 2 ; 

		data = new KeyInfoX509Data() ; 
		data.AddSubjectKeyId( new byte[]{1,2,3,4,5,6} ) ; 
		data.AddSubjectKeyId( new byte[]{7,8,9,10,11,12} ) ; 
		rv = data.SubjectKeyIds.Count == 2 ; 		
		}
	public static void Test3()
		{
		cert = TestCert ; 
		data = new KeyInfoX509Data( cert.Export( X509ContentType.Cert ) ) ;
		rv = ((X509Certificate2)data.Certificates[0]).ToString(true) == cert.ToString(true) ; 

		data = new KeyInfoX509Data( cert ) ; 
		rv = ((X509Certificate2)data.Certificates[0]).ToString(true) == cert.ToString(true) ; 
		}
            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;
            }
Beispiel #6
0
        public void InvalidKeyNode1()
        {
            KeyInfoX509Data data1 = new KeyInfoX509Data();

            Assert.Throws <ArgumentNullException>(() => data1.LoadXml(null));
        }
Beispiel #7
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));
        }
Beispiel #8
0
        public void AddCertificate_Null()
        {
            KeyInfoX509Data data = new KeyInfoX509Data();

            Assert.Throws <ArgumentNullException>(() => data.AddCertificate(null));
        }
Beispiel #9
0
        public void AddIssuerSerial_Issuer_Null()
        {
            KeyInfoX509Data data = new KeyInfoX509Data();

            AssertExtensions.Throws <ArgumentException>("issuerName", () => data.AddIssuerSerial(null, "serial"));
        }
Beispiel #10
0
 public void Constructor_X509CertificateByteArray_Null()
 {
     KeyInfoX509Data data = new KeyInfoX509Data((byte[])null);
 }
Beispiel #11
0
        public string FirmarXml(string tramaXml)
        {
            // Vamos a firmar el XML con la ruta del certificado que está como serializado.

            var certificate = new X509Certificate2();

            certificate.Import(Convert.FromBase64String(RutaCertificadoDigital),
                               PasswordCertificado, X509KeyStorageFlags.MachineKeySet);

            var xmlDoc = new XmlDocument();

            string resultado;

            using (var documento = new MemoryStream(Convert.FromBase64String(tramaXml)))
            {
                xmlDoc.PreserveWhitespace = true;
                xmlDoc.Load(documento);
                int tipo;

                if (TipoDocumento == 1 || TipoDocumento == 2 || TipoDocumento == 3 || TipoDocumento == 4)
                {
                    tipo = 1;
                }
                else
                {
                    tipo = 0;
                }

                var nodoExtension = xmlDoc.GetElementsByTagName("ExtensionContent", EspacioNombres.ext)
                                    .Item(tipo);
                if (nodoExtension == null)
                {
                    throw new InvalidOperationException("No se pudo encontrar el nodo ExtensionContent en el XML");
                }
                nodoExtension.RemoveAll();

                // Creamos el objeto SignedXml.
                var signedXml = new SignedXml(xmlDoc)
                {
                    SigningKey = (RSA)certificate.PrivateKey
                };
                signedXml.SigningKey = certificate.PrivateKey;
                var xmlSignature = signedXml.Signature;

                var env = new XmlDsigEnvelopedSignatureTransform();

                var reference = new Reference(string.Empty);
                reference.AddTransform(env);
                xmlSignature.SignedInfo.AddReference(reference);

                var keyInfo  = new KeyInfo();
                var x509Data = new KeyInfoX509Data(certificate);

                x509Data.AddSubjectName(certificate.Subject);

                keyInfo.AddClause(x509Data);
                xmlSignature.KeyInfo = keyInfo;
                xmlSignature.Id      = "SignatureErickOrlando";
                signedXml.ComputeSignature();

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

                nodoExtension.AppendChild(signedXml.GetXml());

                var settings = new XmlWriterSettings()
                {
                    Encoding = Encoding.GetEncoding("ISO-8859-1")
                };

                using (var memDoc = new MemoryStream())
                {
                    using (var writer = XmlWriter.Create(memDoc, settings))
                    {
                        xmlDoc.WriteTo(writer);
                    }

                    resultado = Convert.ToBase64String(memDoc.ToArray());
                }
            }

            return(resultado);
        }
Beispiel #12
0
        public void WriteContentsTo(
            AddressingVersion addressingVersion,
            XmlDictionaryWriter writer)
        {
            if (writer == null)
            {
                throw new ArgumentNullException("writer");
            }
#if MOBILE
            if (addressingVersion == AddressingVersion.None)
            {
                writer.WriteString(Uri.AbsoluteUri);
            }
            else
            {
                writer.WriteStartElement("Address", addressingVersion.Namespace);
                writer.WriteString(Uri.AbsoluteUri);
                writer.WriteEndElement();
            }
#else
            if (addressingVersion == AddressingVersion.None)
            {
                writer.WriteString(Uri.AbsoluteUri);
            }
            else
            {
                writer.WriteStartElement("Address", addressingVersion.Namespace);
                writer.WriteString(Uri.AbsoluteUri);
                writer.WriteEndElement();

                if (Identity == null)
                {
                    return;
                }

                if (Headers != null)
                {
                    foreach (AddressHeader ah in Headers)
                    {
                        ah.WriteAddressHeader(writer);
                    }
                }

                writer.WriteStartElement("Identity", Constants.WsaIdentityUri);

                X509CertificateEndpointIdentity x509 =
                    Identity as X509CertificateEndpointIdentity;
                if (x509 != null)
                {
                    KeyInfo         ki = new KeyInfo();
                    KeyInfoX509Data x  = new KeyInfoX509Data();
                    foreach (X509Certificate2 cert in x509.Certificates)
                    {
                        x.AddCertificate(cert);
                    }
                    ki.AddClause(x);
                    ki.GetXml().WriteTo(writer);
                }
                else
                {
                    DataContractSerializer ds = new DataContractSerializer(Identity.IdentityClaim.GetType());
                    ds.WriteObject(writer, Identity.IdentityClaim);
                }
                writer.WriteEndElement();
            }
#endif
        }
Beispiel #13
0
    static void Asymmetric(string filename)
    {
        string shortName = Path.GetFileName(filename);

        XmlDocument         doc = new XmlDocument();
        XmlTextReader       xtr = new XmlTextReader(GetReader(filename));
        XmlValidatingReader xvr = new XmlValidatingReader(xtr);

        xtr.Normalization      = true;
        doc.PreserveWhitespace = true;
        doc.Load(xvr);

        try {
            SignedXml s = null;
            if (filename.IndexOf("enveloped") >= 0)
            {
                s = new SignedXml(doc);
            }
            else if (filename.IndexOf("signature-big") >= 0)
            {
                s = new SignedXml(doc);
            }
            else
            {
                s = new SignedXml();
            }

            XmlNodeList nodeList = doc.GetElementsByTagName("Signature", "http://www.w3.org/2000/09/xmldsig#");
            s.LoadXml((XmlElement)nodeList [0]);

#if false // wanna dump?
            Console.WriteLine("\n\nFilename : " + fi.Name);
            DumpSignedXml(s);
#endif
            // MS doesn't extract the public key out of the certificates
            // http://www.dotnet247.com/247reference/a.aspx?u=http://www.kbalertz.com/Feedback_320602.aspx
            Mono.Security.X509.X509Certificate mx = null;
            foreach (KeyInfoClause kic in s.KeyInfo)
            {
                if (kic is KeyInfoX509Data)
                {
                    KeyInfoX509Data kix = (kic as KeyInfoX509Data);
                    if ((kix.Certificates != null) && (kix.Certificates.Count > 0))
                    {
                        System.Security.Cryptography.X509Certificates.X509Certificate x509 = (System.Security.Cryptography.X509Certificates.X509Certificate)kix.Certificates [0];
                        byte[] data = x509.GetRawCertData();
                        mx = new Mono.Security.X509.X509Certificate(data);
                    }
                }
            }

            // special cases
            // 1- Merlin's certificate resolution (manual)
            // 2- Phaos (because Fx doesn't support RetrievalMethod
            switch (shortName)
            {
            case "signature-keyname.xml":
                mx = LoadCertificate(GetPath(filename, "lugh.crt"));
                break;

            case "signature-retrievalmethod-rawx509crt.xml":
                mx = LoadCertificate(GetPath(filename, "balor.crt"));
                break;

            case "signature-x509-is.xml":
                mx = LoadCertificate(GetPath(filename, "macha.crt"));
                break;

            case "signature-x509-ski.xml":
                mx = LoadCertificate(GetPath(filename, "nemain.crt"));
                break;

            case "signature-x509-sn.xml":
                mx = LoadCertificate(GetPath(filename, "badb.crt"));
                break;

            // Phaos
            case "signature-big.xml":
            case "signature-rsa-manifest-x509-data-issuer-serial.xml":
            case "signature-rsa-manifest-x509-data-ski.xml":
            case "signature-rsa-manifest-x509-data-subject-name.xml":
            case "signature-rsa-detached-xslt-transform-retrieval-method.xml":
                mx = LoadCertificate(GetPath(filename, "rsa-cert.der"));
                break;

            case "signature-rsa-detached-xslt-transform-bad-retrieval-method.xml":
                mx = LoadCertificate(GetPath(filename, "dsa-ca-cert.der"));
                break;

            default:
                break;
            }

            bool result = false;
            if (mx != null)
            {
                if (mx.RSA != null)
                {
                    result = s.CheckSignature(mx.RSA);
                }
                else if (mx.DSA != null)
                {
                    result = s.CheckSignature(mx.DSA);
                }
            }
            else
            {
                // use a key existing in the document
                result = s.CheckSignature();
            }

            if (result)
            {
                Console.WriteLine("valid " + shortName);
                valid++;
            }
            else
            {
                Console.WriteLine("INVALID {0}", shortName);
                invalid++;
            }
        }
        catch (Exception ex) {
            Console.WriteLine("EXCEPTION " + shortName + " " + ex);
            error++;
        }
    }
Beispiel #14
0
    // <Snippet2>
    // Sign an XML file and save the signature in a new file.
    public static void SignXmlFile(string FileName, string SignedFileName, string SubjectName)
    {
        if (null == FileName)
        {
            throw new ArgumentNullException("FileName");
        }
        if (null == SignedFileName)
        {
            throw new ArgumentNullException("SignedFileName");
        }
        if (null == SubjectName)
        {
            throw new ArgumentNullException("SubjectName");
        }

        // Load the certificate from the certificate store.
        X509Certificate2 cert = GetCertificateBySubject(SubjectName);

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

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

        // Add the key to the SignedXml document.
        signedXml.SigningKey = cert.PrivateKey;

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

        reference.Uri = "";

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

        reference.AddTransform(env);

        // 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.
        // Create an X509IssuerSerial object and add it to the
        // KeyInfoX509Data object.

        KeyInfoX509Data kdata = new KeyInfoX509Data(cert);

        X509IssuerSerial xserial;

        xserial.IssuerName   = cert.IssuerName.ToString();
        xserial.SerialNumber = cert.SerialNumber;

        kdata.AddIssuerSerial(xserial.IssuerName, xserial.SerialNumber);

        keyInfo.AddClause(kdata);

        // Add the KeyInfo object to the SignedXml object.
        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();

        // Append the element to the XML document.
        doc.DocumentElement.AppendChild(doc.ImportNode(xmlDigitalSignature, true));

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

        // Save the signed XML document to a file specified
        // using the passed string.
        using (XmlTextWriter xmltw = new XmlTextWriter(SignedFileName, new UTF8Encoding(false)))
        {
            doc.WriteTo(xmltw);
            xmltw.Close();
        }
    }
	static void Test6() //Xml roundtrip
		{
		int i = 0 ; 
		data = new KeyInfoX509Data() ; 

		//add certs
		data.AddCertificate( TestCert ) ; 
		data.AddCertificate( EndCert ) ; 

		//add subject name
		data.AddSubjectName( TestCert.SubjectName.Name ) ; 
		data.AddSubjectName( EndCert.SubjectName.Name ) ; 
		
		//add subject keys
		data.AddSubjectKeyId( new byte[]{1,2,3,4,5,6} ) ; 
		data.AddSubjectKeyId( new byte[]{7,8,9,10,11,12} ) ; 

		//add issuer serials
		data.AddIssuerSerial( TestCert.IssuerName.Name , TestCert.SerialNumber ) ; 
		data.AddIssuerSerial( EndCert.IssuerName.Name , EndCert.SerialNumber ) ; 

		//add the crl
		byte[] b = { 100, 101 , 102 , 104 } ; 
		data.CRL = b ;

		KeyInfoX509Data rt = new KeyInfoX509Data() ; 
		rt.LoadXml( data.GetXml() ) ; 
		for( i = 0 ; i < rt.CRL.Length ; i++ ) 
			{
			rv = rt.CRL[i] == data.CRL[i] ; 
			}

		for( i = 0 ; i < rt.Certificates.Count ; i++ ) 
			{
			rv = rt.Certificates[i].ToString() == data.Certificates[i].ToString() ; 
			}
		for( i = 0 ; i < rt.SubjectKeyIds.Count ; i++ ) 
			{
			rv = rt.SubjectKeyIds[i].ToString() == data.SubjectKeyIds[i].ToString() ; 
			}
		for( i = 0 ; i < rt.SubjectNames.Count ; i++ ) 
			{
			rv = rt.SubjectNames[i].ToString() == data.SubjectNames[i].ToString() ;
			}
		}
Beispiel #16
0
        public void AddIssuerSerial_Invalid_Serial()
        {
            KeyInfoX509Data data = new KeyInfoX509Data();

            AssertExtensions.Throws <ArgumentException>("serialNumber", () => data.AddIssuerSerial("issuer", "NotANumber"));
        }
	static void Test7() //negative LoadXml test
		{
		try
			{
			data = new KeyInfoX509Data() ; 
			data.LoadXml( data.GetXml() ) ; 
			rv = false ; 
			}
		catch( CryptographicException ce )
			{
			Console.WriteLine( ce.ToString() ) ; 
			rv = true ; 
			}
		catch( Exception e )
			{
			Console.WriteLine( e.ToString() ) ; 
			rv = false ; 
			}

		try
			{
			data = new KeyInfoX509Data() ; 
			data.LoadXml( null ) ; 
			rv = false ; 
			}
		catch
			{
			rv = true ; 
			}			
		}	
Beispiel #18
0
        public void AddSubjectKeyId_String_Null()
        {
            KeyInfoX509Data data1 = new KeyInfoX509Data();

            Assert.Throws <NullReferenceException>(() => data1.AddSubjectKeyId((string)null));
        }
	public static void Test2()
		{
		try
			{
			data = new KeyInfoX509Data( new X509Certificate2() , X509IncludeOption.WholeChain ) ;
			rv = false ; 
			}
		catch( Exception e ) 
			{
			Console.WriteLine( e.ToString() ) ; 
			rv = true ; 
			}
		}
Beispiel #20
0
        public async Task <FirmadoResponse> FirmarXml(FirmadoRequest request)
        {
            var task = Task.Factory.StartNew(() =>
            {
                var response = new FirmadoResponse();

                var certificate = new X509Certificate2();
                certificate.Import(Convert.FromBase64String(request.CertificadoDigital),
                                   request.PasswordCertificado, X509KeyStorageFlags.MachineKeySet);

                var xmlDoc = new XmlDocument();

                string resultado;

                var betterBytes = Encoding.Convert(Encoding.UTF8,
                                                   Encoding.GetEncoding(Formatos.EncodingIso),
                                                   Convert.FromBase64String(request.TramaXmlSinFirma));

                using (var documento = new MemoryStream(betterBytes))
                {
                    xmlDoc.PreserveWhitespace = false;
                    xmlDoc.Load(documento);

                    var indiceNodo = request.UnSoloNodoExtension ? 0 : 1;

                    var nodoExtension = xmlDoc.GetElementsByTagName("ExtensionContent", EspacioNombres.ext)
                                        .Item(indiceNodo);
                    if (nodoExtension == null)
                    {
                        throw new InvalidOperationException("No se pudo encontrar el nodo ExtensionContent en el XML");
                    }
                    nodoExtension.RemoveAll();

                    // Creamos el objeto SignedXml.
                    var signedXml = new SignedXml(xmlDoc)
                    {
                        SigningKey = certificate.PrivateKey
                    };
                    var xmlSignature = signedXml.Signature;

                    var env = new XmlDsigEnvelopedSignatureTransform();

                    var reference = new Reference(string.Empty);
                    reference.AddTransform(env);
                    xmlSignature.SignedInfo.AddReference(reference);

                    var keyInfo  = new KeyInfo();
                    var x509Data = new KeyInfoX509Data(certificate);

                    x509Data.AddSubjectName(certificate.Subject);

                    keyInfo.AddClause(x509Data);
                    xmlSignature.KeyInfo = keyInfo;
                    xmlSignature.Id      = "SignOpenInvoicePeru";
                    signedXml.ComputeSignature();

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

                    nodoExtension.AppendChild(signedXml.GetXml());

                    using (var memDoc = new MemoryStream())
                    {
                        using (var writer = XmlWriter.Create(memDoc,
                                                             new XmlWriterSettings {
                            Encoding = Encoding.GetEncoding(Formatos.EncodingIso)
                        }))
                        {
                            xmlDoc.WriteTo(writer);
                        }

                        resultado = Convert.ToBase64String(memDoc.ToArray());
                    }
                }
                response.TramaXmlFirmado = resultado;

                return(response);
            });

            return(await task);
        }