Пример #1
0
        /*
         * static void AddP12 (string path, string filename, string password, ushort port)
         * {
         *      X509Certificate2 x509 = null;
         *      try {
         *              x509 = new X509Certificate2 (filename, password);
         *      } catch (Exception e) {
         *              Console.Error.WriteLine ("error loading certificate [{0}]", e.Message);
         *              Help (true);
         *      }
         *
         *      string target_cert = Path.Combine (path, String.Format ("{0}.cer", port));
         *      if (File.Exists (target_cert)) {
         *              Console.Error.WriteLine ("error: there is already a certificate for that port.");
         *              Help (true);
         *      }
         *      string target_pvk = Path.Combine (path, String.Format ("{0}.pvk", port));
         *      if (File.Exists (target_pvk)) {
         *              Console.Error.WriteLine ("error: there is already a certificate for that port.");
         *              Help (true);
         *      }
         *
         *      using (Stream cer = File.OpenWrite (target_cert)) {
         *              byte [] raw = x509.RawData;
         *              cer.Write (raw, 0, raw.Length);
         *      }
         *
         *      x509.PrivateKey.Save (target_pvk);
         * }
         */

        static void AddCertPvk(string path, string cert, string pvk, ushort port)
        {
            try {
                X509Certificate2 x509 = new X509Certificate2(cert);
                x509.PrivateKey = PrivateKey.CreateFromFile(pvk).RSA;
            } catch (Exception e) {
                Console.Error.WriteLine("error loading certificate or private key [{0}]", e.Message);
                Help(true);
            }

            string target_cert = Path.Combine(path, String.Format("{0}.cer", port));

            if (File.Exists(target_cert))
            {
                Console.Error.WriteLine("error: there is already a certificate for that port.");
                Help(true);
            }
            string target_pvk = Path.Combine(path, String.Format("{0}.pvk", port));

            if (File.Exists(target_pvk))
            {
                Console.Error.WriteLine("error: there is already a certificate for that port.");
                Help(true);
            }
            File.Copy(cert, target_cert);
            File.Copy(pvk, target_pvk);
        }
Пример #2
0
        static AsymmetricAlgorithm MyPrivateKeySelectionCallback(X509Certificate certificate, string targetHost)
        {
            PrivateKey key = null;

            try
            {
                //it is very important that the key has the .pvk format in windows!!!
                key = PrivateKey.CreateFromFile("myKey.pvk", "xxx");
            }
            catch (CryptographicException ex)
            {
                Console.WriteLine();
                Console.WriteLine();
                Console.WriteLine(ex);
                Console.WriteLine();
                Console.WriteLine();
            }

            if (key == null)
            {
                return(null);
            }

            return(key.RSA);
        }
Пример #3
0
 public void BadHeader()
 {
     byte[] bad = (byte[])nopwd.Clone();
     bad [4] = 0x01;
     WriteBuffer(bad);
     PrivateKey pvk = PrivateKey.CreateFromFile(testfile, null);
 }
Пример #4
0
        void LoadCertificateAndKey(IPAddress addr, int port)
        {
#if !DNXCORE50 && !DNX45 && !NET45
            // Actually load the certificate
            try {
                string dirname = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
                string path    = Path.Combine(dirname, ".mono");
                path = Path.Combine(path, "httplistener");
                string cert_file = Path.Combine(path, String.Format("{0}.cer", port));
                if (!File.Exists(cert_file))
                {
                    return;
                }
                string pvk_file = Path.Combine(path, String.Format("{0}.pvk", port));
                if (!File.Exists(pvk_file))
                {
                    return;
                }
                cert = new X509Certificate2(cert_file);
                key  = PrivateKey.CreateFromFile(pvk_file).RSA;
            } catch {
                // ignore errors
            }
#else
            throw new NotSupportedException();
#endif
        }
        private void LoadCertificateAndKey(IPAddress addr, int port)
        {
            // Actually load the certificate
            try
            {
                string dirname = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
                string path    = Path.Combine(dirname, ".mono");
                path = Path.Combine(path, "httplistener");
                string cert_file = Path.Combine(path, String.Format("{0}.cer", port));
                if (!File.Exists(cert_file))
                {
                    return;
                }
                cert = new X509Certificate2(cert_file);

                if (cert.HasPrivateKey)
                {
                    key = cert.PrivateKey;
                    return;
                }

                string pvk_file = Path.Combine(path, String.Format("{0}.pvk", port));
                if (!File.Exists(pvk_file))
                {
                    return;
                }
                key = PrivateKey.CreateFromFile(pvk_file).RSA;
            }
            catch
            {
                cert = null;
                key  = null;
            }
        }
Пример #6
0
        static private RSA GetPrivateKey(string keyfile, CspParameters csp)
        {
            RSA rsa = null;

            if (keyfile != null)
            {
                if (!File.Exists(keyfile))
                {
                    Console.WriteLine("Couldn't find '{0}' file.", keyfile);
                    return(null);
                }

                try {
                    PrivateKey pvk = PrivateKey.CreateFromFile(keyfile);
                    rsa = pvk.RSA;
                }
                catch (CryptographicException) {
                    Console.WriteLine("Enter password for {0}: ", keyfile);
                    string password = Console.ReadLine();
                    try {
                        PrivateKey pvk = PrivateKey.CreateFromFile(keyfile, password);
                        rsa = pvk.RSA;
                    }
                    catch (CryptographicException) {
                        Console.WriteLine("Invalid password!");
                    }
                }
            }
            else
            {
                rsa = new RSACryptoServiceProvider(csp);
            }

            return(rsa);
        }
