Beispiel #1
0
        public static void TestX509Certificate2()
        {
            Console.WriteLine("TestX509Certificate2");

            // Generated using:
            // openssl req -x509 -sha256 -nodes -days 365 -newkey rsa:2048 -keyout private.key -out certificate_pub.crt
            string certificateText = File.ReadAllText("certificate_pub.crt");
            string privateKeyText  = File.ReadAllText("private.key");

            ICertificateProvider provider    = new CertificateFromFileProvider(certificateText, privateKeyText);
            X509Certificate2     certificate = provider.Certificate;

            Console.WriteLine("X509Certificate2:");
            Console.WriteLine(certificate);
            Console.WriteLine();
            Console.WriteLine("PrivateKey:");
            RSACryptoServiceProvider cryptoServiceProvider = provider.PrivateKey;

            ShowRSAProperties(cryptoServiceProvider);

            var xml = XDocument.Parse(RSAExtensions.ToXmlString(cryptoServiceProvider, true));

            Console.WriteLine(xml.ToString());

            // Sign the data
            byte[] hello     = new UTF8Encoding().GetBytes("Hello World");
            byte[] hashValue = cryptoServiceProvider.Encrypt(hello, false);

            // var publicKey = provider.PublicKey;
            byte[] decrypted = cryptoServiceProvider.Decrypt(hashValue, false);
            Console.WriteLine("decrypted: {0}", Encoding.UTF8.GetString(decrypted));
        }
Beispiel #2
0
        public static void GenerateKeys(string publicKeyFile, string privateKeyFile)
        {
            using (var rsa = new RSACryptoServiceProvider((int)KeySizes.SIZE_2048))
            {
                rsa.PersistKeyInCsp = false;

                if (File.Exists(privateKeyFile))
                {
                    File.Delete(privateKeyFile);
                }

                if (File.Exists(publicKeyFile))
                {
                    File.Delete(publicKeyFile);
                }

                string publicKey = RSAExtensions.ToXmlString(rsa, false);
                File.WriteAllText(publicKeyFile, publicKey);
                string privateKey = RSAExtensions.ToXmlString(rsa, true);
                File.WriteAllText(privateKeyFile, privateKey);
            }
        }