public DifiGatewaySettings CreateGatewaySettings()
 {
     var service = new System.Security.Cryptography.X509Certificates.X509Certificate2("Certificates\\idporten-ver2.difi.no-v2.crt", "changeit");
     var client = new System.Security.Cryptography.X509Certificates.X509Certificate2("Certificates\\WcfClient.pfx", "changeit");
     var settings = new DifiGatewaySettings(client, service);
     return settings;
 }
Beispiel #2
0
        static void Main(string[] args)
        {
            System.Security.Cryptography.X509Certificates.X509Certificate2 cert = null;

            if (System.IO.File.Exists("cert.pfx") && System.IO.File.Exists("pw.txt"))
                cert = new System.Security.Cryptography.X509Certificates.X509Certificate2("cert.pfx", System.IO.File.ReadAllText("pw.txt"));

            //serv = new vProto.BaseServer(5665, cert);
            if (cert == null)
                serv = new vProto.Protocols.TCP.Server(5665);
            else
                serv = new vProto.Protocols.TCP.SSL.Server(5665, cert);

            serv.ClientConnected += serv_ClientConnected;
            serv.ClientConnectionFailed += serv_ClientConnectionFailed;
            serv.ClientDisconnected += serv_ClientDisconnected;

            serv.Start();

            var updater = new Timer(new TimerCallback(delegate(object state)
            {
                var peers = serv.ListAllClientIDs();

                string peerStr = string.Empty;

                if (peers == null)
                {
                    peerStr = "No clients!?";
                }
                else
                {
                    peerStr = "#" + peers.Count;

                    if (peers.Count < 15)
                        for (int i = 0; i < peers.Count; i++)
                            if (i == 0)
                                peerStr += ": " + peers[i];
                            else
                                peerStr += ", " + peers[i];
                }

                Console.Title = string.Format("Speed: In {0}; Out {1}; Clients: {2}", serv.IncommingSpeed, serv.OutgoingSpeed, peerStr);

                //for (int i = 0; i < peers.Count; i++)
                //    serv[i].SendData(Encoding.UTF8.GetBytes(Console.Title));

            }), null, 1000, 1000);

            Console.ReadLine();

            serv.Dispose();

            updater.Dispose();
        }
 private string GetSelloFromPFX(string cadenaOriginal) {
     System.Security.Cryptography.SHA1CryptoServiceProvider sha1 = new System.Security.Cryptography.SHA1CryptoServiceProvider();
     System.Security.Cryptography.X509Certificates.X509Certificate2 cert = new System.Security.Cryptography.X509Certificates.X509Certificate2(this.PFXArchivo,
          this.PFXContrasena, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags.MachineKeySet);
     System.Security.Cryptography.RSACryptoServiceProvider rsaCryptoIPT = (System.Security.Cryptography.RSACryptoServiceProvider)cert.PrivateKey;
     System.Text.UTF8Encoding encoder = new System.Text.UTF8Encoding();
     byte[] binData = encoder.GetBytes(cadenaOriginal);
     byte[] binSignature = rsaCryptoIPT.SignData(binData, sha1);
     string sello = Convert.ToBase64String(binSignature);
     return sello;
 }
Beispiel #4
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            var certificate = new System.Security.Cryptography.X509Certificates.X509Certificate2("MyCertificate.pfx", "CertPass");
            app.UseKestrelHttps(certificate);

            app.UseIISPlatformHandler();

            app.UseStaticFiles();

            app.UseMvc();
        }
        private static HttpWebRequest CreateRequest(string url, string managementCertificate)
        {
            var cert = new System.Security.Cryptography.X509Certificates.X509Certificate2(Convert.FromBase64String(managementCertificate));
            var request = (HttpWebRequest)HttpWebRequest.CreateDefault(new Uri(url));

            request.Headers.Add("x-ms-version", "2013-11-01");
            request.Method = "GET";
            request.ContentType = "application/xml";

            // Attach the certificate to the request.
            request.ClientCertificates.Add(cert);

            return request;
        }
Beispiel #6
0
        static void Main(string[] args)
        {
            var pk =  PassKit.Parse(System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "costco.pkpass"));

            Console.WriteLine(pk.Barcode.Message);

            var cert = new System.Security.Cryptography.X509Certificates.X509Certificate2(
                Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "testpass.p12"), "password");

            var outFile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "testoutput.pkpass");

            try { File.Delete(outFile); } catch { }

            pk.Write(outFile, cert);

            Console.WriteLine("OK");
        }
        public static bool IsSignedBy(this X509Certificate thisCertificate, X509Certificate signerCertificate)
        {
            X509Certificate2 c = new X509Certificate2(thisCertificate.GetTbsCertificate());
            X509Certificate2 i = new X509Certificate2(signerCertificate.GetTbsCertificate());
            X509Certificate2 c2 = new X509Certificate2(@"c:\temp\der.cer");
            X509Certificate2 i2 = new X509Certificate2(@"c:\temp\cader.cer");
            /*byte[] pvSubject = thisCertificate.GetTbsCertificate();
            byte[] pvIssuer = signerCertificate.GetTbsCertificate();
            */
            System.Text.Encoding.ASCII.GetString(c.RawData);
            IntPtr pvSubject = c.Handle;
            IntPtr pvIssuer = i.Handle;
            int res = SspiProvider.CryptVerifyCertificateSignatureEx(IntPtr.Zero, X509_ASN_ENCODING,
                                                           CRYPT_VERIFY_CERT_SIGN_SUBJECT_CERT, pvSubject,
                                                           CRYPT_VERIFY_CERT_SIGN_ISSUER_CERT, pvIssuer, 0,
                                                           IntPtr.Zero);
            Marshal.GetLastWin32Error();
            CmsSigner signer = new CmsSigner(i);
            SignedCms signedMessage = new SignedCms();
            // deserialize PKCS #7 byte array

            signedMessage.Decode(thisCertificate.GetTbsCertificate());
            Log.Write("Veryfy old");
            Log.Write("EndVeryfy old");
            Log.Write("Get signer's public key");
            var publicKey = signerCertificate.GetPublicKey();
            Log.Write("Got signer's public key");
            try
            {
                Log.Write("Veryfy signature");
                //TODO: log errors
                thisCertificate.Verify(publicKey);
                Log.Write("Verified");
            }
            catch (CertificateException)
            {
                return false;
            }
            catch (InvalidKeyException)
            {
                return false;
            }
            return true;
        }
Beispiel #8
0
 public string Format(string format, object arg, System.IFormatProvider formatProvider)
 {
     var str = string.Empty;
     System.Security.Cryptography.X509Certificates.X509Certificate2 x509Certificate = null;
     var flag = false;
     if (arg is System.Security.Cryptography.X509Certificates.X509Certificate2)
         x509Certificate = arg as System.Security.Cryptography.X509Certificates.X509Certificate2;
     else if (arg is System.Security.Cryptography.X509Certificates.X509Certificate) {
         try {
             x509Certificate = new System.Security.Cryptography.X509Certificates.X509Certificate2((System.Security.Cryptography.X509Certificates.X509Certificate) arg);
         } catch (System.Security.Cryptography.CryptographicException ex) {
             flag = true;
             str = string.Format("Error formatting certificate: {0}", ex.Message);
         }
     }
     if (x509Certificate != null)
         str = ExFormatProvider.FormatX509Certificate(x509Certificate, format, defaultFormatProvider);
     else if (!flag)
         str = !(arg is System.IFormattable) ? (arg == null ? string.Empty : arg.ToString()) : ((System.IFormattable) arg).ToString(format, defaultFormatProvider);
     return str;
 }
        // https://sites.google.com/a/jsc-solutions.net/backlog/knowledge-base/2015/20151102
        // set by?
        // Z:\jsc.svn\core\ScriptCoreLib.Ultra.Library\ScriptCoreLib.Ultra.Library\Extensions\TcpListenerExtensions.cs

        public static void Invoke(InternalGlobal g)
        {
            // did we ask the user for PIN ?


            var path = new FileInfo("ClientCertificate.crt");
            if (path.Exists)
            {
                try
                {
                    Console.WriteLine("enter InternalCassiniClientCertificateLoader "
                        + new { path.FullName }
                        //+ new { Environment.CurrentDirectory, typeof(InternalCassiniClientCertificateLoader).Assembly.Location }
                    );

                    // 'System.Security.Cryptography.X509Certificates.X509Certificate' to type 'System.Security.Cryptography.X509Certificates.X509Certificate2'.


                    var crt = new System.Security.Cryptography.X509Certificates.X509Certificate2();

                    crt.Import(File.ReadAllBytes(path.FullName));

                    g.ClientCertificate = crt;

                }
                catch (Exception err)
                {
                    Console.WriteLine(new { err });

                    throw;
                }
                finally
                {
                    File.Delete(path.FullName);
                }
            }

        }
