Exemplo n.º 1
0
 private static string ConvertPrivateKeyToPem(AsymmetricKeyParameter privateKey)
 {
     using (var stringWriter = new StringWriter())
     {
         var pkcsgen   = new Pkcs8Generator(privateKey);
         var pemwriter = new PemWriter(stringWriter);
         pemwriter.WriteObject(pkcsgen.Generate());
         return(stringWriter.ToString());
     }
 }
        public static void GenerateKeyPair(out string publicKey, out char[] privateKey)
        {
            try
            {
                // Construct the RSACryptoServiceProvider object
                RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(2048);

                // Extract the public/private key pair
                var rsaKeyPair = DotNetUtilities.GetRsaKeyPair(rsa);

                // Extract the private key
                var pkcs8Gen = new Pkcs8Generator(rsaKeyPair.Private);
                var pemObj   = pkcs8Gen.Generate();

                MemoryStream memoryStream = new MemoryStream();
                TextWriter   streamWriter = new StreamWriter(memoryStream);
                PemWriter    pemWriter    = new PemWriter(streamWriter);
                pemWriter.WriteObject(pemObj);
                streamWriter.Flush();

                // Extract byte array from memory stream
                byte[] bytearray = memoryStream.GetBuffer();

                // Convert byte array into char array
                privateKey = Encoding.ASCII.GetChars(bytearray);

                // Clear byte array
                Array.Clear(bytearray, 0, bytearray.Length);

                // Dispose stream writer and memory stream
                streamWriter.Dispose();
                memoryStream.Dispose();

                // Extract the public key
                TextWriter stringWriter = new StringWriter();
                pemWriter = new PemWriter(stringWriter);
                pemWriter.WriteObject(rsaKeyPair.Public);
                stringWriter.Flush();
                publicKey = stringWriter.ToString();

                // Display the extracted public key
                Console.WriteLine("public key, {0}", publicKey);

                // Display the extracted private key
                foreach (char ch in privateKey)
                {
                    Console.Write(ch);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }
Exemplo n.º 3
0
        private static string GeneratePrivateKey(AsymmetricKeyParameter key)
        {
            var builder = new StringBuilder();

            using (var writer = new StringWriter(builder))
            {
                var pkcs8Gen = new Pkcs8Generator(key);
                var pemObj   = pkcs8Gen.Generate();

                var pemWriter = new PemWriter(writer);
                pemWriter.WriteObject(pemObj);
            }

            return(builder.ToString());
        }
Exemplo n.º 4
0
        /// <summary>
        /// Save a private key in an encrypted PKCS#8 object
        /// </summary>
        /// <param name="privateKey">Private key value</param>
        /// <param name="password">Password for encrypt</param>
        /// <returns>PKCS#8 object</returns>
        internal static string SaveP8(AsymmetricKeyParameter privateKey, string password)
        {
            // Use the FIPS-140 system prng
            SecureRandom random = new SecureRandom(new CryptoApiRandomGenerator());

            // Build PKCS#8
            Pkcs8Generator p8 = new Pkcs8Generator(privateKey, "PBEWITHSHA256AND128BITAES-CBC-BC");

            p8.Password       = password.ToCharArray();
            p8.SecureRandom   = random;
            p8.IterationCount = 2048;
            PemObject pem = p8.Generate();

            return(pem.Content.ToString());
        }
Exemplo n.º 5
0
        /// <summary>
        /// 读取pfx证书,并将密钥存储为PKCS#8格式
        /// </summary>
        /// <param name="pfxFileName"></param>
        /// <param name="password"></param>
        public static void ConvertPfxToPkcs8(string pfxFileName, string password)
        {
            var certificate = ReadX509Certificate(pfxFileName, password);
            var rsa         = RSA.Create();

            rsa.FromXmlString(certificate.PrivateKey.ToXmlString(true));

            var bcKeyPair = DotNetUtilities.GetRsaKeyPair(rsa);
            var pkcs8Gen  = new Pkcs8Generator(bcKeyPair.Private);
            var pemObj    = pkcs8Gen.Generate();
            var pkcs8Out  = new StreamWriter(@"e:\privkey.pk8", false);
            var pemWriter = new PemWriter(pkcs8Out);

            pemWriter.WriteObject(pemObj);
            pkcs8Out.Close();
        }
Exemplo n.º 6
0
        //
        // Bouncy Castle PKCS#8 Formater
        // Output is the same as this OpenSSL command:
        // openssl pkcs12 -in certname.pfx -nocerts -out key.pem -nodes
        //
        private string GetPkcs8Format(RSACryptoServiceProvider csp)
        {
            var rsaParams = csp.ExportParameters(true);
            var keyPair   = DotNetUtilities.GetRsaKeyPair(rsaParams);
            var pkcs8Gen  = new Pkcs8Generator(keyPair.Private);
            var pemObj    = pkcs8Gen.Generate();
            var sb        = new StringBuilder();

            using (var pkcs8Out = new StringWriter(sb))
            {
                var pemWriter = new PemWriter(pkcs8Out);
                pemWriter.WriteObject(pemObj);
            }

            return(sb.ToString());
        }
Exemplo n.º 7
0
        /// <summary>
        ///     Generates a PKCS private key from the PowerRSA object
        /// </summary>
        /// <param name="prsa"></param>
        /// <returns></returns>
        public static string ConvertPrivateKeyToPKCS(PowerRSA prsa)
        {
            var rsa = RSA.Create();

            rsa.FromXmlString(prsa.PrivateKey);
            var    bcKeyPair = DotNetUtilities.GetRsaKeyPair(rsa);
            var    pkcs8Gen  = new Pkcs8Generator(bcKeyPair.Private);
            var    pemObj    = pkcs8Gen.Generate();
            string outputPem;

            using (var sw = new StringWriter())
            {
                var pkcs8Out  = sw;
                var pemWriter = new PemWriter(pkcs8Out);
                pemWriter.WriteObject(pemObj);
                pkcs8Out.Close();
                outputPem = sw.ToString();
            }
            return(outputPem);
        }
Exemplo n.º 8
0
        public static void Convert(string privXmlFilename, string privPkcs8Filename)
        {
            StringBuilder sb = new StringBuilder();
            string        line;
            var           xmlIn = new StreamReader(privXmlFilename);

            while ((line = xmlIn.ReadLine()) != null)
            {
                sb.Append(line);
            }
            var xmlKey = sb.ToString();
            var rsa    = RSA.Create();

            rsa.FromXmlString(xmlKey);
            var bcKeyPair = DotNetUtilities.GetRsaKeyPair(rsa);
            var pkcs8Gen  = new Pkcs8Generator(bcKeyPair.Private);
            var pemObj    = pkcs8Gen.Generate();
            var pkcs8Out  = new StreamWriter(privPkcs8Filename, false);
            var pemWriter = new PemWriter(pkcs8Out);

            pemWriter.WriteObject(pemObj);
            pkcs8Out.Close();
        }
Exemplo n.º 9
0
        /// <summary>
        /// Exports the key into a supported key format.
        /// </summary>
        public byte[] Export(PkiEncodingFormat format, char[] password = null)
        {
            switch (format)
            {
            case PkiEncodingFormat.Pem:
                using (var sw = new StringWriter())
                {
                    object pemObject = NativeKey;
                    if (IsPrivate && password != null)
                    {
                        var pkcs8Gen = new Pkcs8Generator(NativeKey,
                                                          Pkcs8Generator.PbeSha1_3DES);
                        pkcs8Gen.Password = password;
                        pemObject         = pkcs8Gen.Generate();
                    }
                    var pemWriter = new PemWriter(sw);
                    pemWriter.WriteObject(pemObject);
                    return(Encoding.UTF8.GetBytes(sw.GetStringBuilder().ToString()));
                }

            case PkiEncodingFormat.Der:
                if (IsPrivate)
                {
                    var keyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(NativeKey);
                    return(keyInfo.GetDerEncoded());
                }
                else
                {
                    var keyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(NativeKey);
                    return(keyInfo.GetDerEncoded());
                }

            default:
                throw new NotSupportedException();
            }
        }
Exemplo n.º 10
0
        static public AppData GenerateRSAPrivateKey(RSAKeySize strength, string password, int iteration, Label label, IDispatcher dispatcher)
        {
            try
            {
                IDictionary attrs = new Hashtable
                {
                    { X509Name.CN, "commonname" },
                    { X509Name.O, "organization" },
                    { X509Name.OU, "organizationalUnit" },
                    { X509Name.L, "locality" },
                    { X509Name.ST, "state" },
                    { X509Name.C, "countryIso2Characters" },
                    { X509Name.EmailAddress, "emailAddress" }
                };

                UpdateStatus("1 of 16 Completed!\nCreating X509", "", label, dispatcher);
                X509Name subject = new X509Name(new ArrayList(attrs.Keys), attrs);

                UpdateStatus("2 of 16 Completed!\n1 of 3 RSA Key Pair\nInitializing", "X509 Generated", label, dispatcher);
                RsaKeyPairGenerator rsa = new RsaKeyPairGenerator();

                UpdateStatus("3 of 16 Completed!\n2 of 3 RSA Key Pair\nRandomizing", "", label, dispatcher);
                rsa.Init(new KeyGenerationParameters(GetSecureRandom(), (int)strength));

                UpdateStatus("4 of 16 Completed!\n3 of 3 RSA Key Pair\nGenerating", "Randomizing Done", label, dispatcher);
                AsymmetricCipherKeyPair asym = rsa.GenerateKeyPair();

                UpdateStatus("5 of 16 Completed!\n1 of 4 Encrypting RSA Key Pair: Initalizing", "RSA Keys Created", label, dispatcher);
                var generator = new Pkcs8Generator(asym.Private, Pkcs8Generator.PbeSha1_RC4_128);
                generator.IterationCount = iteration;

                UpdateStatus("6 of 16 Completed!\n2 of 4 Encrypting RSA Key Pair: Randomize", "", label, dispatcher);
                generator.SecureRandom = GetSecureRandom();

                UpdateStatus("7 of 16 Completed!\n3 of 4 Encrypting RSA Key Pair: Hashing", "Randomize Done", label, dispatcher);
                generator.Password = Hash512Iterate(password.ToByteArray(), iteration).ToBase64().ToCharArray();

                UpdateStatus("8 of 16 Completed!\n4 of 4 Encrypting RSA Key Pair: Finalizing", "Hashing Done", label, dispatcher);
                var pem = generator.Generate();

                string SecurePrivateKey = ConvertRSAPemToString(pem);

                UpdateStatus("9 of 16 Completed!\nStoring Encrypted RSA Key Pair", "RSA Key Pair Encrypted", label, dispatcher);
                AppData appData = new AppData
                {
                    RSAPrivateKey = SecurePrivateKey,
                    RSAPublicKey  = StringBuilder(asym, KeyType.PublicKey),
                };

                int id = App.AppDatabase.SaveDataAsync(appData).Result;
                if (id != 1)
                {
                    throw new Exception("GenerateRSAKey: RSA Save Key filed. id != 1");
                }

                appData.ID = 1;

                UpdateStatus("10 of 16 Completed!\nLoading RSA Key Pair", "RSA Key Pair Stored", label, dispatcher);

                if (!LoadRSAKey(password, iteration))
                {
                    throw new Exception("Generate KeyPair: Could not load RSA Keys");
                }

                UpdateStatus("11 of 16 Completed!\nCreating PKCS#10 CSR", "RSA Keys Loaded", label, dispatcher);

                Asn1SignatureFactory       signatureFactory = new Asn1SignatureFactory(PkcsObjectIdentifiers.Sha512WithRsaEncryption.Id, asym.Private);
                Pkcs10CertificationRequest csr = new Pkcs10CertificationRequest(signatureFactory, subject, asym.Public, null);
                appData.CSR = StringBuilder(csr);

                UpdateStatus("12 of 16 Completed!\n1 of 4 AES Tasks: Creating Seed", "PKCS#10 CSR Created", label, dispatcher);
                appData.Seed = GenerateSeed(false).seed;

                UpdateStatus("13 of 16 Completed!\n2 of 4 AES Tasks: Creating Salt", "AES Seed Created", label, dispatcher);
                appData.Salt = GenerateSalt(false).salt;

                UpdateStatus("14 of 16 Completed!\n3 of 4 AES Tasks: Encrypting Iterations", "AES Salt Created", label, dispatcher);
                appData.Iterations = RSAEncrypt(iteration.ToString());

                UpdateStatus("15 of 16 Completed!\n4 of 4 AES Tasks: Encrypting Certs", "Iterations Encrypted", label, dispatcher);
                appData = AESEncrypt(appData) as AppData;
                if (appData == null)
                {
                    throw new Exception("AES Encryption Failed during Key Generation");
                }

                UpdateStatus("16 of 16 Completed!\nFinishing up", "", label, dispatcher);
                App.AppDatabase.SaveDataAsync(appData).Wait();

                return(appData);
            }
            catch (Exception e)
            {
                FileHelper.WriteFile(ErrorHelper.FormatError(e), FileHelper.ErrorPath, true);
                return(null);
            }
        }
Exemplo n.º 11
0
        // Adapted from:
        // - https://stackoverflow.com/a/27659151/5302680
        // - https://stackoverflow.com/q/21937369/5302680
        public static RSAKey Generate(int strength = 4096, string passPhrase = null)
        {
            try
            {
                RSAKey result = new RSAKey();
                IAsymmetricCipherKeyPairGenerator gen;
                KeyGenerationParameters           param;
                gen   = new RsaKeyPairGenerator();
                param = new RsaKeyGenerationParameters(
                    BigInteger.ValueOf(3L),
                    new SecureRandom(),
                    strength,
                    80
                    );
                gen.Init(param);
                AsymmetricCipherKeyPair pair = gen.GenerateKeyPair();
                using (TextWriter textWriter = new StringWriter())
                {
                    PemWriter wr = new PemWriter(textWriter);
                    if (passPhrase != null)
                    {
                        var encryptor = new Pkcs8Generator(pair.Private, Pkcs8Generator.PbeSha1_3DES);
                        encryptor.IterationCount = 80;
                        encryptor.Password       = passPhrase.ToCharArray();
                        var pem = encryptor.Generate();
                        wr.WriteObject(pem);
                    }
                    else
                    {
                        wr.WriteObject(pair.Private);
                    }
                    wr.Writer.Flush();
                    result.PrivatePEM = textWriter.ToString();
                }

                using (TextWriter textWriter = new StringWriter())
                {
                    PemWriter wr = new PemWriter(textWriter);
                    wr.WriteObject(pair.Public);
                    wr.Writer.Flush();

                    result.PublicPEM = textWriter.ToString();
                }

                using (StringReader sr = new StringReader(result.PublicPEM))
                {
                    PemReader        reader       = new PemReader(sr);
                    RsaKeyParameters r            = (RsaKeyParameters)reader.ReadObject();
                    byte[]           sshrsa_bytes = Encoding.Default.GetBytes("ssh-rsa");
                    byte[]           n            = r.Modulus.ToByteArray();
                    byte[]           e            = r.Exponent.ToByteArray();

                    string buffer64;
                    using (MemoryStream ms = new MemoryStream()){
                        ms.Write(ToBytes(sshrsa_bytes.Length), 0, 4);
                        ms.Write(sshrsa_bytes, 0, sshrsa_bytes.Length);
                        ms.Write(ToBytes(e.Length), 0, 4);
                        ms.Write(e, 0, e.Length);
                        ms.Write(ToBytes(n.Length), 0, 4);
                        ms.Write(n, 0, n.Length);
                        ms.Flush();
                        buffer64 = Convert.ToBase64String(ms.ToArray());
                    }

                    result.PublicSSH = string.Format(
                        "ssh-rsa {0} {1}@{2}@{3}",
                        buffer64,
                        "PEMEncrypt",
                        Environment.UserName,
                        Environment.MachineName);
                }

                return(result);
            }
            catch (Org.BouncyCastle.Crypto.CryptoException ex)
            {
                throw ex;
            }
        }