예제 #1
0
		public void TestRsaSha1()
		{
			using (Configuration cfg = new Configuration("openssl.cnf"))
			{
				// Test RSA/SHA1 with other SelfSigned method
				BigNumber bn = 0x10001;
				CryptoKey key;

				using (RSA rsa = new RSA())
				{
					rsa.GenerateKeys(2048, bn, OnGenerator, null);
					key = new CryptoKey(rsa);
					// rsa is assigned, we no longer need this instance
				}

				using (var root = X509CertificateAuthority.SelfSigned(
					                  cfg,
					                  new SimpleSerialNumber(),
					                  key,
					                  MessageDigest.SHA1,
					                  "Root1",
					                  DateTime.Now,
					                  TimeSpan.FromDays(365)))
				{
					Console.WriteLine(root.Certificate);
				}
			}
		}
예제 #2
0
		public void TestWithoutCfg() {
			BigNumber bn = 0x10001;
			CryptoKey key;
			using (RSA rsa = new RSA()) {
				rsa.GenerateKeys(2048, bn, OnGenerator, null);
				key = new CryptoKey(rsa);
				// rsa is assigned, we no longer need this instance
			}

			X509V3ExtensionList extList = new X509V3ExtensionList();
			extList.Add(new X509V3ExtensionValue("subjectKeyIdentifier", false, "hash"));
			extList.Add(new X509V3ExtensionValue("authorityKeyIdentifier", false, "keyid:always,issuer:always"));
			extList.Add(new X509V3ExtensionValue("basicConstraints", true, "critical,CA:true"));
			extList.Add(new X509V3ExtensionValue("keyUsage", false, "cRLSign,keyCertSign"));

			using (X509CertificateAuthority root = X509CertificateAuthority.SelfSigned(
				new SimpleSerialNumber(),
				key,
				MessageDigest.SHA1,
				"Root1",
				DateTime.Now,
				TimeSpan.FromDays(365),
				extList)) {
				Console.WriteLine(root.Certificate);
				// Iterate the extensions
				Console.WriteLine("X509v3 Extensions:");
				using (OpenSSL.Core.Stack<X509Extension> ext_stack = root.Certificate.Extensions) {
					foreach (X509Extension ext in ext_stack) {
						Console.WriteLine("Name:{0}, IsCritical:{1}, Value:{2}", ext.Name, ext.IsCritical, ext);
					}
				}
			}
		}
예제 #3
0
 static void Main(string[] args)
 {
     Console.WriteLine("Generating RSA Key ...");
     RSA rsa = new RSA();
     rsa.GenerateKeys(2048, 1, null, null);
     string pem = rsa.PublicKeyAsPEM.Replace("\n", "").Replace("-----BEGIN PUBLIC KEY-----", "").Replace("-----END PUBLIC KEY-----", "");
     byte[] bytes = Convert.FromBase64String(pem);
     Console.WriteLine(Utility.ToHexString(bytes, false));
     Console.ReadLine();
 }
        /// <summary>
        /// Creates a new CryptoKey with public and private keys generated by the
        /// RSA algorithm.
        /// </summary>
        /// <param name="numberOfBits">The bit strength to be used for the RSA algorithm. A value greater than 1024 is recommended.</param>
        /// <returns>A new CryptoKey with both private and public keys generated used the RSA algorithm.</returns>
        public static CryptoKey CreateNewRsaKey(int numberOfBits)
        {
            using (var rsa = new RSA())
            {
                BigNumber exponent = 0x10001; // this needs to be a prime number
                rsa.GenerateKeys(numberOfBits, exponent, OnGenerator, null);

                return new CryptoKey(rsa);
            }
        }
예제 #5
0
        private void button3_Click(object sender, EventArgs e)
        {
            Encoding encoding = Encoding.UTF8;

            using (OpenSSL.Crypto.RSA rsa = new OpenSSL.Crypto.RSA())
            {
                rsa.GenerateKeys(4096, BigNumber.One, null, null);
                privateKey = rsa.PrivateKeyAsPEM;
                publicKey  = rsa.PublicKeyAsPEM;
                MessageBox.Show("publicKey: " + publicKey + "\nprivateKey: " + privateKey);
            }
        }