Beispiel #10
0
 public static Microsoft.AspNetCore.Server.Kestrel.Core.ListenOptions UseHttps(this Microsoft.AspNetCore.Server.Kestrel.Core.ListenOptions listenOptions, System.Security.Cryptography.X509Certificates.X509Certificate2 serverCertificate, System.Action <Microsoft.AspNetCore.Server.Kestrel.Https.HttpsConnectionAdapterOptions> configureOptions)
 {
     throw null;
 }
        /// <summary>
        /// 
        /// </summary>
        /// <remarks>Based on <see cref="http://www.fkollmann.de/v2/post/Creating-certificates-using-BouncyCastle.aspx"/></remarks>
        /// <param name="subjectName"></param>
        /// <returns></returns>
        public static void z_dep_GenerateCertificate(string subjectName, long serialNumber, DateTime expireOn, System.Security.Cryptography.X509Certificates.X509Certificate2 issuingCertificate, out string thumbprint, out string pemPrivateKey, out string pemPublicCert, out byte[] publicCert, out byte[] pkcs12Data, out string password)
        {

            AsymmetricKeyParameter caPrivateKey;
            var caCert = ReadCertificateFromX509Certificate2(issuingCertificate, out caPrivateKey);

            //var caAuth = new AuthorityKeyIdentifierStructure(caCert);
            //var authKeyId = new AuthorityKeyIdentifier(caAuth.GetKeyIdentifier());

            // ---------------------------

            // Generating Random Numbers
            var randomGenerator = new CryptoApiRandomGenerator();
            var random = new SecureRandom(randomGenerator);

            var gen = new X509V3CertificateGenerator();

            // var certName = new X509Name("CN=" + subjectName);

            var list = new Dictionary<string, string>();
            AddItems(list, "CN", subjectName);
            AddItems(list, "O", "CompliaShield");
            AddItems(list, "OU", "CompliaShield");
            //var simpleCertName = GetItemString(list);
            //var certNameLight = new X509Name(simpleCertName);

            list.Add("L", "Boulder");
            list.Add("ST", "Colorado");
            list.Add("C", "US");
            var subjectFull = GetItemString(list);
            var certName = new X509Name(subjectFull);


            BigInteger serialNo;
            if (serialNumber == 0)
            {
                serialNo = BigInteger.ProbablePrime(120, random);
            }
            else
            {
                serialNo = BigInteger.ValueOf(serialNumber);
            }
            gen.SetSerialNumber(serialNo);
            gen.SetSubjectDN(certName);

            gen.SetIssuerDN(caCert.IssuerDN);

            var issuerPublicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(caCert.GetPublicKey());
            var issuerGeneralNames = new GeneralNames(new GeneralName(caCert.IssuerDN));
            var issuerSerialNumber = caCert.SerialNumber;

            var authorityKeyIdentifier = new AuthorityKeyIdentifier(issuerPublicKeyInfo, issuerGeneralNames, issuerSerialNumber);
            gen.AddExtension(X509Extensions.AuthorityKeyIdentifier.Id, true, authorityKeyIdentifier);

            // gen.SetIssuerUniqueID(caCert.IssuerUniqueID.GetBytes())

            gen.SetNotAfter(expireOn);
            gen.SetNotBefore(DateTime.Now.AddHours(-2));
            gen.SetSignatureAlgorithm("SHA256WithRSA"); //("MD5WithRSA");

            var kpgen = new RsaKeyPairGenerator();
            kpgen.Init(new KeyGenerationParameters(random, 2048)); // new SecureRandom(new CryptoApiRandomGenerator()), 2048));
            var subjectKeyPair = kpgen.GenerateKeyPair();
            gen.SetPublicKey(subjectKeyPair.Public);

            gen.AddExtension(
                X509Extensions.ExtendedKeyUsage.Id,
                false,
                new ExtendedKeyUsage(new KeyPurposeID[] { KeyPurposeID.IdKPClientAuth, KeyPurposeID.IdKPServerAuth, KeyPurposeID.IdKPCodeSigning }));

            //1.3.6.1.5.5.7.3.1 = server authentication
            //1.3.6.1.5.5.7.3.2 = client authentication
            //1.3.6.1.5.5.7.3.3 = code signing

            var certificate = gen.Generate(caPrivateKey);

            PrivateKeyInfo info = PrivateKeyInfoFactory.CreatePrivateKeyInfo(subjectKeyPair.Private);

            // merge into X509Certificate2
            var x509 = new System.Security.Cryptography.X509Certificates.X509Certificate2(certificate.GetEncoded());
            var seq = (Asn1Sequence)Asn1Object.FromByteArray(info.PrivateKey.GetDerEncoded());
            if (seq.Count != 9)
            {
                throw new PemException("Malformed sequence in RSA private key.");
            }

            var rsa = new RsaPrivateKeyStructure(seq);
            RsaPrivateCrtKeyParameters rsaparams = new RsaPrivateCrtKeyParameters(
                rsa.Modulus, rsa.PublicExponent, rsa.PrivateExponent, rsa.Prime1, rsa.Prime2, rsa.Exponent1, rsa.Exponent2, rsa.Coefficient);

            //-------------

            //RsaPrivateCrtKeyParameters rsaparams = (RsaPrivateCrtKeyParameters)subjectKeyPair.Private;
            RSAParameters rsaParameters = DotNetUtilities.ToRSAParameters(rsaparams);
            CspParameters cspParameters = new CspParameters();
            cspParameters.KeyContainerName = Guid.NewGuid().ToString(); // "MyKeyContainer";
            RSACryptoServiceProvider rsaKey = new RSACryptoServiceProvider(2048, cspParameters);
            rsaKey.ImportParameters(rsaParameters);

            // ------------

            x509.PrivateKey = rsaKey; // DotNetUtilities.ToRSA(rsaparams);

            // Generating Random Numbers
            var chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-()#$%^&@+=!{}[]*.,";
            var rnd = new Random();

            password = new string(
                Enumerable.Repeat(chars, 32)
                          .Select(s => s[rnd.Next(s.Length)])
                          .ToArray());
            thumbprint = x509.Thumbprint.ToLower();
            publicCert = x509.Export(System.Security.Cryptography.X509Certificates.X509ContentType.Cert);

            var privateKeyPem = new StringBuilder();
            var privateKeyPemWriter = new PemWriter(new StringWriter(privateKeyPem));
            privateKeyPemWriter.WriteObject(certificate);
            privateKeyPemWriter.WriteObject(subjectKeyPair.Private);
            privateKeyPemWriter.Writer.Flush();
            pemPrivateKey = privateKeyPem.ToString();

            var publicKeyPem = new StringBuilder();
            var utf8WithoutBom = new System.Text.UTF8Encoding(false);
            var publicKeyPemWriter = new PemWriter(new StringWriterWithEncoding(publicKeyPem, utf8WithoutBom));
            publicKeyPemWriter.WriteObject(certificate);
            publicKeyPemWriter.Writer.Flush();
            pemPublicCert = publicKeyPem.ToString();
            pemPublicCert = pemPublicCert.Replace(Environment.NewLine, "\n"); //only use newline and not returns

            pkcs12Data = x509.Export(System.Security.Cryptography.X509Certificates.X509ContentType.Pfx, password);

        }
Beispiel #12
0
        // Only the ctor should be calling with isAuthority = true
        // if isAuthority, value for isMachineCert doesn't matter
        private X509CertificateContainer CreateCertificate(bool isAuthority, bool isMachineCert, X509Certificate signingCertificate, CertificateCreationSettings certificateCreationSettings)
        {
            if (certificateCreationSettings == null)
            {
                if (isAuthority)
                {
                    certificateCreationSettings = new CertificateCreationSettings();
                }
                else
                {
                    throw new Exception("Parameter certificateCreationSettings cannot be null when isAuthority is false");
                }
            }

            // Set to default cert creation settings if not set
            if (certificateCreationSettings.ValidityNotBefore == default(DateTime))
            {
                certificateCreationSettings.ValidityNotBefore = _defaultValidityNotBefore;
            }
            if (certificateCreationSettings.ValidityNotAfter == default(DateTime))
            {
                certificateCreationSettings.ValidityNotAfter = _defaultValidityNotAfter;
            }

            string[] subjects = certificateCreationSettings.Subjects;
            if (!isAuthority ^ (signingCertificate != null))
            {
                throw new ArgumentException("Either isAuthority == true or signingCertificate is not null");
            }

            if (!isAuthority && (subjects == null || subjects.Length == 0))
            {
                throw new ArgumentException("If not creating an authority, must specify at least one Subject", "subjects");
            }

            if (!isAuthority && string.IsNullOrWhiteSpace(subjects[0]))
            {
                throw new ArgumentException("Certificate Subject must not be an empty string or only whitespace", "creationSettings.Subjects");
            }

            EnsureInitialized();

            _certGenerator.Reset();
            _certGenerator.SetSignatureAlgorithm(_signatureAlthorithm);

            X509Name authorityX509Name = CreateX509Name(_authorityCanonicalName);
            
            var keyPair = isAuthority ? _authorityKeyPair : _keyPairGenerator.GenerateKeyPair();
            if (isAuthority)
            {
                _certGenerator.SetIssuerDN(authorityX509Name);
                _certGenerator.SetSubjectDN(authorityX509Name);

                var authorityKeyIdentifier = new AuthorityKeyIdentifier(
                    SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(_authorityKeyPair.Public),
                    new GeneralNames(new GeneralName(authorityX509Name)),
                    new BigInteger(7, _random).Abs());

                _certGenerator.AddExtension(X509Extensions.AuthorityKeyIdentifier, true, authorityKeyIdentifier);
                _certGenerator.AddExtension(X509Extensions.KeyUsage, true, new KeyUsage(X509KeyUsage.DigitalSignature | X509KeyUsage.KeyAgreement | X509KeyUsage.KeyCertSign | X509KeyUsage.KeyEncipherment | X509KeyUsage.CrlSign));

            }
            else
            {
                X509Name subjectName = CreateX509Name(subjects[0]);
                _certGenerator.SetIssuerDN(PrincipalUtilities.GetSubjectX509Principal(signingCertificate));
                _certGenerator.SetSubjectDN(subjectName);

                _certGenerator.AddExtension(X509Extensions.AuthorityKeyIdentifier, true, new AuthorityKeyIdentifierStructure(_authorityKeyPair.Public));
                _certGenerator.AddExtension(X509Extensions.KeyUsage, true, new KeyUsage(X509KeyUsage.DigitalSignature | X509KeyUsage.KeyAgreement | X509KeyUsage.KeyEncipherment));

            }

            _certGenerator.AddExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(keyPair.Public));

            _certGenerator.SetSerialNumber(new BigInteger(64 /*sizeInBits*/, _random).Abs());
            _certGenerator.SetNotBefore(certificateCreationSettings.ValidityNotBefore);
            _certGenerator.SetNotAfter(certificateCreationSettings.ValidityNotAfter);
            _certGenerator.SetPublicKey(keyPair.Public);

            _certGenerator.AddExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(isAuthority));
            _certGenerator.AddExtension(X509Extensions.ExtendedKeyUsage, true, new ExtendedKeyUsage(KeyPurposeID.IdKPServerAuth, KeyPurposeID.IdKPClientAuth));

            if (!isAuthority)
            {
                if (isMachineCert)
                {
                    List<Asn1Encodable> subjectAlternativeNames = new List<Asn1Encodable>(); 
                    
                    // All endpoints should also be in the Subject Alt Names 
                    for (int i = 0; i < subjects.Length; i++)
                    {
                        if (!string.IsNullOrWhiteSpace(subjects[i]))
                        {
                            // Machine certs can have additional DNS names
                            subjectAlternativeNames.Add(new GeneralName(GeneralName.DnsName, subjects[i]));
                        }
                    }

                    _certGenerator.AddExtension(X509Extensions.SubjectAlternativeName, true, new DerSequence(subjectAlternativeNames.ToArray()));
                }
                else
                {
                    if (subjects.Length > 1)
                    {
                        var subjectAlternativeNames = new Asn1EncodableVector();
                    
                        // Only add a SAN for the user if there are any
                        for (int i = 1; i < subjects.Length; i++)
                        {
                            if (!string.IsNullOrWhiteSpace(subjects[i]))
                            {
                                Asn1EncodableVector otherNames = new Asn1EncodableVector();
                                otherNames.Add(new DerObjectIdentifier(_upnObjectId));
                                otherNames.Add(new DerTaggedObject(true, 0, new DerUtf8String(subjects[i])));

                                Asn1Object genName = new DerTaggedObject(false, 0, new DerSequence(otherNames));

                                subjectAlternativeNames.Add(genName);
                            }
                        }
                        _certGenerator.AddExtension(X509Extensions.SubjectAlternativeName, true, new DerSequence(subjectAlternativeNames));
                    }
                }
            }

            var crlDistributionPoints = new DistributionPoint[1] {
                new DistributionPoint(new DistributionPointName(
                    new GeneralNames(new GeneralName(GeneralName.UniformResourceIdentifier, _crlUri))), null, new GeneralNames(new GeneralName(authorityX509Name)))
                };
            var revocationListExtension = new CrlDistPoint(crlDistributionPoints);
            _certGenerator.AddExtension(X509Extensions.CrlDistributionPoints, false, revocationListExtension);

            X509Certificate cert = _certGenerator.Generate(_authorityKeyPair.Private, _random);
            if (certificateCreationSettings.IsValidCert)
            {
                EnsureCertificateValidity(cert);
            }

            // For now, given that we don't know what format to return it in, preserve the formats so we have 
            // the flexibility to do what we need to

            X509CertificateContainer container = new X509CertificateContainer(); 

            X509CertificateEntry[] chain = new X509CertificateEntry[1];
            chain[0] = new X509CertificateEntry(cert);

            Pkcs12Store store = new Pkcs12StoreBuilder().Build();
            store.SetKeyEntry("", new AsymmetricKeyEntry(keyPair.Private), chain);

            using (MemoryStream stream = new MemoryStream())
            {
                store.Save(stream, _password.ToCharArray(), _random);
                container.Pfx = stream.ToArray(); 
            }

            X509Certificate2 outputCert;
            if (isAuthority)
            {
                // don't hand out the private key for the cert when it's the authority
                outputCert = new X509Certificate2(cert.GetEncoded()); 
            } 
            else
            {
                // Otherwise, allow encode with the private key. note that X509Certificate2.RawData will not provide the private key
                // you will have to re-export this cert if needed
                outputCert = new X509Certificate2(container.Pfx, _password, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet);
            }

            container.Subject = subjects[0];
            container.InternalCertificate = cert;
            container.Certificate = outputCert;
            container.Thumbprint = outputCert.Thumbprint;

            Trace.WriteLine("[CertificateGenerator] generated a certificate:");
            Trace.WriteLine(string.Format("    {0} = {1}", "isAuthority", isAuthority));
            if (!isAuthority)
            {
                Trace.WriteLine(string.Format("    {0} = {1}", "Signed by", signingCertificate.SubjectDN));
                Trace.WriteLine(string.Format("    {0} = {1}", "Subject (CN) ", subjects[0]));
                Trace.WriteLine(string.Format("    {0} = {1}", "Alt names ", string.Join(", ", subjects)));
            }
            Trace.WriteLine(string.Format("    {0} = {1}", "HasPrivateKey:", outputCert.HasPrivateKey));
            Trace.WriteLine(string.Format("    {0} = {1}", "Thumbprint", outputCert.Thumbprint));

            return container;
        }
        public void Setup()
        {
            _serverCert = Test.Common.Configuration.Certificates.GetServerCertificate();
            _listener   = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            _listener.Bind(new IPEndPoint(IPAddress.Loopback, 0));
            _listener.Listen(int.MaxValue);
            string responseText =
                "HTTP/1.1 200 OK\r\n" + (chunkedResponse ?
                                         $"Transfer-Encoding: chunked\r\n\r\n{responseLength.ToString("X")}\r\n{new string('a', responseLength)}\r\n0\r\n\r\n" :
                                         $"Content-Length: {responseLength}\r\n\r\n{new string('a', responseLength)}");
            ReadOnlyMemory <byte> responseBytes = Encoding.UTF8.GetBytes(responseText);

            _serverTask = Task.Run(async() =>
            {
                try
                {
                    while (true)
                    {
                        using (Socket s = await _listener.AcceptAsync())
                        {
                            try
                            {
                                Stream stream = new NetworkStream(s);
                                if (ssl)
                                {
                                    var sslStream = new SslStream(stream, false, delegate { return(true); });
                                    await sslStream.AuthenticateAsServerAsync(_serverCert, false, SslProtocols.None, false);
                                    stream = sslStream;
                                }

                                using (var reader = new StreamReader(stream, Encoding.ASCII, detectEncodingFromByteOrderMarks: false, bufferSize: 100))
                                {
                                    while (true)
                                    {
                                        while (!string.IsNullOrEmpty(await reader.ReadLineAsync()))
                                        {
                                            ;
                                        }
                                        await stream.WriteAsync(responseBytes);
                                    }
                                }
                            }
                            catch (SocketException e) when(e.SocketErrorCode == SocketError.ConnectionAborted)
                            {
                            }
                        }
                    }
                }
                catch { }
            });

            var ep  = (IPEndPoint)_listener.LocalEndPoint;
            var uri = new Uri($"http{(ssl ? "s" : "")}://{ep.Address}:{ep.Port}/");

            _handler = new SocketsHttpHandler();
            _invoker = new HttpMessageInvoker(_handler);

            if (ssl)
            {
                _handler.SslOptions.RemoteCertificateValidationCallback = delegate { return(true); };
            }

            _request = new HttpRequestMessage(HttpMethod.Get, uri);
        }