Пример #7
0
        private void LoadPrivateKeyFile(string filename, string password)
        {
            if ((filename == null) || (key != null))
            {
                return;
            }

            try {
                if (password == null)
                {
                    key = PrivateKey.CreateFromFile(filename).RSA;
                }
                else
                {
                    key = PrivateKey.CreateFromFile(filename, password).RSA;
                }
            }
            catch (CryptographicException ce) {
                string message = String.Format("Invalid private key password or private key file '{0}' is corrupt.", filename);
                throw new CryptographicException(message, ce);
            }
            catch (Exception e) {
                string message = String.Format("Unable to load private key '{0}'.", filename);
                throw new CryptographicException(message, e);
            }
        }
Пример #8
0
        internal X509Certificate LoadCertificateAndKey(IPAddress addr, int port)
        {
            lock (registry) {
                if (certificate != null)
                {
                    return(certificate);
                }

                // Actually load the certificate
                try {
                    string dirname = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
                    string path    = Path.Combine(dirname, ".mono");
                    path = Path.Combine(path, "httplistener");
                    string cert_file = Path.Combine(path, String.Format("{0}.cer", port));
                    if (!File.Exists(cert_file))
                    {
                        return(null);
                    }
                    string pvk_file = Path.Combine(path, String.Format("{0}.pvk", port));
                    if (!File.Exists(pvk_file))
                    {
                        return(null);
                    }
                    var cert = new X509Certificate2(cert_file);
                    cert.PrivateKey = PrivateKey.CreateFromFile(pvk_file).RSA;
                    certificate     = cert;
                    return(certificate);
                } catch {
                    // ignore errors
                    certificate = null;
                    return(null);
                }
            }
        }
Пример #9
0
 private AsymmetricAlgorithm PrivateKeySelectionCallback(X509Certificate certificate, string targetHost)
 {
     Console.WriteLine("SslStream.PrivateKeyCertSelectionDelegate");
     try {
         PrivateKey key;
         if (_serverKeyFilename == String.Empty)
         {
             Assembly assembly        = Assembly.GetExecutingAssembly();
             Stream   stream          = assembly.GetManifestResourceStream("localhost.pvk");
             byte[]   privateKeyBytes = new byte[stream.Length];
             stream.Read(privateKeyBytes, 0, Convert.ToInt32(stream.Length));
             key = new PrivateKey(privateKeyBytes, "");
             Console.WriteLine("foo");
             return(key.RSA);
         }
         else
         {
             key = PrivateKey.CreateFromFile(_serverKeyFilename);
             Console.WriteLine("foo");
             return(key.RSA);
         }
     } catch (Exception ex) {
         Console.WriteLine("Exception: " + ex.Message);
     }
     Console.WriteLine("null");
     return(null);
 }
Пример #10
0
        public void MSPasswordWeak()
        {
            WriteBuffer(pwd);
            PrivateKey pvk = PrivateKey.CreateFromFile(testfile, "password");

            AssertNotNull("mspwd.RSA", pvk.RSA);
            Assert("mspwd.Encrypted", pvk.Encrypted);
            Assert("mspwd.Weak", pvk.Weak);
        }
Пример #11
0
        public void MSPasswordWeak()
        {
            WriteBuffer(pwd);
            PrivateKey pvk = PrivateKey.CreateFromFile(testfile, "password");

            Assert.IsNotNull(pvk.RSA, "mspwd.RSA");
            Assert.IsTrue(pvk.Encrypted, "mspwd.Encrypted");
            Assert.IsTrue(pvk.Weak, "mspwd.Weak");
        }
Пример #12
0
        public void MSNoPassword()
        {
            WriteBuffer(nopwd);
            PrivateKey pvk = PrivateKey.CreateFromFile(testfile);

            AssertNotNull("msnopwd.RSA", pvk.RSA);
            Assert("msnopwd.Encrypted", !pvk.Encrypted);
            Assert("msnopwd.Weak", pvk.Weak);
            AssertEquals("msnopwd.KeyType", 2, pvk.KeyType);
        }
Пример #13
0
        public void MSNoPassword()
        {
            WriteBuffer(nopwd);
            PrivateKey pvk = PrivateKey.CreateFromFile(testfile);

            Assert.IsNotNull(pvk.RSA, "msnopwd.RSA");
            Assert.IsTrue(!pvk.Encrypted, "msnopwd.Encrypted");
            Assert.IsTrue(pvk.Weak, "msnopwd.Weak");
            Assert.AreEqual(2, pvk.KeyType, "msnopwd.KeyType");
        }
