Example #1
0
        private static X509Certificate LoadCertificate(string path, string password, out PrivateKey privateKey, out Provider provider)
        {
            X509Certificate certificate = null;

            provider   = null;
            privateKey = null;

            //Cargar certificado de fichero PFX
            KeyStore ks = KeyStore.getInstance("PKCS12");

            ks.load(new BufferedInputStream(new FileInputStream(path)), password.ToCharArray());
            IPKStoreManager storeManager = new KSStore(ks, new PassStoreKS(password));
            var             certificates = storeManager.getSignCertificates();

            //Si encontramos el certificado...
            if (certificates.size() == 1)
            {
                certificate = (X509Certificate)certificates.get(0);

                // Obtención de la clave privada asociada al certificado
                privateKey = storeManager.getPrivateKey(certificate);

                // Obtención del provider encargado de las labores criptográficas
                provider = storeManager.getProvider(certificate);
            }

            return(certificate);
        }
Example #2
0
        public static void Firmar(string origen, string destino, string rutaFirma, string contraseniaFirma)
        {
            PrivateKey      privateKey;
            Provider        provider;
            X509Certificate certificate = LoadCertificate(rutaFirma, contraseniaFirma, out privateKey, out provider);

            //Si encontramos el certificado...
            if (certificate != null)
            {
                //Política de firma (Con las librerías JAVA, esto se define en tiempo de ejecución)
                TrustFactory.instance             = TrustExtendFactory.newInstance();
                TrustFactory.truster              = MyPropsTruster.getInstance();
                PoliciesManager.POLICY_SIGN       = new Facturae31Manager();
                PoliciesManager.POLICY_VALIDATION = new Facturae31Manager();
                TrustFactory.instance             = TrustFactory.newInstance();
                TrustFactory.truster              = PropsTruster.getInstance();
                PoliciesManager.POLICY_SIGN       = new Facturae31Manager();
                PoliciesManager.POLICY_VALIDATION = new Facturae31Manager();
                DataToSign dataToSign = new DataToSign();
                dataToSign.setXadesFormat(EnumFormatoFirma.XAdES_BES);
                dataToSign.setEsquema(XAdESSchemas.XAdES_132);
                dataToSign.setXMLEncoding("UTF-8");
                dataToSign.setEnveloped(true);
                dataToSign.setParentSignNode("comprobante");
                dataToSign.addObject(new ObjectToSign(new InternObjectToSign("comprobante"), "contenido comprobante", null, "text/xml", null));
                dataToSign.setDocument(Erp90w(origen));
                object[]         objArray         = (new FirmaXML()).signFile(certificate, dataToSign, privateKey, provider);
                FileOutputStream fileOutputStream = new FileOutputStream(destino);
                UtilidadTratarNodo.saveDocumentToOutputStream((Document)objArray[0], fileOutputStream, true);
                fileOutputStream.close();
            }
        }
Example #3
0
 public override bool displayCertificates(X509Certificate[] certificates)
 {
     //todo did not find a way to show the chain in the case of self signed certs
     X509Certificate2 cert = ConvertCertificate(certificates[0]);
     X509Certificate2UI.DisplayCertificate(cert);
     return true;
 }