Beispiel #14
0
        public void reload_attach_inbound(ReloadMessage recmsg)
        {

            try
            {
                AttachReqAns req_answ = (AttachReqAns)recmsg.reload_message_body;
                NodeId OriginatorID = recmsg.OriginatorID;

                if (req_answ != null && req_answ.ice_candidates != null)
                {
                    //if (ReloadGlobals.UseNoIce || m_ReloadConfig.IsBootstrap)
                    //{
                    //Node attacher = new Node(recmsg.OriginatorID, req_answ.ice_candidates);           // markus, moved down
                    //bool isFinger = m_topology.routing_table.isFinger(attacher.Id);

                    //m_topology.routing_table.AddNode(attacher);
                    //m_topology.routing_table.SetNodeState(recmsg.OriginatorID, NodeState.attached);
                    //}


                    // incoming ATTACH REQUEST, so localnode is controlled agent
                    if (recmsg.IsRequest())
                    {

                        m_ReloadConfig.Logger(ReloadGlobals.TRACEFLAGS.T_RELOAD,
                                      String.Format("{0} ==> {1} TransId={2:x16}",
                                      RELOAD_MessageCode.Attach_Answer.ToString().PadRight(16, ' '),
                                      OriginatorID, recmsg.TransactionID));

                        ReloadMessage sendmsg = create_attach_answ(
                          new Destination(OriginatorID), recmsg.TransactionID);

                        // log output
                        m_ReloadConfig.Logger(ReloadGlobals.TRACEFLAGS.T_INFO, String.Format("Attach Request: Transaction ID: {0:x}", recmsg.TransactionID));

                        foreach (IceCandidate cand in ((AttachReqAns)sendmsg.reload_message_body).ice_candidates)
                            m_ReloadConfig.Logger(ReloadGlobals.TRACEFLAGS.T_INFO, String.Format("Attach Request: Gathered local candidate for Answer: {0}:{1} (TransId: {2:x})", cand.addr_port.ipaddr.ToString(), cand.addr_port.port, sendmsg.TransactionID));

                        foreach (IceCandidate cand in req_answ.ice_candidates)
                            m_ReloadConfig.Logger(ReloadGlobals.TRACEFLAGS.T_INFO, String.Format("Attach Request: Received remote candidate: {0}:{1} (TransId: {2:x})", cand.addr_port.ipaddr.ToString(), cand.addr_port.port, recmsg.TransactionID));


                        recmsg.PutViaListToDestination(sendmsg);
                        //sendmsg.addOverlayForwardingOptions(recmsg);  //Proprietary  //--Joscha	
                        if (m_machine is GWMachine)
                        { //workaround in case date is stored at the gateway node responsible to route the message back into the interconnectionoverlay 
                            if (sendmsg.forwarding_header.destination_list[0].destination_data.node_id == ((GWMachine)m_machine).GateWay.interDomainPeer.Topology.LocalNode.Id)
                            {
                                sendmsg.reload_message_body.RELOAD_MsgCode = RELOAD_MessageCode.Fetch_Answer;
                                ((GWMachine)m_machine).GateWay.interDomainPeer.Transport.receive_message(sendmsg);
                            }
                            else
                                send(sendmsg, m_topology.routing_table.GetNode(recmsg.LastHopNodeId));
                        }
                        else
                        {
                            send(sendmsg, m_topology.routing_table.GetNode(recmsg.LastHopNodeId));
                        }




                        // markus
                        if (!ReloadGlobals.UseNoIce) // using ICE
                        {
                            // we only need ICE processing if localnode is a peer (in case of bootstrap we need no checks)
                            if (!m_ReloadConfig.IsBootstrap)
                            {

                                #region ICE TODO
                                // localnode is Peer => ICE processing (this is controlled node)
                                AttachReqAns attachAnswer = (AttachReqAns)sendmsg.reload_message_body;

                                // deep copy of local and remote ice candidates
                                List<IceCandidate> localIceCandidatesCopy = new List<IceCandidate>();
                                List<IceCandidate> remoteIceCandidatesCopy = new List<IceCandidate>();

                                // local candidates
                                foreach (IceCandidate cand in attachAnswer.ice_candidates)
                                {
                                    IceCandidate deepCopy = (IceCandidate)cand.Clone();
                                    localIceCandidatesCopy.Add(deepCopy);
                                }

                                // remote candidates
                                foreach (IceCandidate cand in req_answ.ice_candidates)
                                {
                                    IceCandidate deepCopy = (IceCandidate)cand.Clone();
                                    remoteIceCandidatesCopy.Add(deepCopy);
                                }

                                // now form check list
                                //CheckList checkList = ICE.FormCheckList(attachAnswer.ice_candidates, req_answ.ice_candidates, false);
                                CheckList checkList = ICE.FormCheckList(localIceCandidatesCopy, remoteIceCandidatesCopy, false);

                                ICE.PrintCandidatePairList(checkList.candidatePairs);

                                Console.WriteLine("ThreadId: {0}, send_params einfügen: checkList count {1}", Thread.CurrentThread.ManagedThreadId, checkList.candidatePairs.Count);
                                // Add to connection queue
                                for (int i = 0; i < checkList.candidatePairs.Count; i++)
                                {
                                    ReloadSendParameters send_params = new ReloadSendParameters()
                                    {
                                        connectionTableEntry = null,
                                        destinationAddress = checkList.candidatePairs[i].remoteCandidate.addr_port.ipaddr,
                                        port = checkList.candidatePairs[i].remoteCandidate.addr_port.port,
                                        buffer = null,
                                        frame = false,
                                        done = new Port<bool>(),
                                        // markus
                                        connectionSocket = null,
                                    };


                                    // if key already exists => skip
                                    if (!GetForwardingAndLinkManagementLayer().GetConnectionQueue().ContainsKey(checkList.candidatePairs[i].remoteCandidate))
                                        GetForwardingAndLinkManagementLayer().GetConnectionQueue().Add(checkList.candidatePairs[i].remoteCandidate, send_params);

                                }

                                ICE.ScheduleChecks(checkList, m_ReloadConfig.Logger);

                                // Wait for signals of all succeded candidate pairs. Only one of the succeded candidate pairs is nominated
                                #region signaling
                                // wait for nomination signal
                                List<Thread> waitingThreads = new List<Thread>();

                                foreach (CandidatePair candPair in checkList.candidatePairs)
                                {
                                    if (candPair.state == CandidatePairState.Succeeded)
                                    {
                                        switch (candPair.localCandidate.tcpType)
                                        {
                                            case TcpType.Active:
                                                {
                                                    if (candPair.localCandidate.activeConnectingSocket != null)
                                                    {
                                                        Thread waitThread = new Thread(() =>
                                                        {
                                                            candPair.nominated = ICE.WaitForSignal(candPair.localCandidate.activeConnectingSocket);
                                                        });
                                                        waitingThreads.Add(waitThread);
                                                        waitThread.Start();
                                                    }
                                                }
                                                break;

                                            case TcpType.Passive:
                                                {
                                                    if (candPair.localCandidate.passiveAcceptedSocket != null)
                                                    {
                                                        Thread waitThread = new Thread(() =>
                                                        {
                                                            candPair.nominated = ICE.WaitForSignal(candPair.localCandidate.passiveAcceptedSocket);
                                                        });
                                                        waitingThreads.Add(waitThread);
                                                        waitThread.Start();
                                                    }
                                                }
                                                break;

                                            case TcpType.SO:
                                                {
                                                    if (candPair.localCandidate.soAcceptedSocket != null)
                                                    {
                                                        Thread waitThread = new Thread(() =>
                                                        {
                                                            candPair.nominated = ICE.WaitForSignal(candPair.localCandidate.soAcceptedSocket);
                                                        });
                                                        waitingThreads.Add(waitThread);
                                                        waitThread.Start();
                                                    }

                                                    else if (candPair.localCandidate.soConnectingSocket != null)
                                                    {
                                                        Thread waitThread = new Thread(() =>
                                                        {
                                                            candPair.nominated = ICE.WaitForSignal(candPair.localCandidate.soConnectingSocket);
                                                        });
                                                        waitingThreads.Add(waitThread);
                                                        waitThread.Start();
                                                    }
                                                }
                                                break;

                                        }   // switch
                                    }   // if
                                }   // foreach

                                // wait for all threads
                                foreach (Thread waitingThread in waitingThreads)
                                {
                                    waitingThread.Join();
                                }
                                #endregion


                                // choose pair
                                CandidatePair choosenPair = null;

                                // any nominated pair?
                                if (checkList.candidatePairs.Any(item => item.nominated == true))
                                {
                                    choosenPair = checkList.candidatePairs.First(item => item.nominated == true);
                                }

                                // Close all sockets of all candidate pairs not nominated
                                //for (int i = 0; i < checkList.candidatePairs.Count; i++)
                                //    if ((!checkList.candidatePairs[i].nominated) || (checkList.candidatePairs[i].state != CandidatePairState.Succeeded))
                                //        ICE.CloseAllCandidateSockets(checkList.candidatePairs[i].localCandidate);

                                // add node with chosen remote candidate
                                if (choosenPair != null)
                                {

                                    // save connection
                                    //GetForwardingAndLinkManagementLayer().SaveConnection(choosenPair);

                                    // get connection
                                    Socket socket = GetForwardingAndLinkManagementLayer().GetConnection(choosenPair);

                                    // Get IPAdress and Port of the attacher from attachers certificate cn
                                    System.Security.Cryptography.X509Certificates.X509Certificate2 tempcert = new System.Security.Cryptography.X509Certificates.X509Certificate2(recmsg.security_block.Certificates[0].Certificate);
                                    IPEndPoint attacherEndpoint =
                                        new IPEndPoint(IPAddress.Parse(tempcert.SubjectName.Name.ToString().Split(':')[1]),
                                                       Convert.ToInt32( tempcert.SubjectName.Name.ToString().Split(':')[2]));
                                    // StartReloadTLSClient
                                    GetForwardingAndLinkManagementLayer().StartReloadTLSClient(OriginatorID, socket, attacherEndpoint);

                                    // for all candidates send_params.done = true
                                    for (int i = 0; i < checkList.candidatePairs.Count; i++)
                                    {
                                        ReloadSendParameters send_params;

                                        GetForwardingAndLinkManagementLayer().GetConnectionQueue().TryGetValue(checkList.candidatePairs[i].remoteCandidate, out send_params);

                                        if (send_params != null)
                                        {
                                            send_params.done.Post(true);

                                            // remove from connection queue
                                            GetForwardingAndLinkManagementLayer().GetConnectionQueue().Remove(checkList.candidatePairs[i].remoteCandidate);
                                        }
                                    }

                                    List<IceCandidate> choosenRemoteCandidates = new List<IceCandidate>();
                                    choosenRemoteCandidates.Add(choosenPair.remoteCandidate);

                                    Node attacher = new Node(recmsg.OriginatorID, choosenRemoteCandidates);
                                    bool isFinger = m_topology.routing_table.isFinger(attacher.Id);

                                    m_topology.routing_table.AddNode(attacher);
                                    m_topology.routing_table.SetNodeState(recmsg.OriginatorID, NodeState.attached);
                                }

                                // free all port mappings created by UPnP
                                foreach (IceCandidate cand in attachAnswer.ice_candidates)
                                {
                                    if (cand.cand_type == CandType.tcp_nat)
                                    {
                                        UPnP upnp = new UPnP();
                                        bool discovered = upnp.Discover(cand.rel_addr_port.ipaddr);

                                        if (discovered)
                                            upnp.DeletePortMapping(cand.addr_port.port, ProtocolType.Tcp);
                                    }
                                }


                                #endregion

                            }


                            else
                            {
                                // localnode is bootstrap => no ICE processing

                                Node attacher = new Node(recmsg.OriginatorID, req_answ.ice_candidates);
                                bool isFinger = m_topology.routing_table.isFinger(attacher.Id);

                                m_topology.routing_table.AddNode(attacher);
                                m_topology.routing_table.SetNodeState(recmsg.OriginatorID, NodeState.attached);

                            }


                        }

                        // using NO ICE
                        else
                        {

                            Node attacher = new Node(recmsg.OriginatorID, req_answ.ice_candidates);
                            bool isFinger = m_topology.routing_table.isFinger(attacher.Id);

                            m_topology.routing_table.AddNode(attacher);
                            m_topology.routing_table.SetNodeState(recmsg.OriginatorID, NodeState.attached);
                        }
                        // markus end



                        if (req_answ.SendUpdate)
                            Arbiter.Activate(m_DispatcherQueue, new IterativeTask<Node, Node>(
                              m_topology.routing_table.GetNode(OriginatorID),
                              m_topology.routing_table.GetNode(recmsg.LastHopNodeId),
                              SendUpdate));



                    }

                    // incoming ATTACH ANSWER, so localnode is controlling agent
                    // and localnode must be a peer, because bootstraps dont create attach requests and because of this cant receive an attach answer
                    else
                    {
                        // using NOICE
                        if (ReloadGlobals.UseNoIce)     // markus: added if/else statement
                        {
                            m_ReloadConfig.Logger(ReloadGlobals.TRACEFLAGS.T_ERROR,
                              String.Format("{0} <== {1} (not handled!!)",
                              req_answ.RELOAD_MsgCode.ToString().PadRight(16, ' '), OriginatorID));
                        }

                        // using ICE
                        else
                        {
                            // get local candidates from request
                            List<IceCandidate> localCandidates = null;
                            bool gotLocalCandidate = m_attachRequestCandidates.TryGetValue(recmsg.TransactionID, out localCandidates);

                            // log output
                            m_ReloadConfig.Logger(ReloadGlobals.TRACEFLAGS.T_INFO, String.Format("Attach Answer: Transaction ID: {0:x}", recmsg.TransactionID));
                            foreach (IceCandidate cand in localCandidates)
                                m_ReloadConfig.Logger(ReloadGlobals.TRACEFLAGS.T_INFO, String.Format("Attach Answer: Got local candidate: {0}:{1} (TransId: {2:x})", cand.addr_port.ipaddr.ToString(), cand.addr_port.port, recmsg.TransactionID));

                            foreach (IceCandidate cand in req_answ.ice_candidates)
                                m_ReloadConfig.Logger(ReloadGlobals.TRACEFLAGS.T_INFO, String.Format("Attach Answer: Received remote candidate: {0}:{1} (TransId: {2:x})", cand.addr_port.ipaddr.ToString(), cand.addr_port.port, recmsg.TransactionID));


                            if (req_answ.ice_candidates != null)
                            {
                                // we need ice, except the answering peer is a bootstrap
                                bool needIce = true;

                                //// bootstrap responses with only one candidate
                                //if (req_answ.ice_candidates.Count == 1)
                                //{
                                // is it really a bootstrap?
                                if (req_answ.ice_candidates[0].cand_type == CandType.tcp_bootstrap)
                                {
                                    // attached to a bootstrap, so we have to do nothing here, no ice processing needed
                                    needIce = false;
                                }

                                //}

                                if (needIce)
                                {
                                    #region ICE TODO
                                    // ICE processing (this is controlling node)
                                    if (gotLocalCandidate)
                                    {
                                        // deep copy of remote ice candidates
                                        List<IceCandidate> remoteIceCandidatesCopy = new List<IceCandidate>();

                                        // remote candidates
                                        foreach (IceCandidate cand in req_answ.ice_candidates)
                                        {
                                            IceCandidate deepCopy = (IceCandidate)cand.Clone();
                                            remoteIceCandidatesCopy.Add(deepCopy);
                                        }

                                        //CheckList checkList = ICE.FormCheckList(localCandidates, req_answ.ice_candidates, true);
                                        CheckList checkList = ICE.FormCheckList(localCandidates, remoteIceCandidatesCopy, true);

                                        ICE.PrintCandidatePairList(checkList.candidatePairs);

                                        ICE.ScheduleChecks(checkList, m_ReloadConfig.Logger);

                                        m_attachRequestCandidates.Remove(recmsg.TransactionID);

                                        #region signaling

                                        // any succeeded pair?
                                        if (checkList.candidatePairs.Any(item => item.state == CandidatePairState.Succeeded))
                                        {
                                            // get all succeeded pairs
                                            List<CandidatePair> succeededPairs = checkList.candidatePairs.Where(item => item.state == CandidatePairState.Succeeded).ToList();

                                            // send nomination signal to peer
                                            bool sentSuccessfull = false;
                                            bool nominated;
                                            int counter = 0;

                                            foreach (CandidatePair pair in succeededPairs)
                                            {
                                                // simply nominate the first succeeded pair
                                                if (counter == 0)
                                                    nominated = true;
                                                else
                                                    nominated = false;

                                                switch (pair.localCandidate.tcpType)
                                                {
                                                    case TcpType.Active:
                                                        {
                                                            if (pair.localCandidate.activeConnectingSocket != null)
                                                            {
                                                                sentSuccessfull = ICE.SendSignal(pair.localCandidate.activeConnectingSocket, nominated);
                                                                pair.nominated = nominated;
                                                            }
                                                        }
                                                        break;

                                                    case TcpType.Passive:
                                                        {
                                                            if (pair.localCandidate.passiveAcceptedSocket != null)
                                                            {
                                                                sentSuccessfull = ICE.SendSignal(pair.localCandidate.passiveAcceptedSocket, nominated);
                                                                pair.nominated = nominated;
                                                            }
                                                        }
                                                        break;

                                                    case TcpType.SO:
                                                        {
                                                            if (pair.localCandidate.soAcceptedSocket != null)
                                                            {
                                                                sentSuccessfull = ICE.SendSignal(pair.localCandidate.soAcceptedSocket, nominated);
                                                                pair.nominated = nominated;
                                                            }

                                                            else if (pair.localCandidate.soConnectingSocket != null)
                                                            {
                                                                sentSuccessfull = ICE.SendSignal(pair.localCandidate.soConnectingSocket, nominated);
                                                                pair.nominated = nominated;
                                                            }
                                                        }
                                                        break;

                                                }   // switch

                                                counter++;

                                            }   // foreach


                                            if (sentSuccessfull)
                                            {

                                            }


                                        #endregion  // signaling


                                            // Start Server here, if a nominated pair exists
                                            if (checkList.candidatePairs.Any(item => item.nominated))
                                            {
                                                CandidatePair choosenPair = checkList.candidatePairs.First(item => item.nominated);

                                                // save connection here too?
                                                //GetForwardingAndLinkManagementLayer().SaveConnection(choosenPair);

                                                // get connection
                                                Socket socket = GetForwardingAndLinkManagementLayer().GetConnection(choosenPair);

                                                // StartReloadTLSServer
                                                GetForwardingAndLinkManagementLayer().StartReloadTLSServer(socket);
                                            } // if (any nominated)


                                        }   // if (any succeeded pair)

                                        // Close all sockets of all candidate pairs not nominated
                                        //for (int i = 0; i < checkList.candidatePairs.Count; i++)
                                        //    if ((!checkList.candidatePairs[i].nominated) || (checkList.candidatePairs[i].state != CandidatePairState.Succeeded))
                                        //        ICE.CloseAllCandidateSockets(checkList.candidatePairs[i].localCandidate);
                                    }

                                    #endregion  // ICE

                                }

                                // existing nat candidates to free?
                                if (localCandidates != null)
                                {
                                    // free all port mappings created by UPnP
                                    foreach (IceCandidate cand in localCandidates)
                                    {
                                        if (cand.cand_type == CandType.tcp_nat)
                                        {
                                            UPnP upnp = new UPnP();
                                            bool discovered = upnp.Discover(cand.rel_addr_port.ipaddr);

                                            if (discovered)
                                                upnp.DeletePortMapping(cand.addr_port.port, ProtocolType.Tcp);

                                        }
                                    }
                                }

                            }

                        }


                    }
                }
            }
            catch (Exception e)
            {

                throw;
            }

        }
        public static X509Certificate ReadCertificateFromBytes(byte[] certificate, string password, out AsymmetricKeyParameter privateKey)
        {
            var x509 = new System.Security.Cryptography.X509Certificates.X509Certificate2(certificate, password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags.Exportable);
            
            privateKey = TransformRSAPrivateKey(x509.PrivateKey);

            var cert = DotNetUtilities.FromX509Certificate(x509);
            return cert;
        }