Пример #14
0
        public void RemovePassword()
        {
            WriteBuffer(nopwd);
            PrivateKey pvk  = PrivateKey.CreateFromFile(testfile, "password");
            string     rsa1 = pvk.RSA.ToXmlString(true);

            pvk.Save(testfile);
            pvk = PrivateKey.CreateFromFile(testfile);
            Assert.IsNotNull(pvk.RSA, "nomorepwd.RSA");
            string rsa2 = pvk.RSA.ToXmlString(true);

            Assert.AreEqual(rsa1, rsa2, "nomorepwd.RSA identical");
            Assert.IsTrue(!pvk.Encrypted, "nomorepwd.Encrypted");
            Assert.IsTrue(pvk.Weak, "nomorepwd.Weak");
        }
Пример #15
0
 void LoadCertificateAndKey(IPAddress addr, int port)
 {
     // Actually load the certificate
     try {
         string dirname = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
         string path    = Path.Combine(dirname, ".mono");
         path = Path.Combine(path, "httplistener");
         string cert_file = Path.Combine(path, String.Format("{0}.cer", port));
         string pvk_file  = Path.Combine(path, String.Format("{0}.pvk", port));
         cert = new X509Certificate2(cert_file);
         key  = PrivateKey.CreateFromFile(pvk_file).RSA;
     } catch {
         // ignore errors
     }
 }
Пример #16
0
        public void RemovePassword()
        {
            WriteBuffer(nopwd);
            PrivateKey pvk  = PrivateKey.CreateFromFile(testfile, "password");
            string     rsa1 = pvk.RSA.ToXmlString(true);

            pvk.Save(testfile);
            pvk = PrivateKey.CreateFromFile(testfile);
            AssertNotNull("nomorepwd.RSA", pvk.RSA);
            string rsa2 = pvk.RSA.ToXmlString(true);

            AssertEquals("nomorepwd.RSA identical", rsa1, rsa2);
            Assert("nomorepwd.Encrypted", !pvk.Encrypted);
            Assert("nomorepwd.Weak", pvk.Weak);
        }
 private void LoadCertificateAndKey(IPAddress addr, int port)
 {
     try
     {
         string folderPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
         string path       = Path.Combine(folderPath, ".mono");
         path = Path.Combine(path, "httplistener");
         string fileName = Path.Combine(path, string.Format("{0}.cer", port));
         string filename = Path.Combine(path, string.Format("{0}.pvk", port));
         this.cert = new System.Security.Cryptography.X509Certificates.X509Certificate2(fileName);
         this.key  = PrivateKey.CreateFromFile(filename).RSA;
     }
     catch
     {
     }
 }
Пример #18
0
        public void ConvertToPasswordStrong()
        {
            WriteBuffer(nopwd);
            PrivateKey pvk  = PrivateKey.CreateFromFile(testfile);
            string     rsa1 = pvk.RSA.ToXmlString(true);

            pvk.Weak = false;     // we want strong crypto
            pvk.Save(testfile, "password");
            pvk = PrivateKey.CreateFromFile(testfile, "password");
            Assert.IsNotNull(pvk.RSA, "topwd.RSA");
            string rsa2 = pvk.RSA.ToXmlString(true);

            Assert.AreEqual(rsa1, rsa2, "topwd.RSA identical");
            Assert.IsTrue(pvk.Encrypted, "topwd.Encrypted");
            Assert.IsTrue(!pvk.Weak, "topwd.Weak");
        }
Пример #19
0
        public void ConvertToPasswordStrong()
        {
            WriteBuffer(nopwd);
            PrivateKey pvk  = PrivateKey.CreateFromFile(testfile);
            string     rsa1 = pvk.RSA.ToXmlString(true);

            pvk.Weak = false;     // we want strong crypto
            pvk.Save(testfile, "password");
            pvk = PrivateKey.CreateFromFile(testfile, "password");
            AssertNotNull("topwd.RSA", pvk.RSA);
            string rsa2 = pvk.RSA.ToXmlString(true);

            AssertEquals("topwd.RSA identical", rsa1, rsa2);
            Assert("topwd.Encrypted", pvk.Encrypted);
            Assert("topwd.Weak", !pvk.Weak);
        }
Пример #20
0
 private void LoadCertificateAndKey(IPAddress addr, int port)
 {
     try
     {
         string folderPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
         string path       = Path.Combine(folderPath, ".mono");
         path = Path.Combine(path, "httplistener");
         string fileName = Path.Combine(path, $"{port}.cer");
         string filename = Path.Combine(path, $"{port}.pvk");
         cert = new X509Certificate2(fileName);
         key  = PrivateKey.CreateFromFile(filename).RSA;
     }
     catch
     {
     }
 }
Пример #21
0
        public void SaltWithoutPassword()
        {
            byte[] bad     = (byte[])nopwd.Clone();
            int    saltlen = BitConverterLE.ToInt32(bad, 16);
            int    keylen  = BitConverterLE.ToInt32(bad, 20);

            // preserve total length
            saltlen += 8;
            keylen  -= 8;
            // modify blob
            byte[] data = BitConverterLE.GetBytes(saltlen);
            Buffer.BlockCopy(data, 0, bad, 16, data.Length);
            data = BitConverterLE.GetBytes(keylen);
            Buffer.BlockCopy(data, 0, bad, 20, data.Length);
            // save-n-load
            WriteBuffer(bad);
            PrivateKey pvk = PrivateKey.CreateFromFile(testfile, null);
        }