예제 #6
0
		static TestCipher()
		{
			const int numKeys = 10;
			Keys = new CryptoKey[numKeys];
			for (int i = 0; i < numKeys; i++)
			{
				using (var rsa = new RSA())
				{
					rsa.GenerateKeys(1024, BigNumber.One, null, null);
					Keys[i] = new CryptoKey(rsa);
				}
			}
		}
예제 #7
0
        public void TestGenRSA()
        {
            BigNumber e = null;
            //if (options.IsSet("3"))
            //    e = 3;
            //else if (options.IsSet("f4"))
            //    e = 0x10001;
            e = 0x10001;

            var rsagen = new RSA();
            rsagen.GenerateKeys(2048, e, GeneratorHandler, null);

            Cipher enc = null;
            //if (options.IsSet("des"))
            //    enc = Cipher.DES_CBC;
            //else if (options.IsSet("des3"))
            //    enc = Cipher.DES_EDE3_CBC;
            //else if (options.IsSet("idea"))
            //    enc = Cipher.Idea_CBC;
            //else if (options.IsSet("aes128"))
            //    enc = Cipher.AES_128_CBC;
            //else if (options.IsSet("aes192"))
            //    enc = Cipher.AES_192_CBC;
            //else if (options.IsSet("aes256"))
            //    enc = Cipher.AES_256_CBC;

            string passwd = null;

            using (var bio = BIO.MemoryBuffer())
            {
                rsagen.WritePrivateKey(bio, enc, OnPassword, passwd);

                var outfile = "openssl-rsagen-privatekey.txt";
                if (string.IsNullOrEmpty(outfile))
                    Console.WriteLine(bio.ReadString());
                else
                    File.WriteAllText(outfile, bio.ReadString());
            }

            using (var bio = BIO.MemoryBuffer())
            {
                rsagen.WritePublicKey(bio);

                var outfile = "openssl-rsagen-publickey.txt";
                if (string.IsNullOrEmpty(outfile))
                    Console.WriteLine(bio.ReadString());
                else
                    File.WriteAllText(outfile, bio.ReadString());
            }
        }
예제 #8
0
        private static X509Certificate CreateCertificate()
        {
            BigNumber bn = 0x10001;
            var rsa = new RSA();
            rsa.GenerateKeys(2048, bn, null, null);
            var key = new CryptoKey(rsa);

            var cert = new X509Certificate(
                new SimpleSerialNumber().Next(),
                new X509Name("Mooege"),
                new X509Name("Mooege"),
                key,
                DateTime.Now,
                DateTime.Now + TimeSpan.FromDays(365));

            cert.PrivateKey = key;
            return cert;
        }
예제 #9
0
		X509Certificate CreateCertificate(X509CertificateAuthority ca, string name, Configuration cfg, string section)
		{
			var now = DateTime.Now;
			var future = now + TimeSpan.FromDays(365);

			using (var subject = new X509Name(name))
			using (var rsa = new RSA())
			{
				rsa.GenerateKeys(1024, BigNumber.One, null, null);
				using (var key = new CryptoKey(rsa))
				{
					var request = new X509Request(1, subject, key);
					var cert = ca.ProcessRequest(request, now, future, cfg, section);
					cert.PrivateKey = key;
					return cert;
				}
			}
		}
예제 #10
0
		public void CanCompare()
		{
			using (DSA dsa = new DSA(true))
			{
				using (CryptoKey lhs = new CryptoKey(dsa))
				{
					Assert.AreEqual(lhs, lhs);
					using (CryptoKey rhs = new CryptoKey(dsa))
					{
						Assert.AreEqual(lhs, rhs);
					}

					using (DSA dsa2 = new DSA(true))
					{
						using (CryptoKey other = new CryptoKey(dsa2))
						{
							Assert.IsFalse(lhs == other);
						}
					}
				}
			}

			using (RSA rsa = new RSA())
			{
				rsa.GenerateKeys(1024, BigNumber.One, null, null);
				using (CryptoKey lhs = new CryptoKey(rsa))
				{
					Assert.AreEqual(lhs, lhs);
					using (CryptoKey rhs = new CryptoKey(rsa))
					{
						Assert.AreEqual(lhs, rhs);
					}

					using (RSA rsa2 = new RSA())
					{
						rsa2.GenerateKeys(1024, BigNumber.One, null, null);
						using (CryptoKey other = new CryptoKey(rsa2))
						{
							Assert.IsFalse(lhs == other);
						}
					}
				}
			}
		}