Beispiel #16
0
 public CmsRecipient(System.Security.Cryptography.X509Certificates.X509Certificate2 certificate, System.Security.Cryptography.RSAEncryptionPadding rsaEncryptionPadding)
 {
 }
Beispiel #17
0
 public CmsSigner(System.Security.Cryptography.Pkcs.SubjectIdentifierType signerIdentifierType, System.Security.Cryptography.X509Certificates.X509Certificate2 certificate)
 {
 }
Beispiel #18
0
 public bool MatchesCertificate(System.Security.Cryptography.X509Certificates.X509Certificate2 certificate)
 {
     throw null;
 }
Beispiel #19
0
 public CmsRecipient(System.Security.Cryptography.Pkcs.SubjectIdentifierType recipientIdentifierType, System.Security.Cryptography.X509Certificates.X509Certificate2 certificate, System.Security.Cryptography.RSAEncryptionPadding rsaEncryptionPadding)
 {
 }
 public X509CertificateEndpointIdentity(System.Security.Cryptography.X509Certificates.X509Certificate2 certificate)
 {
 }
 public ClientCertificateCredential(string tenantId, string clientId, System.Security.Cryptography.X509Certificates.X509Certificate2 clientCertificate, Azure.Identity.TokenCredentialOptions options)
 {
 }
 public ClientCertificateCredential(string tenantId, string clientId, System.Security.Cryptography.X509Certificates.X509Certificate2 clientCertificate)
 {
 }
        /// <summary>
        /// 
        /// </summary>
        /// <remarks>Based on <see cref="http://www.fkollmann.de/v2/post/Creating-certificates-using-BouncyCastle.aspx"/></remarks>
        /// <param name="subjectName"></param>
        /// <returns></returns>
        public static byte[] GenerateCertificate(string subjectName, byte[] issuingCertificate, string issuingCertificatePassword, out string password)
        {

            AsymmetricKeyParameter caPrivateKey;
            var caCert = ReadCertificateFromBytes(issuingCertificate, issuingCertificatePassword, out caPrivateKey);

            var caAuth = new AuthorityKeyIdentifierStructure(caCert);
            var authKeyId = new AuthorityKeyIdentifier(caAuth.GetKeyIdentifier());

            // ---------------------------

            // Generating Random Numbers
            var randomGenerator = new CryptoApiRandomGenerator();
            var random = new SecureRandom(randomGenerator);

            var chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-()#$%^&@+=!";
            var rnd = new Random();
            var result = new string(
                Enumerable.Repeat(chars, 15)
                          .Select(s => s[rnd.Next(s.Length)])
                          .ToArray());
            password = result;

            var gen = new X509V3CertificateGenerator();
            var certName = new X509Name("CN=" + subjectName);
            var serialNo = BigInteger.ProbablePrime(120, random);
            gen.SetSerialNumber(serialNo);
            gen.SetSubjectDN(certName);
            gen.SetIssuerDN(caCert.IssuerDN);

            // gen.SetIssuerUniqueID(caCert.IssuerUniqueID.GetBytes())

            gen.SetNotAfter(DateTime.Now.AddYears(100));
            gen.SetNotBefore(DateTime.Now.Subtract(new TimeSpan(7, 0, 0, 0)));
            gen.SetSignatureAlgorithm("SHA256WithRSA"); //("MD5WithRSA");

            var kpgen = new RsaKeyPairGenerator();
            kpgen.Init(new KeyGenerationParameters(random, 2048)); // new SecureRandom(new CryptoApiRandomGenerator()), 2048));
            var subjectKeyPair = kpgen.GenerateKeyPair();
            gen.SetPublicKey(subjectKeyPair.Public);

            //gen.AddExtension(
            //   X509Extensions.AuthorityKeyIdentifier,
            //   false,
            //   authKeyId);

            //gen.AddExtension(
            //    X509Extensions.SubjectKeyIdentifier,
            //    false,
            //    new SubjectKeyIdentifierStructure(kp.Public)
            //    );

            //gen.AddExtension(
            //    X509Extensions.AuthorityKeyIdentifier.Id,
            //    false,
            //    new AuthorityKeyIdentifier(
            //        SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(kp.Public),
            //        new GeneralNames(new GeneralName(certName)),
            //        serialNo));

            gen.AddExtension(
                X509Extensions.ExtendedKeyUsage.Id,
                false,
                new ExtendedKeyUsage(new KeyPurposeID[] { KeyPurposeID.IdKPClientAuth, KeyPurposeID.IdKPServerAuth, KeyPurposeID.IdKPCodeSigning }));

            //1.3.6.1.5.5.7.3.1 = server authentication
            //1.3.6.1.5.5.7.3.2 = client authentication
            //1.3.6.1.5.5.7.3.3 = code signing

            var certificate = gen.Generate(caPrivateKey);

            PrivateKeyInfo info = PrivateKeyInfoFactory.CreatePrivateKeyInfo(subjectKeyPair.Private);

            // merge into X509Certificate2
            var x509 = new System.Security.Cryptography.X509Certificates.X509Certificate2(certificate.GetEncoded());
            var seq = (Asn1Sequence)Asn1Object.FromByteArray(info.PrivateKey.GetDerEncoded());
            if (seq.Count != 9)
            {
                throw new PemException("malformed sequence in RSA private key");
            }

            var rsa = new RsaPrivateKeyStructure(seq);
            RsaPrivateCrtKeyParameters rsaparams = new RsaPrivateCrtKeyParameters(
                rsa.Modulus, rsa.PublicExponent, rsa.PrivateExponent, rsa.Prime1, rsa.Prime2, rsa.Exponent1, rsa.Exponent2, rsa.Coefficient);

            //-------------

            //RsaPrivateCrtKeyParameters rsaparams = (RsaPrivateCrtKeyParameters)subjectKeyPair.Private;
            RSAParameters rsaParameters = DotNetUtilities.ToRSAParameters(rsaparams);
            CspParameters cspParameters = new CspParameters();
            cspParameters.KeyContainerName = Guid.NewGuid().ToString(); // "MyKeyContainer";
            RSACryptoServiceProvider rsaKey = new RSACryptoServiceProvider(2048, cspParameters);
            rsaKey.ImportParameters(rsaParameters);

            // ------------

            x509.PrivateKey = rsaKey; // DotNetUtilities.ToRSA(rsaparams);


            //var certBytes = DotNetUtilities.ToX509Certificate(certificate).Export(System.Security.Cryptography.X509Certificates.X509ContentType.Pfx, password);

            //var x5092 = new System.Security.Cryptography.X509Certificates.X509Certificate2(certBytes, password);
            //var rsaPriv = DotNetUtilities.ToRSA(subjectKeyPair.Private as RsaPrivateCrtKeyParameters);
            //x509.PrivateKey = rsaPriv;

            var x509Bytes = x509.Export(System.Security.Cryptography.X509Certificates.X509ContentType.Cert);
            System.IO.File.WriteAllBytes(@"C:\mycertx509x.cer", x509Bytes);

            var x509Bytes2 = x509.Export(System.Security.Cryptography.X509Certificates.X509ContentType.Pkcs12, password);

            System.IO.File.WriteAllBytes(@"C:\mycertx509x.pfx", x509Bytes2);
            System.IO.File.WriteAllText(@"C:\mycertx509x_pass.txt", password);

            //Utility.AddCertToStore(x509, System.Security.Cryptography.X509Certificates.StoreName.My, System.Security.Cryptography.X509Certificates.StoreLocation.LocalMachine);

            return x509Bytes2;
        }