Пример #22
0
        public void CreatePVK()
        {
            PrivateKey pvk = new PrivateKey();

            pvk.KeyType = 2;
            pvk.RSA     = RSA.Create();
            string rsa1 = pvk.RSA.ToXmlString(true);

            pvk.Save(testfile, "mono");

            pvk = PrivateKey.CreateFromFile(testfile, "mono");
            AssertNotNull("new.RSA", pvk.RSA);
            string rsa2 = pvk.RSA.ToXmlString(true);

            AssertEquals("new.RSA identical", rsa1, rsa2);
            Assert("new.Encrypted", pvk.Encrypted);
            Assert("new.Weak", !pvk.Weak);
        }
Пример #23
0
        public void CreatePVK()
        {
            PrivateKey pvk = new PrivateKey();

            pvk.KeyType = 2;
            pvk.RSA     = RSA.Create();
            string rsa1 = pvk.RSA.ToXmlString(true);

            pvk.Save(testfile, "mono");

            pvk = PrivateKey.CreateFromFile(testfile, "mono");
            Assert.IsNotNull(pvk.RSA, "new.RSA");
            string rsa2 = pvk.RSA.ToXmlString(true);

            Assert.AreEqual(rsa1, rsa2, "new.RSA identical");
            Assert.IsTrue(pvk.Encrypted, "new.Encrypted");
            Assert.IsTrue(!pvk.Weak, "new.Weak");
        }
Пример #24
0
        public SocketPongClient(Socket socket, bool useTls, int readBufferSize, string certFile, string pvkFile, string pvkPassword) :
            base(useTls, readBufferSize, socket)
        {
            if (useTls)
            {
                _privateKey = PrivateKey.CreateFromFile(pvkFile, pvkPassword).RSA;

                SslServerStream secureStream = new SslServerStream(
                    base.NetworkStream,
                    X509Certificate.CreateFromCertFile(certFile),
                    false,
                    true,
                    Mono.Security.Protocol.Tls.SecurityProtocolType.Tls);

                secureStream.PrivateKeyCertSelectionDelegate = new PrivateKeySelectionCallback(PrivateKeyCertSelectionCallback);

                base.SecureStream = secureStream;
            }
        }
Пример #25
0
        internal X509Certificate LoadCertificateAndKey(IPAddress addr, int port)
        {
#if SECURITY_DEP
            lock (_internalLock) {
                if (certificate != null)
                {
                    return(certificate);
                }

                // Actually load the certificate
                try {
                    string dirname = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
                    string path    = Path.Combine(dirname, ".mono");
                    path = Path.Combine(path, "httplistener");
                    string cert_file = Path.Combine(path, String.Format("{0}.cer", port));
                    if (!File.Exists(cert_file))
                    {
                        return(null);
                    }
                    string pvk_file = Path.Combine(path, String.Format("{0}.pvk", port));
                    if (!File.Exists(pvk_file))
                    {
                        return(null);
                    }
                    var cert       = new X509Certificate2(cert_file);
                    var privateKey = PrivateKey.CreateFromFile(pvk_file).RSA;
                    certificate = new X509Certificate2((X509Certificate2Impl)cert.Impl.CopyWithPrivateKey(privateKey));
                    return(certificate);
                } catch {
                    // ignore errors
                    certificate = null;
                    return(null);
                }
            }
#else
            throw new PlatformNotSupportedException();
#endif
        }