예제 #11
0
		public void CanCompareRSA()
		{
			using (var rsa = new RSA())
			{
				rsa.GenerateKeys(1024, BigNumber.One, null, null);
				using (var lhs = new CryptoKey(rsa))
				{
					Assert.AreEqual(lhs, lhs);
					using (var rhs = new CryptoKey(rsa))
					{
						Assert.AreEqual(lhs, rhs);
					}

					using (var rsa2 = new RSA())
					{
						rsa2.GenerateKeys(1024, BigNumber.One, null, null);
						using (var other = new CryptoKey(rsa2))
						{
							Assert.AreNotEqual(lhs, other);
						}
					}
				}
			}
		}
예제 #12
0
		public void Execute(string[] args)
		{
			try
			{
				options.ParseArguments(args);
			}
			catch (Exception)
			{
				Usage();
				return;
			}

			int bits = 512;
			if (this.options.Arguments.Count == 1)
				bits = Convert.ToInt32(this.options.Arguments[0]);

			BigNumber e = null;
			if (options.IsSet("3"))
				e = 3;
			else if (options.IsSet("f4"))
				e = 0x10001;

			Console.Error.WriteLine("Generating RSA private key, {0} bit long modulus", bits);

			RSA rsa = new RSA();
			rsa.GenerateKeys(bits, e, Program.OnGenerator, null);

			Console.Error.WriteLine("e is {0} (0x{1})", e.ToDecimalString(), e.ToHexString());

			Cipher enc = null;
			if (options.IsSet("des"))
				enc = Cipher.DES_CBC;
			else if (options.IsSet("des3"))
				enc = Cipher.DES_EDE3_CBC;
			else if (options.IsSet("idea"))
				enc = Cipher.Idea_CBC;
			else if (options.IsSet("aes128"))
				enc = Cipher.AES_128_CBC;
			else if (options.IsSet("aes192"))
				enc = Cipher.AES_192_CBC;
			else if (options.IsSet("aes256"))
				enc = Cipher.AES_256_CBC;

			using (BIO bio = BIO.MemoryBuffer())
			{
				rsa.WritePrivateKey(bio, enc, Program.OnPassword, this.options["passout"]);

				string outfile = this.options["out"] as string;
				if (string.IsNullOrEmpty(outfile))
					Console.WriteLine(bio.ReadString());
				else
					File.WriteAllText(outfile, bio.ReadString());
			}
		}
예제 #13
0
		public void CanCreateFromRSA()
		{
			using (RSA rsa = new RSA())
			{
				rsa.GenerateKeys(1024, BigNumber.One, null, null);
				using (CryptoKey key = new CryptoKey(rsa))
				{
					Assert.AreEqual(CryptoKey.KeyType.RSA, key.Type);
					Assert.AreEqual(rsa.Size, key.Size);
				}
			}
		}
예제 #14
0
		public void CanCreateFromRSA()
		{
			using (var rsa = new RSA())
			{
				rsa.GenerateKeys(1024, BigNumber.One, null, null);
				using (var key = new CryptoKey(rsa))
				{
					Assert.AreEqual(CryptoKey.KeyType.RSA, key.Type);
					Assert.AreEqual(rsa.Size, key.Size);
					Assert.AreEqual(rsa.Handle, key.GetRSA().Handle);
				}

				using (var key = new CryptoKey())
				{
					key.Assign(rsa);
					Assert.AreEqual(rsa.Handle, key.GetRSA().Handle);
				}
			}
		}