Beispiel #24
0
 public CmsSigner(System.Security.Cryptography.Pkcs.SubjectIdentifierType signerIdentifierType, System.Security.Cryptography.X509Certificates.X509Certificate2 certificate, System.Security.Cryptography.AsymmetricAlgorithm privateKey)
 {
 }
        public static X509Certificate ReadCertificateFromBytes(byte[] certificate, string password, out AsymmetricKeyParameter privateKey)
        {
            var x509 = new System.Security.Cryptography.X509Certificates.X509Certificate2(certificate, password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags.Exportable);
            //var reader = new PemReader(new StringReader(pemValue));
            //Object obj = reader.ReadObject();
            //if (obj is AsymmetricCipherKeyPair)
            //{
            //    privateKey = (RsaPrivateCrtKeyParameters)((AsymmetricCipherKeyPair)obj).Private;
            //}
            //else
            //{
            //    throw new InvalidOperationException("certificate did not have private key.");
            //}
            privateKey = TransformRSAPrivateKey(x509.PrivateKey);

            var cert = DotNetUtilities.FromX509Certificate(x509);
            return cert;
        }
Beispiel #26
0
 public CmsSigner(System.Security.Cryptography.X509Certificates.X509Certificate2 certificate)
 {
 }
Beispiel #27
0
        static void verify(string file)
        {
            digidoc.digidoc.initialize();
            try
            {
                Console.WriteLine("Opening file: " + file);
                WDoc b = new WDoc(file);

                Console.WriteLine("Files:");
                for (uint i = 0; i < b.documentCount(); ++i)
                {
                    Document d = b.getDocument(i);
                    Console.WriteLine(" {0} - {1}", i, d.getFileName());
                }
                Console.WriteLine();

                Console.WriteLine("Signatures:");
                for (uint i = 0; i < b.signatureCount(); ++i)
                {
                    Signature s = b.getSignature(i);

                    SignatureProductionPlace p = s.getProductionPlace();
                    Console.WriteLine("Address: {0} {1} {2} {3}", p.city, p.countryName, p.stateOrProvince, p.postalCode);

                    SignerRole r = s.getSignerRole();
                    Console.Write("Role:");
                    for (int j = 0; j < r.claimedRoles.Count; ++j)
                        Console.Write(" " + r.claimedRoles[j]);
                    Console.WriteLine();

                    Console.WriteLine("Time: " + s.getSigningTime());

                    System.Security.Cryptography.X509Certificates.X509Certificate2 c =
                        new System.Security.Cryptography.X509Certificates.X509Certificate2(s.getSigningCert());
                    Console.WriteLine("Cert: " + c.Subject);
                    try
                    {
                        s.validateOffline();
                        Console.WriteLine("Signature is valid");
                    }
                    catch (DigidocSignatureException e)
                    {
                        Console.WriteLine("Signature is invalid");
                        Console.WriteLine(e.Message);
                    }
                }
            }
            catch (DigidocBDocException e)
            {
                Console.WriteLine(e.Message);
            }
            catch (DigidocIOException e)
            {
                Console.WriteLine(e.Message);
            }
            catch (DigidocSignException e)
            {
                Console.WriteLine(e.Message);
            }
            catch (DigidocSignatureException e)
            {
                Console.WriteLine(e.Message);
            }
            catch (DigidocException e)
            {
                Console.WriteLine(e.Message);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
            digidoc.digidoc.terminate();
        }
Beispiel #28
0
 public System.Security.Cryptography.Pkcs.Pkcs12CertBag AddCertificate(System.Security.Cryptography.X509Certificates.X509Certificate2 certificate)
 {
     throw null;
 }
Beispiel #29
0
		/// <summary>
		/// Initializes a new instance of the <see cref="MimeKit.Cryptography.CmsRecipient"/> class.
		/// </summary>
		/// <remarks>
		/// <para>The initial value of the <see cref="EncryptionAlgorithms"/> property will be set to
		/// the Triple-DES encryption algorithm, which should be safe to assume for all modern
		/// S/MIME v3.x client implementations.</para>
		/// <para>The <see cref="RecipientIdentifierType"/> will be initialized to
		/// <see cref="SubjectIdentifierType.IssuerAndSerialNumber"/>.</para>
		/// </remarks>
		/// <param name="certificate">The recipient's certificate.</param>
		/// <exception cref="System.ArgumentNullException">
		/// <paramref name="certificate"/> is <c>null</c>.
		/// </exception>
		public CmsRecipient (X509Certificate2 certificate)
		{
			if (certificate == null)
				throw new ArgumentNullException ("certificate");

			EncryptionAlgorithms = new EncryptionAlgorithm[] { EncryptionAlgorithm.TripleDes };
			RecipientIdentifierType = SubjectIdentifierType.IssuerAndSerialNumber;
			Certificate = DotNetUtilities.FromX509Certificate (certificate);
		}
 public static System.Security.Cryptography.ECDsa GetECDsaPrivateKey(this System.Security.Cryptography.X509Certificates.X509Certificate2 certificate)
 {
     throw null;
 }
Beispiel #31
0
 public static System.Security.Cryptography.RSA GetRSAPublicKey(this System.Security.Cryptography.X509Certificates.X509Certificate2 certificate)
 {
     return(default(System.Security.Cryptography.RSA));
 }
 public System.Security.Cryptography.X509Certificates.X509Certificate2 Create(System.Security.Cryptography.X509Certificates.X509Certificate2 issuerCertificate, System.DateTimeOffset notBefore, System.DateTimeOffset notAfter, byte[] serialNumber)
 {
     throw null;
 }
Beispiel #33
0
        static X509Certificate GetBouncyCastleCertificate(X509Certificate2 certificate)
        {
            var rawData = certificate.GetRawCertData();

            return(new X509CertificateParser().ReadCertificate(rawData));
        }
 public X509Certificate2Collection(System.Security.Cryptography.X509Certificates.X509Certificate2 certificate)
 {
 }
        public static void GenerateRootCertificate(string subjectName, long serialNumber, DateTime expireOn, bool isCertificateAuthority, out string thumbprint, out string pemPrivateKey, out string pemPublicCert, out byte[] publicCert, out byte[] pkcs12Data, out string password)
        {

            // Generating Random Numbers
            var randomGenerator = new CryptoApiRandomGenerator();
            var random = new SecureRandom(randomGenerator);

            var kpgen = new RsaKeyPairGenerator();
            kpgen.Init(new KeyGenerationParameters(random, 2048)); //new SecureRandom(new CryptoApiRandomGenerator()), 2048));
            var subjectKeyPair = kpgen.GenerateKeyPair();

            var gen = new X509V3CertificateGenerator();

            var certName = new X509Name("CN=" + subjectName);

            BigInteger serialNo;
            if (serialNumber == 0)
            {
                serialNo = BigInteger.ProbablePrime(120, random);
            }
            else
            {
                serialNo = BigInteger.ValueOf(serialNumber);
            }

            gen.SetSerialNumber(serialNo);
            gen.SetSubjectDN(certName);
            gen.SetIssuerDN(certName);

            gen.SetNotAfter(expireOn);
            gen.SetNotBefore(DateTime.Now.Date);
            gen.SetSignatureAlgorithm("SHA256WithRSA"); //("MD5WithRSA");
            gen.SetPublicKey(subjectKeyPair.Public);


            gen.AddExtension(
                X509Extensions.BasicConstraints.Id,
                true,
                new BasicConstraints(isCertificateAuthority));


            //// NOT WORKING... NOT PASSING CERTIFICATE ISSUING ALLOWED
            //if (isCertificateAuthority)
            //{
            //    gen.AddExtension(
            //         X509Extensions.BasicConstraints.,
            //         true,
            //         new BasicConstraints(isCertificateAuthority));
            //}



            var certificate = gen.Generate(subjectKeyPair.Private, random);

            PrivateKeyInfo info = PrivateKeyInfoFactory.CreatePrivateKeyInfo(subjectKeyPair.Private);
            var x509 = new System.Security.Cryptography.X509Certificates.X509Certificate2(certificate.GetEncoded());
            var seq = (Asn1Sequence)Asn1Object.FromByteArray(info.PrivateKey.GetDerEncoded());
            if (seq.Count != 9)
            {
                throw new PemException("Malformed sequence in RSA private key.");
            }

            var rsa = new RsaPrivateKeyStructure(seq);
            RsaPrivateCrtKeyParameters rsaparams = new RsaPrivateCrtKeyParameters(
                rsa.Modulus, rsa.PublicExponent, rsa.PrivateExponent, rsa.Prime1, rsa.Prime2, rsa.Exponent1, rsa.Exponent2, rsa.Coefficient);

            RSAParameters rsaParameters = DotNetUtilities.ToRSAParameters(rsaparams);
            CspParameters cspParameters = new CspParameters();
            cspParameters.KeyContainerName = Guid.NewGuid().ToString(); // "MyKeyContainer";
            RSACryptoServiceProvider rsaKey = new RSACryptoServiceProvider(2048, cspParameters);
            rsaKey.ImportParameters(rsaParameters);

            x509.PrivateKey = rsaKey; // DotNetUtilities.ToRSA(rsaparams);

            // Generating Random Numbers
            var chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-()#$%^&@+=!";
            var rnd = new Random();

            password = new string(
                Enumerable.Repeat(chars, 32)
                          .Select(s => s[rnd.Next(s.Length)])
                          .ToArray());
            thumbprint = x509.Thumbprint.ToLower();
            publicCert = x509.Export(System.Security.Cryptography.X509Certificates.X509ContentType.Cert);

            var privateKeyPem = new StringBuilder();
            var privateKeyPemWriter = new PemWriter(new StringWriter(privateKeyPem));
            privateKeyPemWriter.WriteObject(certificate);
            privateKeyPemWriter.WriteObject(subjectKeyPair.Private);
            privateKeyPemWriter.Writer.Flush();
            pemPrivateKey = privateKeyPem.ToString();

            var publicKeyPem = new StringBuilder();
            var utf8WithoutBom = new System.Text.UTF8Encoding(false);
            var publicKeyPemWriter = new PemWriter(new StringWriterWithEncoding(publicKeyPem, utf8WithoutBom));
            publicKeyPemWriter.WriteObject(certificate);
            publicKeyPemWriter.Writer.Flush();
            pemPublicCert = publicKeyPem.ToString();
            pemPublicCert = pemPublicCert.Replace(Environment.NewLine, "\n"); //only use newline and not returns

            pkcs12Data = x509.Export(System.Security.Cryptography.X509Certificates.X509ContentType.Pfx, password);
        }
 public void Insert(int index, System.Security.Cryptography.X509Certificates.X509Certificate2 certificate)
 {
 }
        private void StartHTTP()
        {
            try
            {
                m_log.Info("[HTTPD]: Spawned main thread OK");
                //m_httpListener = new HttpListener();
                NotSocketErrors = 0;
                if (!m_ssl)
                {
                    //m_httpListener.Prefixes.Add("http://+:" + m_port + "/");
                    //m_httpListener.Prefixes.Add("http://10.1.1.5:" + m_port + "/");
                    m_httpListener2 = new CoolHTTPListener(m_listenIPAddress, (int)m_port);
                    m_httpListener2.ExceptionThrown += httpServerException;
                    m_httpListener2.LogWriter = httpserverlog;

                    // Uncomment this line in addition to those in HttpServerLogWriter
                    // if you want more detailed trace information from the HttpServer
                    //m_httpListener2.UseTraceLogs = true;

                    m_httpListener2.DisconnectHandler = httpServerDisconnectMonitor;
                }
                else
                {
                    //m_httpListener.Prefixes.Add("https://+:" + (m_sslport) + "/");
                    //m_httpListener.Prefixes.Add("http://+:" + m_port + "/");
                    System.Security.Cryptography.X509Certificates.X509Certificate2 cert =
                             new System.Security.Cryptography.X509Certificates.X509Certificate2("SineWaveCert.pfx", "123");
                    m_httpListener2 = new CoolHTTPListener(IPAddress.Any, (int)m_port, cert);
                    m_httpListener2.ExceptionThrown += httpServerException;
                    m_httpListener2.LogWriter = httpserverlog;
                    m_httpListener2.DisconnectHandler = httpServerDisconnectMonitor;
                }

                m_httpListener2.RequestHandler += OnHandleRequestIOThread;
                //m_httpListener.Start();
                m_httpListener2.Start(64);
                HTTPDRunning = true;

                //HttpListenerContext context;
                //while (true)
                //{
                //    context = m_httpListener.GetContext();
                //    ThreadPool.QueueUserWorkItem(new WaitCallback(HandleRequest), context);
                // }
            }
            catch (Exception e)
            {
                m_log.Error("[HTTPD]: Error - " + e.Message);
                m_log.Error("[HTTPD]: Tip: Do you have permission to listen on port " + m_port + ", " + m_sslport + "?");

                // We want this exception to halt the entire server since in current configurations we aren't too
                // useful without inbound HTTP.
                throw e;
            }
        }
 public void Remove(System.Security.Cryptography.X509Certificates.X509Certificate2 certificate)
 {
 }
        /// <summary>
        /// Are we capable of generating, saving, loading and removing a cert.  A test of a host system's compatibility
        /// with our cert stuff
        /// </summary>
        public static void GenerateSaveAndReload()
        {
            //USING BOUNCY CASTLE
            // create bouncy castle cert and save it
            AsymmetricCipherKeyPair kp;
            var x509 = CertificateGenerator.GenerateCertificate("Subject", out kp);

            string FilePath = "cert.pfx";
            string Alias = "foo";
            string Pwd = "bar";

            // save it
            CertificateGenerator.SaveToFile(x509, kp, FilePath, Alias, Pwd);

            //USING NATIVE.NET TO CONSUME BOUNCY
            // open the store as X509Certificate2
            var x5092 = new System.Security.Cryptography.X509Certificates.X509Certificate2(FilePath, Pwd);

            Console.WriteLine(x5092.SubjectName);
            Console.WriteLine(x5092.Thumbprint);
            Console.WriteLine(x5092.PrivateKey.SignatureAlgorithm);

            //clean it up
            File.Delete(FilePath);
        }
 public static System.Security.Cryptography.X509Certificates.X509Certificate2 CopyWithPrivateKey(this System.Security.Cryptography.X509Certificates.X509Certificate2 certificate, System.Security.Cryptography.DSA privateKey)
 {
     throw null;
 }
        public static byte[] GenerateRootCertificate(string subjectName, string password, out string pemValue)
        {

            // Generating Random Numbers
            var randomGenerator = new CryptoApiRandomGenerator();
            var random = new SecureRandom(randomGenerator);

            var kpgen = new RsaKeyPairGenerator();
            kpgen.Init(new KeyGenerationParameters(random, 2048)); //new SecureRandom(new CryptoApiRandomGenerator()), 2048));
            var subjectKeyPair = kpgen.GenerateKeyPair();

            var gen = new X509V3CertificateGenerator();

            var certName = new X509Name("CN=" + subjectName);
            BigInteger serialNo = BigInteger.ValueOf(4); //BigInteger.ProbablePrime(120, random);
            gen.SetSerialNumber(serialNo);

            gen.SetSubjectDN(certName);
            gen.SetIssuerDN(certName);

            gen.SetNotAfter(DateTime.Now.AddYears(100));
            gen.SetNotBefore(DateTime.Now.Subtract(new TimeSpan(7, 0, 0, 0)));
            gen.SetSignatureAlgorithm("SHA256WithRSA"); //("MD5WithRSA");
            gen.SetPublicKey(subjectKeyPair.Public);

            //gen.AddExtension(
            //    X509Extensions.SubjectKeyIdentifier,
            //    false,
            //    new SubjectKeyIdentifierStructure(kp.Public)
            //    );

            //gen.AddExtension(
            //    X509Extensions.AuthorityKeyIdentifier.Id,
            //    false,
            //    new AuthorityKeyIdentifier(
            //        SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(subjectKeyPair.Public),
            //        new GeneralNames(new GeneralName(certName)),
            //        serialNo));

            var certificate = gen.Generate(subjectKeyPair.Private, random);

            var privateKeyPem = new StringBuilder();
            var privateKeyPemWriter = new PemWriter(new StringWriter(privateKeyPem));

            privateKeyPemWriter.WriteObject(certificate);
            privateKeyPemWriter.WriteObject(subjectKeyPair.Private);
            privateKeyPemWriter.Writer.Flush();
            pemValue = privateKeyPem.ToString();
            System.IO.File.WriteAllText(@"C:\_rootCa.pem", pemValue);

            //var certBytes = DotNetUtilities.ToX509Certificate(certificate).Export(System.Security.Cryptography.X509Certificates.X509ContentType.Pkcs12, password);

            //var x509 = new System.Security.Cryptography.X509Certificates.X509Certificate2(certificate.GetEncoded());

            //RSA rsaPriv = DotNetUtilities.ToRSA(subjectKeyPair.Private as RsaPrivateCrtKeyParameters);

            //
            PrivateKeyInfo info = PrivateKeyInfoFactory.CreatePrivateKeyInfo(subjectKeyPair.Private);
            var x509 = new System.Security.Cryptography.X509Certificates.X509Certificate2(certificate.GetEncoded());
            var seq = (Asn1Sequence)Asn1Object.FromByteArray(info.PrivateKey.GetDerEncoded());
            if (seq.Count != 9)
            {
                throw new PemException("malformed sequence in RSA private key");
            }

            var rsa = new RsaPrivateKeyStructure(seq);
            RsaPrivateCrtKeyParameters rsaparams = new RsaPrivateCrtKeyParameters(
                rsa.Modulus, rsa.PublicExponent, rsa.PrivateExponent, rsa.Prime1, rsa.Prime2, rsa.Exponent1, rsa.Exponent2, rsa.Coefficient);

            //-------------

            //RsaPrivateCrtKeyParameters rsaparams = (RsaPrivateCrtKeyParameters)subjectKeyPair.Private;
            RSAParameters rsaParameters = DotNetUtilities.ToRSAParameters(rsaparams);
            CspParameters cspParameters = new CspParameters();
            cspParameters.KeyContainerName = Guid.NewGuid().ToString(); // "MyKeyContainer";
            RSACryptoServiceProvider rsaKey = new RSACryptoServiceProvider(2048, cspParameters);
            rsaKey.ImportParameters(rsaParameters);

            // ------------

            x509.PrivateKey = rsaKey; // DotNetUtilities.ToRSA(rsaparams);
            //


            var x509Bytes = x509.Export(System.Security.Cryptography.X509Certificates.X509ContentType.Cert, password);
            System.IO.File.WriteAllBytes(@"C:\_rootCa.cer", x509Bytes);

            var x509Bytes2 = x509.Export(System.Security.Cryptography.X509Certificates.X509ContentType.Pfx, password);
            System.IO.File.WriteAllBytes(@"C:\_rootCa.pfx", x509Bytes2);

            return x509Bytes;
        }
 public bool Build(System.Security.Cryptography.X509Certificates.X509Certificate2 certificate)
 {
     throw null;
 }
        // This reads a certificate from a file.
        // Thanks to: http://blog.softwarecodehelp.com/2009/06/23/CodeForRetrievePublicKeyFromCertificateAndEncryptUsingCertificatePublicKeyForBothJavaC.aspx
        public static X509Certificate ReadCertFromFile(string certificatePath, string password, out AsymmetricKeyParameter privateKey)
        {

            var x5092 = new System.Security.Cryptography.X509Certificates.X509Certificate2(certificatePath, password);
            var cert = DotNetUtilities.FromX509Certificate(x5092);
            privateKey = TransformRSAPrivateKey(x5092.PrivateKey);
            return cert;

            //try
            //{
            //    // Create file stream object to read certificate
            //    var keyStream = new FileStream(strCertificatePath, FileMode.Open, FileAccess.Read);

            //    // Read certificate using BouncyCastle component
            //    var inputKeyStore = new Pkcs12Store();  
            //    inputKeyStore.Load(keyStream, strCertificatePassword.ToCharArray());

            //    //Close File stream
            //    keyStream.Close();

            //    var keyAlias = inputKeyStore.Aliases.Cast<string>().FirstOrDefault(n => inputKeyStore.IsKeyEntry(n));

            //    // Read Key from Alieases  
            //    if (keyAlias == null)
            //        throw new NotImplementedException("Alias");

            //    //Read certificate into 509 format
            //    return (X509Certificate)inputKeyStore.GetCertificate(keyAlias).Certificate;
            //}
            //catch (Exception ex)
            //{
            //    throw ex;
            //}
        }
 public static System.Security.Cryptography.DSA GetDSAPublicKey(this System.Security.Cryptography.X509Certificates.X509Certificate2 certificate)
 {
     throw null;
 }
Beispiel #45
0
 public static Microsoft.AspNetCore.Server.Kestrel.Core.ListenOptions UseHttps(this Microsoft.AspNetCore.Server.Kestrel.Core.ListenOptions listenOptions, System.Security.Cryptography.X509Certificates.X509Certificate2 serverCertificate)
 {
     throw null;
 }
        public ActionResult Details(string id) {
            Guid publicKey;
            if (!Guid.TryParse(id, out publicKey))
                return new HttpStatusCodeResult(System.Net.HttpStatusCode.BadRequest);

            var certificado = DBContext.Certificados.Where(e => e.PublicKey == publicKey).SingleOrDefault();

            if (certificado == null)
                return HttpNotFound();


            System.Security.Cryptography.SHA1CryptoServiceProvider sha1 = new System.Security.Cryptography.SHA1CryptoServiceProvider();
            //System.Security.Cryptography.X509Certificates.X509Certificate2 cert = new System.Security.Cryptography.X509Certificates.X509Certificate2(certificado.PFXArchivo,
            //     certificado.PFXContrasena, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags.MachineKeySet);
            //// System.Security.Cryptography.RSACryptoServiceProvider rsaCryptoIPT = (System.Security.Cryptography.RSACryptoServiceProvider)cert.PrivateKey;
            System.Security.Cryptography.X509Certificates.X509Certificate2 cert = new System.Security.Cryptography.X509Certificates.X509Certificate2(certificado.PFXArchivo,
                 certificado.PFXContrasena, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags.MachineKeySet);
            System.Security.Cryptography.RSACryptoServiceProvider rsaCryptoIPT = (System.Security.Cryptography.RSACryptoServiceProvider)cert.PrivateKey;

             

            //System.Text.UTF8Encoding encoder = new System.Text.UTF8Encoding();
            //byte[] binData = encoder.GetBytes(cadenaOriginal);
            //byte[] binSignature = rsaCryptoIPT.SignData(binData, sha1);
            //string sello = Convert.ToBase64String(binSignature);
            //return sello;


            var model = new CertificadoDetailsViewModel(certificado);
            //model.Issuer = cert.Issuer;
            model.Issuer = cert.IssuerName.Name;
            model.Subject = cert.GetNameInfo(System.Security.Cryptography.X509Certificates.X509NameType.SimpleName, false);

           

            model.Issuer = cert.GetEffectiveDateString();
            model.Issuer = cert.GetExpirationDateString();
            model.Issuer = cert.Subject;
            model.Issuer = certificado.GetNumeroSerie(); //  cert.SerialNumber; // cert.GetSerialNumberString();
            model.Issuer = cert.GetNameInfo(System.Security.Cryptography.X509Certificates.X509NameType.SimpleName, true);
            //model.Issuer = cert.GetNameInfo(System.Security.Cryptography.X509Certificates.X509NameType.SimpleName, false);
            return View(model);
        }            
 public KeyMaterial()
 {
     SigningCertificate = new System.Security.Cryptography.X509Certificates.X509Certificate2("client.pfx", "abc!123");
 }
Beispiel #48
0
 private void Secure(Action success, Action<Exception> error)
 {
     var networkStream = new NetworkStream(_client);
     _clientSslStream = new SslStream(networkStream, false, RemoteCertificateValidationCallback);
     var clientAuthentication = _clientSslStream.BeginAuthenticateAsClient("localhost", null, null);
     var cert = new System.Security.Cryptography.X509Certificates.X509Certificate2("local.pfx", "local");
     _wrapper.Authenticate(cert, RemoteCertificateValidationCallback, success, error);
 }
 // This reads a certificate from a file.
 // Thanks to: http://blog.softwarecodehelp.com/2009/06/23/CodeForRetrievePublicKeyFromCertificateAndEncryptUsingCertificatePublicKeyForBothJavaC.aspx
 public static X509Certificate ReadCertFromFile(string certificatePath, string password, out AsymmetricKeyParameter privateKey)
 {
     var x5092 = new System.Security.Cryptography.X509Certificates.X509Certificate2(certificatePath, password);
     var cert = DotNetUtilities.FromX509Certificate(x5092);
     privateKey = TransformRSAPrivateKey(x5092.PrivateKey);
     return cert;
 }
Beispiel #50
0
 public DtlsSrtpClient(System.Security.Cryptography.X509Certificates.X509Certificate2 certificate) :
     this(DtlsUtils.LoadCertificateChain(certificate), DtlsUtils.LoadPrivateKeyResource(certificate))
 {
 }
Beispiel #51
0
        private void StartHTTP()
        {
            try
            {
                //m_httpListener = new HttpListener();
                NotSocketErrors = 0;
                if (!m_ssl)
                {
                    //m_httpListener.Prefixes.Add("http://+:" + m_port + "/");
                    //m_httpListener.Prefixes.Add("http://10.1.1.5:" + m_port + "/");
                    m_httpListener = HttpListener.Create (m_listenIPAddress, (int)m_port/*, httpserverlog*/);
                    m_httpListener.ExceptionThrown += httpServerException;
                    m_httpListener.LogWriter = httpserverlog;

                    // Uncomment this line in addition to those in HttpServerLogWriter
                    // if you want more detailed trace information from the HttpServer
                    //m_httpListener2.UseTraceLogs = true;

                    //m_httpListener2.DisconnectHandler = httpServerDisconnectMonitor;
                }
                else
                {
                    //m_httpListener.Prefixes.Add("https://+:" + (m_sslport) + "/");
                    //m_httpListener.Prefixes.Add("http://+:" + m_port + "/");
                    System.Security.Cryptography.X509Certificates.X509Certificate2 cert =
                        new System.Security.Cryptography.X509Certificates.X509Certificate2("SineWaveCert.pfx", "123");
                    m_httpListener = HttpListener.Create (IPAddress.Any, (int)m_port, cert/*, httpserverlog*/);
                    m_httpListener.ExceptionThrown += httpServerException;
                    m_httpListener.LogWriter = httpserverlog;
                }

                m_httpListener.RequestReceived += OnRequest;
                m_httpListener.Start(64);

                // Long Poll Service Manager with 3 worker threads a 25 second timeout for no events
                m_PollServiceManager = new PollServiceRequestManager(this, 3, 25000);
                HTTPDRunning = true;
            }
            catch (Exception e)
            {
                m_log.Error("[BASE HTTP SERVER]: Error - " + e.Message);
                m_log.Error("[BASE HTTP SERVER]: Tip: Do you have permission to listen on port " + m_port + "?");
                
                // We want this exception to halt the entire server since in current configurations we aren't too
                // useful without inbound HTTP.
                throw e;
            }
        }
Beispiel #52
0
 public CmsRecipient(System.Security.Cryptography.Pkcs.SubjectIdentifierType recipientIdentifierType, System.Security.Cryptography.X509Certificates.X509Certificate2 certificate)
 {
 }
Beispiel #53
0
		/// <summary>
		/// Initializes a new instance of the <see cref="MimeKit.Cryptography.CmsRecipient"/> class.
		/// </summary>
		/// <remarks>
		/// The initial value of the <see cref="EncryptionAlgorithms"/> property will be set to
		/// the Triple-DES encryption algorithm, which should be safe to assume for all modern
		/// S/MIME v3.x client implementations.
		/// </remarks>
		/// <param name="certificate">The recipient's certificate.</param>
		/// <param name="recipientIdentifierType">The recipient identifier type.</param>
		/// <exception cref="System.ArgumentNullException">
		/// <paramref name="certificate"/> is <c>null</c>.
		/// </exception>
		public CmsRecipient (X509Certificate2 certificate, SubjectIdentifierType recipientIdentifierType = SubjectIdentifierType.IssuerAndSerialNumber)
		{
			if (certificate == null)
				throw new ArgumentNullException (nameof (certificate));

			if (recipientIdentifierType == SubjectIdentifierType.IssuerAndSerialNumber)
				RecipientIdentifierType = SubjectIdentifierType.IssuerAndSerialNumber;
			else
				RecipientIdentifierType = SubjectIdentifierType.SubjectKeyIdentifier;

			EncryptionAlgorithms = new EncryptionAlgorithm[] { EncryptionAlgorithm.TripleDes };
			Certificate = DotNetUtilities.FromX509Certificate (certificate);
		}
Beispiel #54
0
 public CmsRecipient(System.Security.Cryptography.X509Certificates.X509Certificate2 certificate)
 {
 }
Beispiel #55
0
 public bool VerifySignatureForData(System.ReadOnlySpan <byte> data, out System.Security.Cryptography.X509Certificates.X509Certificate2 signerCertificate, System.Security.Cryptography.X509Certificates.X509Certificate2Collection extraCandidates = null)
 {
     throw null;
 }
 public X509CertificateEndpointIdentity(System.Security.Cryptography.X509Certificates.X509Certificate2 primaryCertificate, System.Security.Cryptography.X509Certificates.X509Certificate2Collection supportingCertificates)
 {
 }
        public ActionResult Create(CertificadoCreateViewModel model) {
            //var model = new CertificadoCreateViewModel();
           if (ModelState.IsValid) {
               if (model.CertificadoArchivo == null || model.CertificadoArchivo.ContentLength == 0) {
                    return View();
                }
                try {
                    // var user = UserManager.FindById(this.GetUserId());
                    Guid publicKey = Guid.NewGuid();
                    Certificado certificado = new Certificado();
                    //certificado.NumSerie = model.NumSerie;
                    //certificado.RFC = model.RFC;
                    //certificado.Inicia = model.Inicia; // DateTime.Parse(post["inicia"].ToString(), new System.Globalization.CultureInfo("es-MX"));
                    //certificado.Finaliza = model.Finaliza;
                    ////certificado.CertificadoBase64 = model.CertificadoArchivo;
                    ////certificado.PFXArchivo = model.PFXArchivo;

                    certificado.PFXContrasena = model.PFXContrasena;
                    certificado.Estado = model.Estado;

                    if (model.CertificadoArchivo != null) {
                        MemoryStream target = new MemoryStream();
                        model.CertificadoArchivo.InputStream.CopyTo(target);
                        Byte[] data = target.ToArray();
                        certificado.CertificadoDER = data;
                        //certificado.PFXArchivo = data;
                        certificado.CertificadoBase64 = Convert.ToBase64String(data);

                        System.Security.Cryptography.SHA1CryptoServiceProvider sha1 = new System.Security.Cryptography.SHA1CryptoServiceProvider();
                        //System.Security.Cryptography.X509Certificates.X509Certificate2 cert = new System.Security.Cryptography.X509Certificates.X509Certificate2(data, certificado.PFXContrasena);
                        System.Security.Cryptography.X509Certificates.X509Certificate2 cert = new System.Security.Cryptography.X509Certificates.X509Certificate2(data);
                        // cert.FriendlyName.ToString();

                        certificado.NumSerie = Certificado.GetSerialNumberString(cert);
                        
                        //certificado.RFC = cert.GetNameInfo(System.Security.Cryptography.X509Certificates.X509NameType.SimpleName, false);
                        string[] subject = cert.Subject.Split(',');
                        foreach (string strVal in subject) {
                            string value = strVal.Trim();
                            if (value.StartsWith("OID.2.5.4.45=")) {
                                string value2 = value.Replace("OID.2.5.4.45=", "");
                                certificado.RFC = value2.Substring(0, value2.IndexOf('/') >= 0 ? value2.IndexOf('/') : value2.Length).Trim();
                            }
                        }

                        certificado.Inicia = DateTime.Parse(cert.GetEffectiveDateString());
                        certificado.Finaliza = DateTime.Parse(cert.GetExpirationDateString());
                        //certificado.CertificadoBase64 = model.CertificadoArchivo;
                        //certificado.PFXArchivo = model.PFXArchivo;

                    }

                    if (model.PFXArchivo != null) {
                        MemoryStream target2 = new MemoryStream();
                        model.PFXArchivo.InputStream.CopyTo(target2);
                        Byte[] dataPFX = target2.ToArray();
                        certificado.PFXArchivo = dataPFX;



                    //    MemoryStream target3 = new MemoryStream();
                    //    model.CertificadoArchivo.InputStream.Position = 0;
                    //    model.CertificadoArchivo.InputStream.CopyTo(target3);
                    //    Byte[] data3 = target3.ToArray();
                    //    //string certificadoBase64 = Convert.ToBase64String(data);

                        
                    //    //System.Security.Cryptography.X509Certificates.X509Certificate2 cert = new System.Security.Cryptography.X509Certificates.X509Certificate2(certificado.PFXArchivo,
                    //    //     certificado.PFXContrasena, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags.MachineKeySet);
                    //    //System.Security.Cryptography.RSACryptoServiceProvider rsaCryptoIPT = (System.Security.Cryptography.RSACryptoServiceProvider)cert.PrivateKey;




                    }
                    //else {
                    //    MemoryStream target3 = new MemoryStream();
                    //    model.CertificadoArchivo.InputStream.CopyTo(target3);
                    //    Byte[] data3 = target3.ToArray();
                    //    //string certificadoBase64 = Convert.ToBase64String(data);

                    //    System.Security.Cryptography.SHA1CryptoServiceProvider sha1 = new System.Security.Cryptography.SHA1CryptoServiceProvider();
                    //    System.Security.Cryptography.X509Certificates.X509Certificate2 cert = new System.Security.Cryptography.X509Certificates.X509Certificate2(data3, certificado.PFXContrasena);
                    //    cert.FriendlyName.ToString();
                    //    //System.Security.Cryptography.X509Certificates.X509Certificate2 cert = new System.Security.Cryptography.X509Certificates.X509Certificate2(certificado.PFXArchivo,
                    //    //     certificado.PFXContrasena, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags.MachineKeySet);
                    //    System.Security.Cryptography.RSACryptoServiceProvider rsaCryptoIPT = (System.Security.Cryptography.RSACryptoServiceProvider)cert.PrivateKey;


                    //}

                    if (model.PrivateKeyDER != null) {
                        MemoryStream ms = new MemoryStream();
                        model.PrivateKeyDER.InputStream.CopyTo(ms);
                        Byte[] dataDER = ms.ToArray();
                        certificado.PrivateKeyDER = dataDER;
                    }
                    certificado.PrivateKeyContrasena = model.PrivateKeyContrasena;

                    this.DBContext.Certificados.Add(certificado);
                    this.DBContext.SaveChanges();
                }
                catch (Exception ex) {
                    //log.Error(ex, "Error upload photo blob to storage");
                    ex.ToString();
                }
            }
            return RedirectToAction("Index", "Home");
        }
Beispiel #58
0
 public bool VerifySignatureForHash(System.ReadOnlySpan <byte> hash, System.Security.Cryptography.Oid hashAlgorithmId, out System.Security.Cryptography.X509Certificates.X509Certificate2 signerCertificate, System.Security.Cryptography.X509Certificates.X509Certificate2Collection extraCandidates = null)
 {
     throw null;
 }
Beispiel #59
0
		/// <summary>
		/// Initializes a new instance of the <see cref="MimeKit.Cryptography.CmsSigner"/> class.
		/// </summary>
		/// <remarks>
		/// <para>The initial value of the <see cref="MimeKit.Cryptography.DigestAlgorithm"/> will
		/// be set to <see cref="MimeKit.Cryptography.DigestAlgorithm.Sha1"/> and both the
		/// <see cref="SignedAttributes"/> and <see cref="UnsignedAttributes"/> properties will be
		/// initialized to empty tables.</para>
		/// </remarks>
		/// <param name="certificate">The signer's certificate.</param>
		/// <exception cref="System.ArgumentNullException">
		/// <paramref name="certificate"/> is <c>null</c>.
		/// </exception>
		/// <exception cref="System.ArgumentException">
		/// <paramref name="certificate"/> cannot be used for signing.
		/// </exception>
		public CmsSigner (X509Certificate2 certificate) : this ()
		{
			if (certificate == null)
				throw new ArgumentNullException (nameof (certificate));

			if (!certificate.HasPrivateKey)
				throw new ArgumentException ("The certificate does not contain a private key.", nameof (certificate));

			var cert = DotNetUtilities.FromX509Certificate (certificate);
			var key = DotNetUtilities.GetKeyPair (certificate.PrivateKey);

			CheckCertificateCanBeUsedForSigning (cert);

			CertificateChain = new X509CertificateChain ();
			CertificateChain.Add (cert);
			Certificate = cert;
			PrivateKey = key.Private;
		}
Beispiel #60
0
 public bool VerifySignatureForSignerInfo(System.Security.Cryptography.Pkcs.SignerInfo signerInfo, out System.Security.Cryptography.X509Certificates.X509Certificate2 signerCertificate, System.Security.Cryptography.X509Certificates.X509Certificate2Collection extraCandidates = null)
 {
     throw null;
 }