Пример #26
0
        public static int MakeCertMain(string[] args)
        {
            if (args.Length < 1)
            {
                Header();
                Console.WriteLine("ERROR: Missing output filename {0}", Environment.NewLine);
                Help();
                return(-1);
            }

            string fileName = args [args.Length - 1];

            // default values
            byte[]   sn        = Guid.NewGuid().ToByteArray();
            string   subject   = defaultSubject;
            string   issuer    = defaultIssuer;
            DateTime notBefore = DateTime.Now;
            DateTime notAfter  = new DateTime(643445675990000000);             // 12/31/2039 23:59:59Z

            RSA issuerKey = (RSA)RSA.Create();

            issuerKey.FromXmlString(MonoTestRootAgency);
            RSA subjectKey = (RSA)RSA.Create();

            bool   selfSigned = false;
            string hashName   = "SHA1";

            CspParameters             subjectParams = new CspParameters();
            CspParameters             issuerParams  = new CspParameters();
            BasicConstraintsExtension bce           = null;
            ExtendedKeyUsageExtension eku           = null;
            SubjectAltNameExtension   alt           = null;
            string          p12file           = null;
            string          p12pwd            = null;
            X509Certificate issuerCertificate = null;

            Header();
            try {
                int i = 0;
                while (i < args.Length)
                {
                    switch (args [i++])
                    {
                    // Basic options
                    case "-#":
                        // Serial Number
                        sn = BitConverter.GetBytes(Convert.ToInt32(args [i++]));
                        break;

                    case "-n":
                        // Subject Distinguish Name
                        subject = args [i++];
                        break;

                    case "-$":
                        // (authenticode) commercial or individual
                        // CRITICAL KeyUsageRestriction extension
                        // hash algorithm
                        string usageRestriction = args [i++].ToLower();
                        switch (usageRestriction)
                        {
                        case "commercial":
                        case "individual":
                            Console.WriteLine("WARNING: Unsupported deprecated certification extension KeyUsageRestriction not included");
//									Console.WriteLine ("WARNING: ExtendedKeyUsage for codesigning has been included.");
                            break;

                        default:
                            Console.WriteLine("Unsupported restriction " + usageRestriction);
                            return(-1);
                        }
                        break;

                    // Extended Options
                    case "-a":
                        // hash algorithm
                        switch (args [i++].ToLower())
                        {
                        case "sha1":
                            hashName = "SHA1";
                            break;

                        case "md5":
                            Console.WriteLine("WARNING: MD5 is no more safe for this usage.");
                            hashName = "MD5";
                            break;

                        default:
                            Console.WriteLine("Unsupported hash algorithm");
                            break;
                        }
                        break;

                    case "-b":
                        // Validity / notBefore
                        notBefore = DateTime.Parse(args [i++] + " 23:59:59", CultureInfo.InvariantCulture);
                        break;

                    case "-cy":
                        // basic constraints - autority or end-entity
                        switch (args [i++].ToLower())
                        {
                        case "authority":
                            if (bce == null)
                            {
                                bce = new BasicConstraintsExtension();
                            }
                            bce.CertificateAuthority = true;
                            break;

                        case "end":
                            // do not include extension
                            bce = null;
                            break;

                        case "both":
                            Console.WriteLine("ERROR: No more supported in X.509");
                            return(-1);

                        default:
                            Console.WriteLine("Unsupported certificate type");
                            return(-1);
                        }
                        break;

                    case "-d":
                        // CN private extension ?
                        Console.WriteLine("Unsupported option");
                        break;

                    case "-e":
                        // Validity / notAfter
                        notAfter = DateTime.Parse(args [i++] + " 23:59:59", CultureInfo.InvariantCulture);
                        break;

                    case "-eku":
                        // extendedKeyUsage extension
                        char[]   sep      = { ',' };
                        string[] purposes = args [i++].Split(sep);
                        if (eku == null)
                        {
                            eku = new ExtendedKeyUsageExtension();
                        }
                        foreach (string purpose in purposes)
                        {
                            eku.KeyPurpose.Add(purpose);
                        }
                        break;

                    case "-h":
                        // pathLength (basicConstraints)
                        // MS use an old basicConstrains (2.5.29.10) which
                        // allows both CA and End-Entity. This is no
                        // more supported with 2.5.29.19.
                        if (bce == null)
                        {
                            bce = new BasicConstraintsExtension();
                            bce.CertificateAuthority = true;
                        }
                        bce.PathLenConstraint = Convert.ToInt32(args [i++]);
                        break;

                    case "-alt":
                        if (alt == null)
                        {
                            string [] dnsNames = File.ReadAllLines(args [i++]);
                            alt = new SubjectAltNameExtension(null, dnsNames, null, null);
                        }
                        break;

                    case "-ic":
                        issuerCertificate = LoadCertificate(args [i++]);
                        issuer            = issuerCertificate.SubjectName;
                        break;

                    case "-in":
                        issuer = args [i++];
                        break;

                    case "-iv":
                        // TODO password
                        PrivateKey pvk = PrivateKey.CreateFromFile(args [i++]);
                        issuerKey = pvk.RSA;
                        break;

                    case "-l":
                        // link (URL)
                        // spcSpAgencyInfo private extension
                        Console.WriteLine("Unsupported option");
                        break;

                    case "-m":
                        // validity period (in months)
                        notAfter = notBefore.AddMonths(Convert.ToInt32(args [i++]));
                        break;

                    case "-nscp":
                        // Netscape's private extensions - NetscapeCertType
                        // BasicContraints - End Entity
                        Console.WriteLine("Unsupported option");
                        break;

                    case "-r":
                        selfSigned = true;
                        break;

                    case "-sc":
                        // subject certificate ? renew ?
                        Console.WriteLine("Unsupported option");
                        break;

                    // Issuer CspParameters options
                    case "-ik":
                        issuerParams.KeyContainerName = args [i++];
                        break;

                    case "-iky":
                        // select a key in the provider
                        string ikn = args [i++].ToLower();
                        switch (ikn)
                        {
                        case "signature":
                            issuerParams.KeyNumber = 0;
                            break;

                        case "exchange":
                            issuerParams.KeyNumber = 1;
                            break;

                        default:
                            issuerParams.KeyNumber = Convert.ToInt32(ikn);
                            break;
                        }
                        break;

                    case "-ip":
                        issuerParams.ProviderName = args [i++];
                        break;

                    case "-ir":
                        switch (args [i++].ToLower())
                        {
                        case "localmachine":
                            issuerParams.Flags = CspProviderFlags.UseMachineKeyStore;
                            break;

                        case "currentuser":
                            issuerParams.Flags = CspProviderFlags.UseDefaultKeyContainer;
                            break;

                        default:
                            Console.WriteLine("Unknown key store for issuer");
                            return(-1);
                        }
                        break;

                    case "-is":
                        Console.WriteLine("Unsupported option");
                        return(-1);

                    case "-iy":
                        issuerParams.ProviderType = Convert.ToInt32(args [i++]);
                        break;

                    // Subject CspParameters Options
                    case "-sk":
                        subjectParams.KeyContainerName = args [i++];
                        break;

                    case "-sky":
                        // select a key in the provider
                        string skn = args [i++].ToLower();
                        switch (skn)
                        {
                        case "signature":
                            subjectParams.KeyNumber = 0;
                            break;

                        case "exchange":
                            subjectParams.KeyNumber = 1;
                            break;

                        default:
                            subjectParams.KeyNumber = Convert.ToInt32(skn);
                            break;
                        }
                        break;

                    case "-sp":
                        subjectParams.ProviderName = args [i++];
                        break;

                    case "-sr":
                        switch (args [i++].ToLower())
                        {
                        case "localmachine":
                            subjectParams.Flags = CspProviderFlags.UseMachineKeyStore;
                            break;

                        case "currentuser":
                            subjectParams.Flags = CspProviderFlags.UseDefaultKeyContainer;
                            break;

                        default:
                            Console.WriteLine("Unknown key store for subject");
                            return(-1);
                        }
                        break;

                    case "-ss":
                        Console.WriteLine("Unsupported option");
                        return(-1);

                    case "-sv":
                        string pvkFile = args [i++];
                        if (File.Exists(pvkFile))
                        {
                            PrivateKey key = PrivateKey.CreateFromFile(pvkFile);
                            subjectKey = key.RSA;
                        }
                        else
                        {
                            PrivateKey key = new PrivateKey();
                            key.RSA = subjectKey;
                            key.Save(pvkFile);
                        }
                        break;

                    case "-sy":
                        subjectParams.ProviderType = Convert.ToInt32(args [i++]);
                        break;

                    // Mono Specific Options
                    case "-p12":
                        p12file = args [i++];
                        p12pwd  = args [i++];
                        break;

                    // Other options
                    case "-?":
                        Help();
                        return(0);

                    case "-!":
                        ExtendedHelp();
                        return(0);

                    default:
                        if (i != args.Length)
                        {
                            Console.WriteLine("ERROR: Unknown parameter");
                            Help();
                            return(-1);
                        }
                        break;
                    }
                }

                // serial number MUST be positive
                if ((sn [0] & 0x80) == 0x80)
                {
                    sn [0] -= 0x80;
                }

                if (selfSigned)
                {
                    if (subject != defaultSubject)
                    {
                        issuer    = subject;
                        issuerKey = subjectKey;
                    }
                    else
                    {
                        subject    = issuer;
                        subjectKey = issuerKey;
                    }
                }

                if (subject == null)
                {
                    throw new Exception("Missing Subject Name");
                }

                X509CertificateBuilder cb = new X509CertificateBuilder(3);
                cb.SerialNumber     = sn;
                cb.IssuerName       = issuer;
                cb.NotBefore        = notBefore;
                cb.NotAfter         = notAfter;
                cb.SubjectName      = subject;
                cb.SubjectPublicKey = subjectKey;
                // extensions
                if (bce != null)
                {
                    cb.Extensions.Add(bce);
                }
                if (eku != null)
                {
                    cb.Extensions.Add(eku);
                }
                if (alt != null)
                {
                    cb.Extensions.Add(alt);
                }
                // signature
                cb.Hash = hashName;
                byte[] rawcert = cb.Sign(issuerKey);

                if (p12file == null)
                {
                    WriteCertificate(fileName, rawcert);
                }
                else
                {
                    PKCS12 p12 = new PKCS12();
                    p12.Password = p12pwd;

                    ArrayList list = new ArrayList();
                    // we use a fixed array to avoid endianess issues
                    // (in case some tools requires the ID to be 1).
                    list.Add(new byte [4] {
                        1, 0, 0, 0
                    });
                    Hashtable attributes = new Hashtable(1);
                    attributes.Add(PKCS9.localKeyId, list);

                    p12.AddCertificate(new X509Certificate(rawcert), attributes);
                    if (issuerCertificate != null)
                    {
                        p12.AddCertificate(issuerCertificate);
                    }
                    p12.AddPkcs8ShroudedKeyBag(subjectKey, attributes);
                    p12.SaveToFile(p12file);
                }
                return(0);
            }
            catch (Exception e) {
                Console.WriteLine("ERROR: " + e.ToString());
                Help();
            }
            return(1);
        }