예제 #15
0
        public static RsaKeyPair GenerateRsaPrivateKey(int bits = 2048, BigNumber e = null,
                RsaKeyGeneratorCallback cb = null, object cbArg = null)
        {
            if (e == null)
                e = E_F4;

            using (var rsa = new RSA())
            {
                BigNumber.GeneratorHandler cbWrapper = null;
                if (cb != null)
                    cbWrapper = (x,y,z) => cb(x,y,z);

                Cipher enc = null;
                string pwd = null;
                PasswordHandler pwdCb = null;
                // If we choose to encrypt:
                //      Cipher.DES_CBC;
                //      Cipher.DES_EDE3_CBC;
                //      Cipher.Idea_CBC;
                //      Cipher.AES_128_CBC;
                //      Cipher.AES_192_CBC;
                //      Cipher.AES_256_CBC;
                //   and pwd != null || pwdCb != null
                // We can use a pwdCb to get a password interactively or we can
                // simply pass in a fixed password string (no cbPwd, just pwd)
                if (pwd != null)
                    pwdCb = DefaultPasswordHandler;

                // Ref:  http://openssl.org/docs/manmaster/crypto/RSA_generate_key_ex.html
                rsa.GenerateKeys(bits, e, cbWrapper, cbArg);

                using (var bio = BIO.MemoryBuffer())
                {
                    // Ref:  http://openssl.org/docs/manmaster/crypto/PEM_write_bio_RSAPrivateKey.html
                    rsa.WritePrivateKey(bio, enc, pwdCb, pwd);
                    return new RsaKeyPair(bits, e.ToHexString(), bio.ReadString());
                }
            }
        }
예제 #16
0
        public override PrivateKey GeneratePrivateKey(PrivateKeyParams pkp)
        {
            var rsaPkParams = pkp as RsaPrivateKeyParams;
            var ecPkParams  = pkp as EcPrivateKeyParams;

            if (rsaPkParams != null)
            {
                int bits;
                // Bits less than 1024 are weak Ref: http://openssl.org/docs/manmaster/crypto/RSA_generate_key_ex.html
                if (rsaPkParams.NumBits < RSA_BITS_MINIMUM)
                {
                    bits = RSA_BITS_DEFAULT;
                }
                else
                {
                    bits = rsaPkParams.NumBits;
                }

                BigNumber e;
                if (string.IsNullOrEmpty(rsaPkParams.PubExp))
                {
                    e = RSA_E_F4;
                }
                else if (rsaPkParams.PubExp.StartsWith("0x", StringComparison.OrdinalIgnoreCase))
                {
                    e = BigNumber.FromHexString(rsaPkParams.PubExp);
                }
                else
                {
                    e = BigNumber.FromDecimalString(rsaPkParams.PubExp);
                }

                using (var rsa = new OSSL_RSA())
                {
                    BigNumber.GeneratorHandler cbWrapper = null;
                    if (rsaPkParams.Callback != null)
                    {
                        cbWrapper = (x, y, z) => rsaPkParams.Callback(x, y, z);
                    }

                    Cipher          enc   = null;
                    string          pwd   = null;
                    PasswordHandler pwdCb = null;
                    // If we choose to encrypt:
                    //      Cipher.DES_CBC;
                    //      Cipher.DES_EDE3_CBC;
                    //      Cipher.Idea_CBC;
                    //      Cipher.AES_128_CBC;
                    //      Cipher.AES_192_CBC;
                    //      Cipher.AES_256_CBC;
                    //   and pwd != null || pwdCb != null
                    // We can use a pwdCb to get a password interactively or we can
                    // simply pass in a fixed password string (no cbPwd, just pwd)
                    if (pwd != null)
                    {
                        pwdCb = DefaultPasswordHandler;
                    }

                    // Ref:  http://openssl.org/docs/manmaster/crypto/RSA_generate_key_ex.html
                    rsa.GenerateKeys(bits, e, cbWrapper, rsaPkParams.CallbackArg);

                    using (var bio = BIO.MemoryBuffer())
                    {
                        // Ref:  http://openssl.org/docs/manmaster/crypto/PEM_write_bio_RSAPrivateKey.html
                        rsa.WritePrivateKey(bio, enc, pwdCb, pwd);
                        return(new RsaPrivateKey(bits, e.ToHexString(), bio.ReadString()));
                    }
                }
            }
            else if (ecPkParams != null)
            {
                throw new NotImplementedException("EC private keys have not yet been implemented");

                //var curveName = Asn1Object.FromShortName("P-256");
                ////var curveName = new Asn1Object("P-256");
                //using (var ec =OpenSSL.Crypto.EC.Key.FromCurveName(curveName))
                //{
                //    ec.GenerateKey();
                //}
            }
            else
            {
                throw new NotSupportedException("unsupported private key parameter type");
            }
        }