Example #4
0
 void org.apache.http.conn.ssl.X509HostnameVerifier.verify(java.lang.String arg0, java.security.cert.X509Certificate arg1)
 {
     global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
     if (!IsClrObject)
     {
         @__env.CallVoidMethod(this.JvmHandle, global::org.apache.http.conn.ssl.X509HostnameVerifier_._verify16436, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
     }
     else
     {
         @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::org.apache.http.conn.ssl.X509HostnameVerifier_.staticClass, global::org.apache.http.conn.ssl.X509HostnameVerifier_._verify16436, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
     }
 }
Example #5
0
 public SslError(int arg0, java.security.cert.X509Certificate arg1)  : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
 {
     global::MonoJavaBridge.JNIEnv         @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
     global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.net.http.SslError.staticClass, global::android.net.http.SslError._SslError5430, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
     Init(@__env, handle);
 }
Example #6
0
        /// <summary>
        // RFC2818 - HTTP Over TLS, Section 3.1
        // http://www.ietf.org/rfc/rfc2818.txt
        //
        // 1.  if present MUST use subjectAltName dNSName as identity
        // 1.1.    if multiples entries a match of any one is acceptable
        // 1.2.    wildcard * is acceptable
        // 2.  URI may be an IP address -> subjectAltName.iPAddress
        // 2.1.    exact match is required
        // 3.  Use of the most specific Common Name (CN=) in the Subject
        // 3.1    Existing practice but DEPRECATED
        /// </summary>
        /// <param name="javaCert"></param>
        /// <param name="cert"></param>
        /// <param name="targetHost"></param>
        /// <returns></returns>
        ///todo We should get rid of the java certificate parameter. Means to find an easy way to get the subjectAltNames (see http://www.java2s.com/Open-Source/CSharp/2.6.4-mono-.net-core/System.Net/System/Net/ServicePointManager.cs.htm)
        public static bool CheckServerIdentity(X509Certificate javaCert,
                                               X509Certificate2 cert, string targetHost)
        {
            try
            {
                /*
                 * SubjectAltName ::= GeneralNames
                 *
                 * GeneralNames :: = SEQUENCE SIZE (1..MAX) OF GeneralName
                 *
                 * GeneralName ::= CHOICE {
                 * otherName                       [0]     OtherName,
                 * rfc822Name                      [1]     IA5String,
                 * dNSName                         [2]     IA5String,
                 * x400Address                     [3]     ORAddress,
                 * directoryName                   [4]     Name,
                 * ediPartyName                    [5]     EDIPartyName,
                 * uniformResourceIdentifier       [6]     IA5String,
                 * iPAddress                       [7]     OCTET STRING,
                 * registeredID                    [8]     OBJECT IDENTIFIER}
                 *
                 * SubjectAltName is of form \"rfc822Name=<email>,
                 * dNSName=<host name>, uri=<http://host.com/>,
                 * ipaddress=<address>, guid=<globally unique id>
                 *
                 */

                java.util.Collection ext = javaCert.getSubjectAlternativeNames();
                // subjectAltName
                if (null != ext && ext.size() > 0)
                {
                    for (Iterator i = ext.iterator(); i.hasNext();)
                    {
                        List    item = (List)i.next();
                        Integer type = (Integer)item.get(0);
                        switch (type.intValue())
                        {
                        case 0:
                            continue;     // SubjectAltName of type OtherName not

                        case 1:
                            continue;     // rfc822Name

                        case 2:
                            if (Match(targetHost, (String)item.get(1)))      //dNSName
                            {
                                return(true);
                            }
                            break;

                        case 3:
                            continue;     // x400Address

                        case 4:
                            continue;     // directoryName

                        case 5:
                            continue;     // ediPartyName

                        case 6:
                            //todo shouldn't we handle uri as well? check spec.
                            continue;     // uri

                        case 7:
                            if (targetHost.Equals((String)item.get(1)))      // ipaddress, exact match required
                            {
                                return(true);
                            }
                            break;

                        default:
                            continue;
                        }
                    }
                }
                // Common Name (CN=)
                return(Match(GetCommonName(cert), targetHost));
            }
            catch (Exception e)
            {
                Log.error("ERROR processing certificate: {0}", e);
                return(false);
            }
        }
Example #7
0
 public static X509Certificate2 ConvertCertificate(X509Certificate certificate)
 {
     return(new X509Certificate2(certificate.getEncoded()));
 }
Example #8
0
 public static X509Certificate2 ConvertCertificate(X509Certificate certificate)
 {
     return new X509Certificate2(certificate.getEncoded());
 }
Example #9
0
        /// <summary>
        // RFC2818 - HTTP Over TLS, Section 3.1
        // http://www.ietf.org/rfc/rfc2818.txt
        //
        // 1.  if present MUST use subjectAltName dNSName as identity
        // 1.1.    if multiples entries a match of any one is acceptable
        // 1.2.    wildcard * is acceptable
        // 2.  URI may be an IP address -> subjectAltName.iPAddress
        // 2.1.    exact match is required
        // 3.  Use of the most specific Common Name (CN=) in the Subject
        // 3.1    Existing practice but DEPRECATED
        /// </summary>
        /// <param name="javaCert"></param>
        /// <param name="cert"></param>
        /// <param name="targetHost"></param>
        /// <returns></returns>
        ///todo We should get rid of the java certificate parameter. Means to find an easy way to get the subjectAltNames (see http://www.java2s.com/Open-Source/CSharp/2.6.4-mono-.net-core/System.Net/System/Net/ServicePointManager.cs.htm)        
        public static bool CheckServerIdentity(X509Certificate javaCert,
            X509Certificate2 cert, string targetHost)
        {
            try
            {
                /*
                 SubjectAltName ::= GeneralNames

                 GeneralNames :: = SEQUENCE SIZE (1..MAX) OF GeneralName

                 GeneralName ::= CHOICE {
                  otherName                       [0]     OtherName,
                  rfc822Name                      [1]     IA5String,
                  dNSName                         [2]     IA5String,
                  x400Address                     [3]     ORAddress,
                  directoryName                   [4]     Name,
                  ediPartyName                    [5]     EDIPartyName,
                  uniformResourceIdentifier       [6]     IA5String,
                  iPAddress                       [7]     OCTET STRING,
                  registeredID                    [8]     OBJECT IDENTIFIER}

                 SubjectAltName is of form \"rfc822Name=<email>,
                 dNSName=<host name>, uri=<http://host.com/>,
                 ipaddress=<address>, guid=<globally unique id>

                */

                Collection ext = javaCert.getSubjectAlternativeNames();
                // subjectAltName
                if (null != ext && ext.size() > 0)
                {
                    for (Iterator i = ext.iterator(); i.hasNext();)
                    {
                        List item = (List) i.next();
                        Integer type = (Integer) item.get(0);
                        switch (type.intValue())
                        {
                            case 0:
                                continue; // SubjectAltName of type OtherName not
                            case 1:
                                continue; // rfc822Name

                            case 2:
                                if (Match(targetHost, (String) item.get(1))) //dNSName
                                {
                                    return true;
                                }
                                break;
                            case 3:
                                continue; // x400Address
                            case 4:
                                continue; // directoryName
                            case 5:
                                continue; // ediPartyName
                            case 6:
                                //todo shouldn't we handle uri as well? check spec.
                                continue; // uri
                            case 7:
                                if (targetHost.Equals((String) item.get(1))) // ipaddress, exact match required
                                {
                                    return true;
                                }
                                break;
                            default:
                                continue;
                        }
                    }
                }
                // Common Name (CN=)
                return Match(GetCommonName(cert), targetHost);
            }
            catch (Exception e)
            {
                Log.error("ERROR processing certificate: {0}", e);
                return false;
            }
        }
Example #10
-1
        public override bool isTrusted(String hostName, X509Certificate[] certs)
        {
            X509Certificate2 serverCert = ConvertCertificate(certs[0]);
            X509Chain chain = new X509Chain();
            //todo Online revocation check. Preference.
            chain.ChainPolicy.RevocationMode = X509RevocationMode.Offline; // | X509RevocationMode.Online
            chain.ChainPolicy.UrlRetrievalTimeout = new TimeSpan(0, 0, 0, 10); // set timeout to 10 seconds
            chain.ChainPolicy.VerificationFlags = X509VerificationFlags.NoFlag;

            for (int index = 1; index < certs.Length; index++)
            {
                chain.ChainPolicy.ExtraStore.Add(ConvertCertificate(certs[index]));
            }
            chain.Build(serverCert);

            bool isException = CheckForException(hostName, serverCert);
            if (isException)
            {
                // Exceptions always have precendence
                return true;
            }

            string errorFromChainStatus = GetErrorFromChainStatus(chain, hostName);
            bool certError = null != errorFromChainStatus;
            bool hostnameMismatch = !HostnameVerifier.CheckServerIdentity(certs[0], serverCert, hostName);

            // check if host name matches
            if (null == errorFromChainStatus && hostnameMismatch)
            {
                errorFromChainStatus = Locale.localizedString(
                    "The certificate for this server is invalid. You might be connecting to a server that is pretending to be “%@” which could put your confidential information at risk. Would you like to connect to the server anyway?",
                    "Keychain").Replace("%@", hostName);
            }

            if (null != errorFromChainStatus)
            {
                while (true)
                {
                    TaskDialog d = new TaskDialog();
                    DialogResult r =
                        d.ShowCommandBox(Locale.localizedString("This certificate is not valid", "Keychain"),
                                         Locale.localizedString("This certificate is not valid", "Keychain"),
                                         errorFromChainStatus,
                                         null,
                                         null,
                                         Locale.localizedString("Always Trust", "Keychain"),
                                         String.Format("{0}|{1}|{2}",
                                                       Locale.localizedString("Continue", "Credentials"),
                                                       Locale.localizedString("Disconnect"),
                                                       Locale.localizedString("Show Certificate", "Keychain")),
                                         false,
                                         SysIcons.Warning, SysIcons.Information);
                    if (r == DialogResult.OK)
                    {
                        if (d.CommandButtonResult == 0)
                        {
                            if (d.VerificationChecked)
                            {
                                if (certError)
                                {
                                    //todo can we use the Trusted People and Third Party Certificate Authority Store? Currently X509Chain is the problem.
                                    AddCertificate(serverCert, StoreName.Root);
                                }
                                Preferences.instance().setProperty(hostName + ".certificate.accept",
                                                                   serverCert.SubjectName.Name);
                            }
                            return true;
                        }
                        if (d.CommandButtonResult == 1)
                        {
                            return false;
                        }
                        if (d.CommandButtonResult == 2)
                        {
                            X509Certificate2UI.DisplayCertificate(serverCert);
                        }
                    }
                }
            }
            return true;
        }