Пример #27
0
        public CompleteRequestDialog(IServiceProvider serviceProvider, CertificatesFeature feature)
            : base(serviceProvider)
        {
            InitializeComponent();
            cbStore.SelectedIndex = 0;
            if (Environment.OSVersion.Version < Version.Parse("6.2"))
            {
                // IMPORTANT: WebHosting store is available since Windows 8.
                cbStore.Enabled = false;
            }

            if (!Helper.IsRunningOnMono())
            {
                NativeMethods.TryAddShieldToButton(btnOK);
            }

            var container = new CompositeDisposable();

            FormClosed += (sender, args) => container.Dispose();

            container.Add(
                Observable.FromEventPattern <EventArgs>(txtName, "TextChanged")
                .ObserveOn(System.Threading.SynchronizationContext.Current)
                .Subscribe(evt =>
            {
                btnOK.Enabled = !string.IsNullOrWhiteSpace(txtName.Text) &&
                                !string.IsNullOrWhiteSpace(txtPath.Text);
            }));

            container.Add(
                Observable.FromEventPattern <EventArgs>(btnOK, "Click")
                .ObserveOn(System.Threading.SynchronizationContext.Current)
                .Subscribe(evt =>
            {
                if (!File.Exists(txtPath.Text))
                {
                    ShowMessage(
                        string.Format(
                            "There was an error while performing this operation.{0}{0}Details:{0}{0}Could not find file '{1}'.",
                            Environment.NewLine,
                            txtPath.Text),
                        MessageBoxButtons.OK,
                        MessageBoxIcon.Error,
                        MessageBoxDefaultButton.Button1);
                    return;
                }

                var p12File = DialogHelper.GetTempFileName();
                var p12pwd  = "test";
                try
                {
                    // TODO: check administrator permission.
                    var x509     = new X509Certificate2(txtPath.Text);
                    var filename = DialogHelper.GetPrivateKeyFile(x509.Subject);
                    if (!File.Exists(filename))
                    {
                        ShowMessage(
                            string.Format(
                                "There was an error while performing this operation.{0}{0}Details:{0}{0}Could not find private key for '{1}'.",
                                Environment.NewLine,
                                txtPath.Text),
                            MessageBoxButtons.OK,
                            MessageBoxIcon.Error,
                            MessageBoxDefaultButton.Button1);
                        return;
                    }

                    x509.PrivateKey   = PrivateKey.CreateFromFile(filename).RSA;
                    x509.FriendlyName = txtName.Text;
                    var raw           = x509.Export(X509ContentType.Pfx, p12pwd);
                    File.WriteAllBytes(p12File, raw);
                    Item = x509;
                }
                catch (Exception ex)
                {
                    ShowError(ex, string.Empty, false);
                    return;
                }

                Store = cbStore.SelectedIndex == 0 ? "Personal" : "WebHosting";

                try
                {
                    // add certificate
                    using (var process = new Process())
                    {
                        var start       = process.StartInfo;
                        start.Verb      = "runas";
                        start.FileName  = "cmd";
                        start.Arguments = string.Format("/c \"\"{4}\" /f:\"{0}\" /p:{1} /n:\"{2}\" /s:{3}\"",
                                                        p12File,
                                                        p12pwd,
                                                        txtName.Text,
                                                        cbStore.SelectedIndex == 0 ? "MY" : "WebHosting",
                                                        Path.Combine(Environment.CurrentDirectory, "certificateinstaller.exe"));
                        start.CreateNoWindow = true;
                        start.WindowStyle    = ProcessWindowStyle.Hidden;
                        process.Start();
                        process.WaitForExit();
                        File.Delete(p12File);
                        if (process.ExitCode == 0)
                        {
                            DialogResult = DialogResult.OK;
                        }
                        else
                        {
                            MessageBox.Show(process.ExitCode.ToString());
                        }
                    }
                }
                catch (Win32Exception ex)
                {
                    // elevation is cancelled.
                    if (ex.NativeErrorCode != Microsoft.Web.Administration.NativeMethods.ErrorCancelled)
                    {
                        RollbarLocator.RollbarInstance.Error(ex, new Dictionary <string, object> {
                            { "native", ex.NativeErrorCode }
                        });
                        // throw;
                    }
                }
                catch (Exception ex)
                {
                    RollbarLocator.RollbarInstance.Error(ex);
                }
            }));

            container.Add(
                Observable.FromEventPattern <EventArgs>(btnBrowse, "Click")
                .ObserveOn(System.Threading.SynchronizationContext.Current)
                .Subscribe(evt =>
            {
                DialogHelper.ShowOpenFileDialog(txtPath, "*.cer|*.cer|*.*|*.*");
            }));

            container.Add(
                Observable.FromEventPattern <CancelEventArgs>(this, "HelpButtonClicked")
                .ObserveOn(System.Threading.SynchronizationContext.Current)
                .Subscribe(EnvironmentVariableTarget =>
            {
                feature.ShowHelp();
            }));
        }
Пример #28
0
 public void CreateFromFile_Null()
 {
     PrivateKey pvk = PrivateKey.CreateFromFile(null, "password");
 }
Пример #29
0
        // note: makecert creates the private key in the PVK format
        private static AsymmetricAlgorithm GetPrivateKey(X509Certificate certificate, string targetHost)
        {
            PrivateKey key = PrivateKey.CreateFromFile(keyfile);

            return(key.RSA);
        }
Пример #30
0
        // TODO : cleanup and reorganization, as the code below is a almost a direct copypaste from Mono project's Makecert tool.
        internal /* byte[]*/ PKCS12 GenerateCertificate(/*string[] args,*/ bool isHubRootCA, bool isHubCert, string subjectName, string[] alternateDnsNames)
        {
            if (isHubRootCA && isHubCert)
            {
                throw new Exception("incompatible options isHubRootCA & isHubCert");
            }
            Logger.Append("HUBRN", Severity.INFO, "Asked to create " + ((isHubCert)?"hub certificate, ":"") + ((isHubRootCA)?"root CA, ":"") + ((!isHubCert && !isHubRootCA)?" node certificate for '" + subjectName + "'":""));
            string rootKey  = ConfigurationManager.AppSettings["Security.CAKey"];
            string rootCert = ConfigurationManager.AppSettings["Security.CACertificate"];

            byte[]   sn        = Guid.NewGuid().ToByteArray();
            string   issuer    = defaultIssuer;
            DateTime notBefore = DateTime.Now;
            DateTime notAfter  = DateTime.Now.AddYears(5);

            RSA issuerKey = (RSA)RSA.Create();
            //issuerKey.FromXmlString(MonoTestRootAgency);
            RSA subjectKey = (RSA)RSA.Create();

            bool   selfSigned = isHubRootCA;
            string hashName   = "SHA1";

            BasicConstraintsExtension bce     = null;
            ExtendedKeyUsageExtension eku     = null;
            SubjectAltNameExtension   alt     = null;
            string          p12pwd            = null;
            X509Certificate issuerCertificate = null;

            try{
                if (subjectName == null)
                {
                    throw new Exception("Missing Subject Name");
                }
                if (!subjectName.ToLower().StartsWith("cn="))
                {
                    subjectName = "CN=" + subjectName;
                }

                /*if (alternateDnsNames != null){
                 *      alt = new SubjectAltNameExtension(null, alternateDnsNames, null, null);
                 * }*/
                if (!isHubRootCA)
                {
                    issuerCertificate = LoadCertificate(rootCert);
                    issuer            = issuerCertificate.SubjectName;

                    //case "-iv":
                    // TODO password
                    PrivateKey pvk = PrivateKey.CreateFromFile(rootKey);
                    issuerKey = pvk.RSA;
                }

                // Issuer CspParameters options
                if (isHubRootCA)
                {
                    //subjectName = defaultSubject;
                    string pvkFile = rootKey;
                    if (File.Exists(pvkFile))                       // CA key already exists, reuse
                    {
                        PrivateKey key = PrivateKey.CreateFromFile(pvkFile);
                        subjectKey = key.RSA;
                    }
                    else
                    {
                        PrivateKey key = new PrivateKey();
                        key.RSA = subjectKey;
                        key.Save(pvkFile);
                        // save 'the Mother Of All Keys'
                        //WriteHubMotherCert(issuerKey.ToXmlString(true));
                    }
                }
                else
                {
                    p12pwd = "";
                }

                // serial number MUST be positive
                if ((sn [0] & 0x80) == 0x80)
                {
                    sn [0] -= 0x80;
                }

                if (selfSigned)
                {
                    if (subjectName != defaultSubject)
                    {
                        issuer    = subjectName;
                        issuerKey = subjectKey;
                        //issuerKey = Hub.MotherKey;
                    }
                    else
                    {
                        subjectName = issuer;
                        subjectKey  = issuerKey;
                    }
                }

                X509CertificateBuilder cb = new X509CertificateBuilder(3);
                cb.SerialNumber     = sn;
                cb.IssuerName       = issuer;
                cb.NotBefore        = notBefore;
                cb.NotAfter         = notAfter;
                cb.SubjectName      = subjectName;
                cb.SubjectPublicKey = subjectKey;

                // extensions
                if (bce != null)
                {
                    cb.Extensions.Add(bce);
                }
                if (eku != null)
                {
                    cb.Extensions.Add(eku);
                }
                if (alt != null)
                {
                    cb.Extensions.Add(alt);
                }
                // signature
                cb.Hash = hashName;
                byte[] rawcert = cb.Sign(issuerKey);

                if (isHubRootCA)                 // Hub CA
                {
                    WriteCACertificate(rawcert);
                }
                else
                {
                    PKCS12 p12 = new PKCS12();
                    p12.Password = p12pwd;

                    ArrayList list = new ArrayList();
                    // we use a fixed array to avoid endianess issues
                    // (in case some tools requires the ID to be 1).
                    list.Add(new byte [4] {
                        1, 0, 0, 0
                    });
                    Hashtable attributes = new Hashtable(1);
                    attributes.Add(PKCS9.localKeyId, list);

                    p12.AddCertificate(new X509Certificate(rawcert), attributes);
                    if (issuerCertificate != null)
                    {
                        p12.AddCertificate(issuerCertificate);
                    }
                    p12.AddPkcs8ShroudedKeyBag(subjectKey, attributes);

                    /*var x509cert2 = new System.Security.Cryptography.X509Certificates.X509Certificate2();
                     * x509cert2.Import(p12.GetBytes(), "",
                     *      System.Security.Cryptography.X509Certificates.X509KeyStorageFlags.PersistKeySet| System.Security.Cryptography.X509Certificates.X509KeyStorageFlags.Exportable );
                     * return  x509cert2;*/
                    //return p12.GetBytes();
                    return(p12);
                }
                Logger.Append("HUBRN", Severity.INFO, "Created requested key/cert for '" + subjectName + "'.");
            }
            catch (Exception e) {
                Logger.Append("HUBRN", Severity.ERROR, "Error generating certificate for '" + subjectName + "' : " + e.ToString());
            }
            return(null);
        }