Exemplo n.º 1
0
 /// <summary>
 /// Initializes a new instance of the <see cref="KeyGenerator"/> class
 /// with the specified key size.
 /// </summary>
 /// <remarks>Following key sizes are supported:
 /// - 192
 /// - 224
 /// - 239
 /// - 256 (default)
 /// - 384
 /// - 521</remarks>
 /// <param name="keySize">The key size.</param>
 public KeyGenerator(int keySize)
 {
     var secureRandom = SecureRandom.GetInstance("SHA256PRNG");
     var keyParams = new KeyGenerationParameters(secureRandom, keySize);
     keyGenerator = new ECKeyPairGenerator();
     keyGenerator.Init(keyParams);
 }
Exemplo n.º 2
0
 // TODO: We are not using key containers properly, this code is not secure.
 public static AsymmetricCipherKeyPair GenerateThaliAcceptablePublicPrivateKeyPair()
 {
     var keyGenerationParameters = new KeyGenerationParameters(new SecureRandom(new CryptoApiRandomGenerator()), KeySizeInBits);
     var rsaKeyPairGenerator = new RsaKeyPairGenerator();
     rsaKeyPairGenerator.Init(keyGenerationParameters);
     var keyPair = rsaKeyPairGenerator.GenerateKeyPair();
     return keyPair;
 }
Exemplo n.º 3
0
        private static AsymmetricCipherKeyPair GenerateKeyPair()
        {
            var secureRandom = new SecureRandom(new DigestRandomGenerator(new Sha512Digest()));
            var keyGenerationParameters = new KeyGenerationParameters(secureRandom, RsaKeySize);

            var keyPairGenerator = new RsaKeyPairGenerator();
            keyPairGenerator.Init(keyGenerationParameters);
            return keyPairGenerator.GenerateKeyPair();
        }
		/**
		 * initialise the key generator.
		 *
		 * @param param the parameters to be used for key generation
		 */
		public void Init(
			KeyGenerationParameters parameters)
		{
			if (parameters == null)
				throw new ArgumentNullException("parameters");

			this.uninitialised = false;

			engineInit(parameters);
		}
Exemplo n.º 5
0
        public static AsymmetricCipherKeyPair GetKeyPair()
        {
            var randomGenerator = new CryptoApiRandomGenerator();
            var secureRandom = new SecureRandom(randomGenerator);
            var keyGenerationParameters = new KeyGenerationParameters(secureRandom, 2048);

            var keyPairGenerator = new RsaKeyPairGenerator();
            keyPairGenerator.Init(keyGenerationParameters);
            return keyPairGenerator.GenerateKeyPair();
        }
Exemplo n.º 6
0
        public void Init(
            KeyGenerationParameters parameters)
        {
            if (parameters is ECKeyGenerationParameters)
            {
                ECKeyGenerationParameters ecP = (ECKeyGenerationParameters) parameters;

                this.publicKeyParamSet = ecP.PublicKeyParamSet;
                this.parameters = ecP.DomainParameters;
            }
            else
            {
                DerObjectIdentifier oid;
                switch (parameters.Strength)
                {
                    case 192:
                        oid = X9ObjectIdentifiers.Prime192v1;
                        break;
                    case 224:
                        oid = SecObjectIdentifiers.SecP224r1;
                        break;
                    case 239:
                        oid = X9ObjectIdentifiers.Prime239v1;
                        break;
                    case 256:
                        oid = X9ObjectIdentifiers.Prime256v1;
                        break;
                    case 384:
                        oid = SecObjectIdentifiers.SecP384r1;
                        break;
                    case 521:
                        oid = SecObjectIdentifiers.SecP521r1;
                        break;
                    default:
                        throw new InvalidParameterException("unknown key size.");
                }

                // Set this to make the SubjectPublicKeyInfo contain a named curve
                // Without it, the SPKI contains explicit curve parameters
                publicKeyParamSet = oid;

                X9ECParameters ecps = FindECCurveByOid(oid);

                this.parameters = new ECDomainParameters(
                    ecps.Curve, ecps.G, ecps.N, ecps.H, ecps.GetSeed());
            }

            this.random = parameters.Random;

            if (this.random == null)
            {
                this.random = new SecureRandom();
            }
        }
		public void Init(
			KeyGenerationParameters parameters)
        {
			if (parameters == null)
				throw new ArgumentNullException("parameters");

			// Note: If we start accepting instances of KeyGenerationParameters,
			// must apply constraint checking on strength (see DsaParametersGenerator.Init)

			this.param = (DsaKeyGenerationParameters) parameters;
        }
Exemplo n.º 8
0
        public static byte[] GenerateKey()
        {
            SecureRandom sr = new SecureRandom();

            KeyGenerationParameters kgp = new KeyGenerationParameters(sr, keySize);

            CipherKeyGenerator kg = new CipherKeyGenerator();
            kg.Init(kgp);

            return kg.GenerateKey();
        }
Exemplo n.º 9
0
        public static X509Certificate2 GenerateSelfSignedCert()
        {
            var randomGenerator = new CryptoApiRandomGenerator();
            var random = new SecureRandom(randomGenerator);
            var certificateGenerator = new X509V3CertificateGenerator();
            var serialNumber =
            BigIntegers.CreateRandomInRange(
                BigInteger.One, BigInteger.ValueOf(Int64.MaxValue), random);
            certificateGenerator.SetSerialNumber(serialNumber);
            const string signatureAlgorithm = "SHA1WithRSA";
            certificateGenerator.SetSignatureAlgorithm(signatureAlgorithm);
            var subjectDN = new X509Name("CN=simpletorrent");
            var issuerDN = subjectDN;
            certificateGenerator.SetIssuerDN(issuerDN);
            certificateGenerator.SetSubjectDN(subjectDN);
            var notBefore = DateTime.UtcNow.Date.AddHours(-24);
            var notAfter = notBefore.AddYears(1000);
            certificateGenerator.SetNotBefore(notBefore);
            certificateGenerator.SetNotAfter(notAfter);
            const int strength = 4096;
            var keyGenerationParameters = new KeyGenerationParameters(random, strength);

            var keyPairGenerator = new RsaKeyPairGenerator();
            keyPairGenerator.Init(keyGenerationParameters);
            var subjectKeyPair = keyPairGenerator.GenerateKeyPair();

            certificateGenerator.SetPublicKey(subjectKeyPair.Public);

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

            var store = new Pkcs12Store();
            string friendlyName = certificate.SubjectDN.ToString();
            var certificateEntry = new X509CertificateEntry(certificate);
            store.SetCertificateEntry(friendlyName, certificateEntry);

            store.SetKeyEntry(friendlyName, new AsymmetricKeyEntry(subjectKeyPair.Private), new[] { certificateEntry });

               string password = "******";

            var stream = new MemoryStream();
            store.Save(stream, password.ToCharArray(), random);

            //mono bug #1660 fix -> convert to definite-length encoding
            byte[] pfx = Pkcs12Utilities.ConvertToDefiniteLength(stream.ToArray(), password.ToCharArray());

            var convertedCertificate =
                new X509Certificate2(
                    pfx, password,
                    X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable);

            return convertedCertificate;
        }
        /**
         * initialise the key generator.
         *
         * @param param the parameters to be used for key generation
         */
        public void Init(
            KeyGenerationParameters parameters)
        {
            if (parameters == null)
            {
                throw new ArgumentNullException("parameters");
            }

            this.uninitialised = false;

            engineInit(parameters);
        }
Exemplo n.º 11
0
		public void Init(
            KeyGenerationParameters parameters)
        {
			if (parameters is ECKeyGenerationParameters)
			{
				ECKeyGenerationParameters ecP = (ECKeyGenerationParameters) parameters;

				if (ecP.PublicKeyParamSet != null)
				{
					if (algorithm != "ECGOST3410")
						throw new ArgumentException("parameters invalid for algorithm: " + algorithm, "parameters");

					this.publicKeyParamSet = ecP.PublicKeyParamSet;
				}

				this.parameters = ecP.DomainParameters;
			}
			else
			{
				DerObjectIdentifier oid;
				switch (parameters.Strength)
				{
					case 192:
						oid = X9ObjectIdentifiers.Prime192v1;
						break;
					case 224:
						oid = SecObjectIdentifiers.SecP224r1;
						break;
					case 239:
						oid = X9ObjectIdentifiers.Prime239v1;
						break;
					case 256:
						oid = X9ObjectIdentifiers.Prime256v1;
						break;
					case 384:
						oid = SecObjectIdentifiers.SecP384r1;
						break;
					case 521:
						oid = SecObjectIdentifiers.SecP521r1;
						break;
					default:
						throw new InvalidParameterException("unknown key size.");
				}

				X9ECParameters ecps = X962NamedCurves.GetByOid(oid);

				this.parameters = new ECDomainParameters(
					ecps.Curve, ecps.G, ecps.N, ecps.H, ecps.GetSeed());
			}

			this.random = parameters.Random;
		}
Exemplo n.º 12
0
		public void Init(
            KeyGenerationParameters parameters)
        {
			if (parameters is RsaKeyGenerationParameters)
			{
				this.param = (RsaKeyGenerationParameters)parameters;
			}
			else
			{
				this.param = new RsaKeyGenerationParameters(
					DefaultPublicExponent, parameters.Random, parameters.Strength, DefaultTests);
			}
        }
Exemplo n.º 13
0
		public void Init(
            KeyGenerationParameters parameters)
        {
			if (parameters is ECKeyGenerationParameters)
			{
				ECKeyGenerationParameters ecP = (ECKeyGenerationParameters) parameters;

				this.publicKeyParamSet = ecP.PublicKeyParamSet;
				this.parameters = ecP.DomainParameters;
			}
			else
			{
				DerObjectIdentifier oid;
				switch (parameters.Strength)
				{
					case 192:
						oid = X9ObjectIdentifiers.Prime192v1;
						break;
					case 224:
						oid = SecObjectIdentifiers.SecP224r1;
						break;
					case 239:
						oid = X9ObjectIdentifiers.Prime239v1;
						break;
					case 256:
						oid = X9ObjectIdentifiers.Prime256v1;
						break;
					case 384:
						oid = SecObjectIdentifiers.SecP384r1;
						break;
					case 521:
						oid = SecObjectIdentifiers.SecP521r1;
						break;
					default:
						throw new InvalidParameterException("unknown key size.");
				}

				X9ECParameters ecps = FindECCurveByOid(oid);

				this.parameters = new ECDomainParameters(
					ecps.Curve, ecps.G, ecps.N, ecps.H, ecps.GetSeed());
			}

			this.random = parameters.Random;
		}
		/*
		 * (non-Javadoc)
		 *
		 * @see org.bouncycastle.crypto.AsymmetricCipherKeyPairGenerator#init(org.bouncycastle.crypto.KeyGenerationParameters)
		 */
		public void Init(KeyGenerationParameters parameters)
		{
			this.param = (NaccacheSternKeyGenerationParameters)parameters;
		}
Exemplo n.º 15
0
		/*
		* Constructor, that takes the arguments appropriate for
		* processing the command line directives.
		*/
		public DesExample(
			string	infile,
			string	outfile,
			string	keyfile,
			bool	encrypt)
		{
			/* 
			* First, determine that infile & keyfile exist as appropriate.
			*
			* This will also create the BufferedInputStream as required
			* for reading the input file.  All input files are treated
			* as if they are binary, even if they contain text, it's the
			* bytes that are encrypted.
			*/
			this.encrypt = encrypt;
			try
			{
				inStr = File.OpenRead(infile);
			}
			catch (FileNotFoundException e)
			{
				Console.Error.WriteLine("Input file not found ["+infile+"]");
				throw e;
			}

			try
			{
				outStr = File.Create(outfile);
			}
			catch (IOException e)
			{
				Console.Error.WriteLine("Output file not created ["+outfile+"]");
				throw e;
			}

			if (encrypt)
			{
				try
				{
					/*
					* The process of creating a new key requires a 
					* number of steps.
					*
					* First, create the parameters for the key generator
					* which are a secure random number generator, and
					* the length of the key (in bits).
					*/
					SecureRandom sr = new SecureRandom();

					KeyGenerationParameters kgp = new KeyGenerationParameters(
						sr, 
						DesEdeParameters.DesEdeKeyLength * 8);

					/*
					* Second, initialise the key generator with the parameters
					*/
					DesEdeKeyGenerator kg = new DesEdeKeyGenerator();
					kg.Init(kgp);

					/*
					* Third, and finally, generate the key
					*/
					key = kg.GenerateKey();

					/*
					* We can now output the key to the file, but first
					* hex Encode the key so that we can have a look
					* at it with a text editor if we so desire
					*/
					using (Stream keystream = File.Create(keyfile))
					{
						Hex.Encode(key, keystream);
					}
				}
				catch (IOException e)
				{
					Console.Error.WriteLine("Could not decryption create key file "+
										"["+keyfile+"]");
					throw e;
				}
			}
			else
			{
				try
				{
					// TODO This block is a bit dodgy

					// read the key, and Decode from hex encoding
					Stream keystream = File.OpenRead(keyfile);
//					int len = keystream.available();
					int len = (int) keystream.Length;
					byte[] keyhex = new byte[len];
					keystream.Read(keyhex, 0, len);
					key = Hex.Decode(keyhex);
				}
				catch (IOException e)
				{
					Console.Error.WriteLine("Decryption key file not found, "
						+ "or not valid ["+keyfile+"]");
					throw e;
				}
			}
		}
Exemplo n.º 16
0
		protected virtual void engineInit(
			KeyGenerationParameters parameters)
		{
			this.random = parameters.Random;
			this.strength = (parameters.Strength + 7) / 8;
		}
Exemplo n.º 17
0
        public static X509Certificate2 GenerateSelfSignedCertificate(string subjectName, string issuerName, AsymmetricKeyParameter issuerPrivKey, int keyStrength = 2048)
        {
            // Generating Random Numbers
            var randomGenerator = new CryptoApiRandomGenerator();
            var random = new SecureRandom(randomGenerator);

            // The Certificate Generator
            var gen = new X509V3CertificateGenerator();

            // Serial Number
            var serialNumber = BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(Int64.MaxValue), random);
            gen.SetSerialNumber(serialNumber);

            // Signature Algorithm
            const string signatureAlgorithm = "SHA256WithRSA";
            gen.SetSignatureAlgorithm(signatureAlgorithm);

            // Issuer and Subject Name
            var subjectDN = new X509Name(subjectName);
            var issuerDN = new X509Name(issuerName);
            gen.SetIssuerDN(issuerDN);
            gen.SetSubjectDN(subjectDN);

            // Valid For
            var notBefore = DateTime.UtcNow.Date;
            var notAfter = notBefore.AddYears(2);

            gen.SetNotBefore(notBefore);
            gen.SetNotAfter(notAfter);

            // Subject Public Key
            AsymmetricCipherKeyPair subjectKeyPair;
            var keyGenerationParameters = new KeyGenerationParameters(random, keyStrength);
            var keyPairGenerator = new RsaKeyPairGenerator();
            keyPairGenerator.Init(keyGenerationParameters);
            subjectKeyPair = keyPairGenerator.GenerateKeyPair();

            gen.SetPublicKey(subjectKeyPair.Public);

            // Generating the Certificate
            var issuerKeyPair = subjectKeyPair;

            // selfsign certificate
            var certificate = gen.Generate(issuerPrivKey, random);

            // correcponding private key
            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);

            x509.PrivateKey = DotNetUtilities.ToRSA(rsaparams);
            return x509;

        }
 protected virtual void engineInit(
     KeyGenerationParameters parameters)
 {
     this.random   = parameters.Random;
     this.strength = (parameters.Strength + 7) / 8;
 }
Exemplo n.º 19
0
        public static SshKey CreateKey(SshVersion version,
      PublicKeyAlgorithm algorithm, string comment = "")
        {
            if (version == SshVersion.SSH1 &&
            algorithm != PublicKeyAlgorithm.SSH_RSA) {
            throw new Exception("unsupported version/algorithm combination");
              }

              switch (algorithm) {
            case PublicKeyAlgorithm.SSH_RSA:
              KeyGenerationParameters keyGenParam =
            new KeyGenerationParameters(secureRandom, 512);

              RsaKeyPairGenerator rsaKeyPairGen = new RsaKeyPairGenerator();
              rsaKeyPairGen.Init(keyGenParam);
              AsymmetricCipherKeyPair keyPair = rsaKeyPairGen.GenerateKeyPair();
              var rsaKey = new SshKey(version, keyPair);
              rsaKey.Comment = comment;
              return rsaKey;

            case PublicKeyAlgorithm.SSH_DSS:
              DsaParametersGenerator dsaParamGen = new DsaParametersGenerator();
              dsaParamGen.Init(512, 10, secureRandom);
              DsaParameters dsaParam = dsaParamGen.GenerateParameters();
              DsaKeyGenerationParameters dsaKeyGenParam =
            new DsaKeyGenerationParameters(secureRandom, dsaParam);
              DsaKeyPairGenerator dsaKeyPairGen = new DsaKeyPairGenerator();
              dsaKeyPairGen.Init(dsaKeyGenParam);
              keyPair = dsaKeyPairGen.GenerateKeyPair();
              var dsaKey = new SshKey(SshVersion.SSH2, keyPair);
              dsaKey.Comment = comment;
              return dsaKey;

            case PublicKeyAlgorithm.ECDSA_SHA2_NISTP256:
              X9ECParameters ecdsa256X9Params =
            SecNamedCurves.GetByName("secp256r1");
              ECDomainParameters ecdsa256DomainParams =
            new ECDomainParameters(ecdsa256X9Params.Curve, ecdsa256X9Params.G,
              ecdsa256X9Params.N, ecdsa256X9Params.H);
              ECKeyGenerationParameters ecdsa256GenParams =
            new ECKeyGenerationParameters(ecdsa256DomainParams, secureRandom);
              ECKeyPairGenerator ecdsa256Gen = new ECKeyPairGenerator();
              ecdsa256Gen.Init(ecdsa256GenParams);
              keyPair = ecdsa256Gen.GenerateKeyPair();
              var ecdsa256Key = new SshKey(SshVersion.SSH2, keyPair);
              ecdsa256Key.Comment = comment;
              return ecdsa256Key;

            case PublicKeyAlgorithm.ECDSA_SHA2_NISTP384:
              X9ECParameters ecdsa384X9Params =
            SecNamedCurves.GetByName("secp384r1");
              ECDomainParameters ecdsa384DomainParams =
            new ECDomainParameters(ecdsa384X9Params.Curve, ecdsa384X9Params.G,
              ecdsa384X9Params.N, ecdsa384X9Params.H);
              ECKeyGenerationParameters ecdsa384GenParams =
            new ECKeyGenerationParameters(ecdsa384DomainParams, secureRandom);
              ECKeyPairGenerator ecdsa384Gen = new ECKeyPairGenerator();
              ecdsa384Gen.Init(ecdsa384GenParams);
              keyPair = ecdsa384Gen.GenerateKeyPair();
              var ecdsa384Key = new SshKey(SshVersion.SSH2, keyPair);
              ecdsa384Key.Comment = comment;
              return ecdsa384Key;

            case PublicKeyAlgorithm.ECDSA_SHA2_NISTP521:
              X9ECParameters ecdsa521X9Params =
            SecNamedCurves.GetByName("secp521r1");
              ECDomainParameters ecdsa521DomainParams =
            new ECDomainParameters(ecdsa521X9Params.Curve, ecdsa521X9Params.G,
              ecdsa521X9Params.N, ecdsa521X9Params.H);
              ECKeyGenerationParameters ecdsa521GenParams =
            new ECKeyGenerationParameters(ecdsa521DomainParams, secureRandom);
              ECKeyPairGenerator ecdsa521Gen = new ECKeyPairGenerator();
              ecdsa521Gen.Init(ecdsa521GenParams);
              keyPair = ecdsa521Gen.GenerateKeyPair();
              var ecdsa521Key = new SshKey(SshVersion.SSH2, keyPair);
              ecdsa521Key.Comment = comment;
              return ecdsa521Key;

            case PublicKeyAlgorithm.ED25519:
              var privateKeySeed = secureRandom.GenerateSeed(Ed25519.PrivateKeySeedSizeInBytes);
              var publicKeyBytes = new byte[Ed25519.PublicKeySizeInBytes];
              var privateKeyBytes = new byte[Ed25519.ExpandedPrivateKeySizeInBytes];
              Ed25519.KeyPairFromSeed(out publicKeyBytes, out privateKeyBytes, privateKeySeed);
              var publicKey = new Ed25519PublicKeyParameter(publicKeyBytes);
              var privateKey = new Ed25519PrivateKeyParameter(privateKeyBytes);
              var ed25519Key = new SshKey(SshVersion.SSH2, publicKey, privateKey, comment);
              return ed25519Key;

            default:
              throw new Exception("unsupported algorithm");
              }
        }
Exemplo n.º 20
0
 private static AsymmetricCipherKeyPair GenerateKeys(int keySize)
 {
     var gen = new RsaKeyPairGenerator();
     var secureRandom = new SecureRandom();
     var keyGenParam = new KeyGenerationParameters(secureRandom, keySize);
     gen.Init(keyGenParam);
     return gen.GenerateKeyPair();
 }
        /// <summary>
        /// Creates a self signed application instance certificate.
        /// </summary>
        /// <param name="storeType">Type of certificate store (Directory) <see cref="CertificateStoreType"/>.</param>
        /// <param name="storePath">The store path (syntax depends on storeType).</param>
        /// <param name="password">The password to use to protect the certificate.</param>
        /// <param name="applicationUri">The application uri (created if not specified).</param>
        /// <param name="applicationName">Name of the application (optional if subjectName is specified).</param>
        /// <param name="subjectName">The subject used to create the certificate (optional if applicationName is specified).</param>
        /// <param name="domainNames">The domain names that can be used to access the server machine (defaults to local computer name if not specified).</param>
        /// <param name="keySize">Size of the key (1024, 2048 or 4096).</param>
        /// <param name="startTime">The start time.</param>
        /// <param name="lifetimeInMonths">The lifetime of the key in months.</param>
        /// <param name="hashSizeInBits">The hash size in bits.</param>
        /// <param name="isCA">if set to <c>true</c> then a CA certificate is created.</param>
        /// <param name="issuerCAKeyCert">The CA cert with the CA private key.</param>
        /// <returns>The certificate with a private key.</returns>
        public static X509Certificate2 CreateCertificate(
            string storeType,
            string storePath,
            string password,
            string applicationUri,
            string applicationName,
            string subjectName,
            IList<String> domainNames,
            ushort keySize,
            DateTime startTime,
            ushort lifetimeInMonths,
            ushort hashSizeInBits,
            bool isCA,
            X509Certificate2 issuerCAKeyCert)
        {
            if (!String.IsNullOrEmpty(storeType) &&
                storeType != CertificateStoreType.Directory)
            {
                throw new NotSupportedException("Cannot create a certificate for a non directory store.");
            }

            if (issuerCAKeyCert != null)
            {
                if (!issuerCAKeyCert.HasPrivateKey)
                {
                    throw new NotSupportedException("Cannot sign with a CA certificate without a private key.");
                }

                throw new NotSupportedException("Signing with an issuer CA certificate is currently unsupported.");
            }

            // set default values.
            SetSuitableDefaults(
                ref applicationUri,
                ref applicationName,
                ref subjectName,
                ref domainNames,
                ref keySize,
                ref lifetimeInMonths,
                isCA);

            // cert generators
            SecureRandom random = new SecureRandom();
            X509V3CertificateGenerator cg = new X509V3CertificateGenerator();

            // Serial Number
            BigInteger serialNumber = BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(Int64.MaxValue), random);
            cg.SetSerialNumber(serialNumber);

            // build name attributes
            var nameOids = new ArrayList();
            nameOids.Add(X509Name.DC);
            nameOids.Add(X509Name.CN);

            var nameValues = new ArrayList();
            nameValues.Add(domainNames[0]);
            nameValues.Add(applicationName);

            // self signed 
            X509Name subjectDN = new X509Name(nameOids, nameValues);
            X509Name issuerDN = subjectDN;
            cg.SetIssuerDN(issuerDN);
            cg.SetSubjectDN(subjectDN);

            // valid for
            cg.SetNotBefore(startTime);
            cg.SetNotAfter(startTime.AddMonths(lifetimeInMonths));

            // Private/Public Key
            AsymmetricCipherKeyPair subjectKeyPair;
            var keyGenerationParameters = new KeyGenerationParameters(random, keySize);
            var keyPairGenerator = new RsaKeyPairGenerator();
            keyPairGenerator.Init(keyGenerationParameters);
            subjectKeyPair = keyPairGenerator.GenerateKeyPair();
            cg.SetPublicKey(subjectKeyPair.Public);

            // add extensions
            // Subject key identifier
            cg.AddExtension(X509Extensions.SubjectKeyIdentifier.Id, false,
                new SubjectKeyIdentifier(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(subjectKeyPair.Public)));

            // Basic constraints
            cg.AddExtension(X509Extensions.BasicConstraints.Id, true, new BasicConstraints(isCA));

            // Authority Key identifier
            var issuerKeyPair = subjectKeyPair;
            var issuerSerialNumber = serialNumber;
            cg.AddExtension(X509Extensions.AuthorityKeyIdentifier.Id, false,
                new AuthorityKeyIdentifier(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(subjectKeyPair.Public),
                    new GeneralNames(new GeneralName(issuerDN)), issuerSerialNumber));

            if (!isCA)
            {
                // Key usage 
                cg.AddExtension(X509Extensions.KeyUsage, true,
                    new KeyUsage(KeyUsage.DataEncipherment | KeyUsage.DigitalSignature |
                        KeyUsage.NonRepudiation | KeyUsage.KeyCertSign | KeyUsage.KeyEncipherment));

                // Extended Key usage
                cg.AddExtension(X509Extensions.ExtendedKeyUsage, true,
                    new ExtendedKeyUsage(new List<DerObjectIdentifier>() {
                    new DerObjectIdentifier("1.3.6.1.5.5.7.3.1"), // server auth
                    new DerObjectIdentifier("1.3.6.1.5.5.7.3.2"), // client auth
                    }));

                // subject alternate name
                cg.AddExtension(X509Extensions.SubjectAlternativeName, false,
                    new GeneralNames(new GeneralName[] {
                    new GeneralName(GeneralName.UniformResourceIdentifier, applicationUri),
                    new GeneralName(GeneralName.DnsName, domainNames[0])}));
            }
            else
            {
                // Key usage CA
                cg.AddExtension(X509Extensions.KeyUsage, true,
                    new KeyUsage(KeyUsage.CrlSign | KeyUsage.DigitalSignature | KeyUsage.KeyCertSign));
            }

            // sign certificate
            ISignatureFactory signatureFactory = 
                new Asn1SignatureFactory((hashSizeInBits < 256) ? "SHA1WITHRSA" : "SHA256WITHRSA", subjectKeyPair.Private, random);
            Org.BouncyCastle.X509.X509Certificate x509 = cg.Generate(signatureFactory);

            // create pkcs12 store for cert and private key
            X509Certificate2 certificate = null;
            using (MemoryStream pfxData = new MemoryStream())
            {
                Pkcs12Store pkcsStore = new Pkcs12StoreBuilder().Build();
                X509CertificateEntry[] chain = new X509CertificateEntry[1];
                string passcode = "passcode";
                chain[0] = new X509CertificateEntry(x509);
                pkcsStore.SetKeyEntry(applicationName, new AsymmetricKeyEntry(subjectKeyPair.Private), chain);
                pkcsStore.Save(pfxData, passcode.ToCharArray(), random);

                // merge into X509Certificate2
                certificate = CreateCertificateFromPKCS12(pfxData.ToArray(), passcode);
            }

            Utils.Trace(Utils.TraceMasks.Security, "Created new certificate: {0}", certificate.Thumbprint);

            // add cert to the store.
            if (!String.IsNullOrEmpty(storePath))
            {
                ICertificateStore store = null;
                if (storeType == CertificateStoreType.Directory)
                {
                    using (store = new DirectoryCertificateStore())
                    {
                        store.Open(storePath);
                        store.Add(certificate);
                        store.Close();
                    }
                }
            }

            // note: this cert has a private key!
            return certificate;
        }
Exemplo n.º 22
0
        public static AsymmetricKeyParameter GenerateCACertificate(string subjectName, int keyStrength = 2048)
        {
            // Generating Random Numbers
            var randomGenerator = new CryptoApiRandomGenerator();
            var random = new SecureRandom(randomGenerator);

            // The Certificate Generator
            var certificateGenerator = new X509V3CertificateGenerator();

            // Serial Number
            var serialNumber = BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(Int64.MaxValue), random);
            certificateGenerator.SetSerialNumber(serialNumber);

            // Signature Algorithm
            const string signatureAlgorithm = "SHA256WithRSA";
            certificateGenerator.SetSignatureAlgorithm(signatureAlgorithm);

            // Subject Public Key
            AsymmetricCipherKeyPair subjectKeyPair;
            var keyGenerationParameters = new KeyGenerationParameters(random, keyStrength);
            var keyPairGenerator = new RsaKeyPairGenerator();
            keyPairGenerator.Init(keyGenerationParameters);
            subjectKeyPair = keyPairGenerator.GenerateKeyPair();

            // Issuer and Subject Name
            var subjectDN = new X509Name(subjectName);
            var issuerDN = subjectDN;
            certificateGenerator.SetIssuerDN(issuerDN);
            certificateGenerator.SetSubjectDN(subjectDN);
            //            certificateGenerator.AddExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false));
            certificateGenerator.AddExtension(X509Extensions.AuthorityKeyIdentifier, true, new AuthorityKeyIdentifier(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(subjectKeyPair.Public), new GeneralNames(new GeneralName(issuerDN)), serialNumber));

            // Valid For
            var notBefore = DateTime.UtcNow.Date;
            var notAfter = notBefore.AddYears(2);

            certificateGenerator.SetNotBefore(notBefore);
            certificateGenerator.SetNotAfter(notAfter);

            certificateGenerator.SetPublicKey(subjectKeyPair.Public);

            // Generating the Certificate
            var issuerKeyPair = subjectKeyPair;

            // selfsign certificate
            var certificate = certificateGenerator.Generate(issuerKeyPair.Private, random);
            var x509 = new System.Security.Cryptography.X509Certificates.X509Certificate2(certificate.GetEncoded());

            // Add CA certificate to Root store
            X509Store store = new X509Store(StoreName.Root, StoreLocation.LocalMachine);
            store.Open(OpenFlags.ReadWrite);
            store.Add(x509);
            store.Close();

            store = new X509Store(StoreName.TrustedPublisher, StoreLocation.LocalMachine);
            store.Open(OpenFlags.ReadWrite);
            store.Add(x509);
            store.Close();

            RsaPrivateCrtKeyParameters rsaparams = (RsaPrivateCrtKeyParameters)issuerKeyPair.Private;
            x509.PrivateKey = DotNetUtilities.ToRSA(rsaparams);
            store = new X509Store("PrivateCertStore", StoreLocation.CurrentUser);
            store.Open(OpenFlags.ReadWrite);
            store.Add(x509);
            store.Close();

            return issuerKeyPair.Private;
        }
Exemplo n.º 23
0
        private static AsymmetricCipherKeyPair GenerateKeys(X509V3CertificateGenerator certificateGenerator, SecureRandom random, SignatureHashAlgorithm signatureAlgorithm)
        {
            AsymmetricCipherKeyPair result = null;
            switch (signatureAlgorithm.Signature)
            {
                case TSignatureAlgorithm.Anonymous:
                    break;
                case TSignatureAlgorithm.RSA:
                    KeyGenerationParameters keyGenerationParameters = new KeyGenerationParameters(random, 2048);
                    RsaKeyPairGenerator rsaKeyPairGenerator = new RsaKeyPairGenerator();
                    rsaKeyPairGenerator.Init(keyGenerationParameters);
                    result = rsaKeyPairGenerator.GenerateKeyPair();
                    break;
                case TSignatureAlgorithm.DSA:
                    break;
                case TSignatureAlgorithm.ECDSA:
                    //ECDomainParameters ellipticCurveParameters = EllipticCurveFactory.GetEllipticCurveParameters(TEllipticCurve.secp256r1);
                    ECKeyPairGenerator keyPairGenerator = new ECKeyPairGenerator();
                    //keyPairGenerator.Init(new ECKeyGenerationParameters(ellipticCurveParameters, random));
                    keyPairGenerator.Init(new ECKeyGenerationParameters(Org.BouncyCastle.Asn1.Sec.SecObjectIdentifiers.SecP256r1, random));
                    result = keyPairGenerator.GenerateKeyPair();
                    //certificateGenerator.AddExtension(X509Extensions.SubjectPublicKeyInfo)
                    //PrivateKey = (ECPrivateKeyParameters)keys.Private;
                    //PublicKey = (ECPublicKeyParameters)keys.Public;
                    break;
                default:
                    break;
            }

            certificateGenerator.SetPublicKey(result.Public);
            return result;
        }
        public X509Certificate2 Build()
        {
            // Generating Random Numbers
            var randomGenerator = new CryptoApiRandomGenerator();
            var random = new SecureRandom(randomGenerator);

            // The Certificate Generator
            var certificateGenerator = new X509V3CertificateGenerator();

            // Serial Number
            var serialNumber = BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(long.MaxValue), random);
            certificateGenerator.SetSerialNumber(serialNumber);

            // Signature Algorithm
            certificateGenerator.SetSignatureAlgorithm("SHA256WithRSA");

            // Issuer and Subject Name
            certificateGenerator.SetIssuerDN(new X509Name(_issuerName ?? _subjectName));
            certificateGenerator.SetSubjectDN(new X509Name(_subjectName));

            // Authority Key Identifier
            if (_issuer != null)
            {
                var authorityKeyIdentifier = new AuthorityKeyIdentifierStructure(
                    DotNetUtilities.FromX509Certificate(_issuer));
                certificateGenerator.AddExtension(
                    X509Extensions.AuthorityKeyIdentifier.Id, false, authorityKeyIdentifier);
            }

            // Basic Constraints - certificate is allowed to be used as intermediate.
            certificateGenerator.AddExtension(
                X509Extensions.BasicConstraints.Id, true, new BasicConstraints(_intermediate));

            // Valid For
            certificateGenerator.SetNotBefore(_notBefore ?? DateTime.UtcNow.Date);
            certificateGenerator.SetNotAfter(_notAfter ?? DateTime.UtcNow.Date.AddYears(2));

            // Subject Public Key
            var keyGenerationParameters = new KeyGenerationParameters(random, _keyStrength);
            var keyPairGenerator = new RsaKeyPairGenerator();
            keyPairGenerator.Init(keyGenerationParameters);

            var subjectKeyPair = keyPairGenerator.GenerateKeyPair();
            var issuerKeyPair = _issuerPrivateKey == null
                ? subjectKeyPair
                : DotNetUtilities.GetKeyPair(_issuerPrivateKey);

            certificateGenerator.SetPublicKey(subjectKeyPair.Public);

            // selfsign certificate
            var certificate = certificateGenerator.Generate(issuerKeyPair.Private, random);

            // merge into X509Certificate2
            return new X509Certificate2(certificate.GetEncoded())
            {
                PrivateKey = ConvertToRsaPrivateKey(subjectKeyPair)
            };
        }
Exemplo n.º 25
0
        public X509Certificate2 CreateSelfSignedCertificate(string subjectName, string issuerName)
        {
            // Generating Random Numbers
            CryptoApiRandomGenerator randomGenerator = new CryptoApiRandomGenerator();
            SecureRandom random = new SecureRandom(randomGenerator);

            // The Certificate Generator
            X509V3CertificateGenerator certificateGenerator = new X509V3CertificateGenerator();

            // Serial Number
            BigInteger serialNumber = BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(Int64.MaxValue), random);
            certificateGenerator.SetSerialNumber(serialNumber);

            // Signature Algorithm
            const string signatureAlgorithm = "SHA512withRSA";
            certificateGenerator.SetSignatureAlgorithm(signatureAlgorithm);

            // Issuer and Subject Name
            X509Name subjectDN = new X509Name("CN=" + subjectName);
            X509Name issuerDN = new X509Name("CN=" + issuerName);
            certificateGenerator.SetIssuerDN(issuerDN);
            certificateGenerator.SetSubjectDN(subjectDN);

            // Valid For
            var date = DateTime.Now;
            DateTime notBefore = date.AddDays(-1);
            DateTime notAfter = notBefore.AddYears(2);

            certificateGenerator.SetNotBefore(notBefore);
            certificateGenerator.SetNotAfter(notAfter);

            // Subject Public Key
            const int keyStrength = 2048;
            var keyGenerationParameters = new KeyGenerationParameters(random, keyStrength);
            var keyPairGenerator = new RsaKeyPairGenerator();
            keyPairGenerator.Init(keyGenerationParameters);
            var subjectKeyPair = keyPairGenerator.GenerateKeyPair();

            certificateGenerator.SetPublicKey(subjectKeyPair.Public);

            // Selfsign certificate
            Org.BouncyCastle.X509.X509Certificate certificate = certificateGenerator.Generate(subjectKeyPair.Private, random);

            // Convert to .NET cert // http://blog.differentpla.net/post/20/how-do-i-convert-a-bouncy-castle-certificate-to-a-net-certificate-
            var store = new Pkcs12Store();
            string friendlyName = certificate.SubjectDN.ToString();
            var certificateEntry = new X509CertificateEntry(certificate);
            store.SetCertificateEntry(friendlyName, certificateEntry);
            store.SetKeyEntry(friendlyName, new AsymmetricKeyEntry(subjectKeyPair.Private), new[] { certificateEntry });
            
            const string password = "******"; // required to export
            byte[] certBytes;
            using (var stream = new MemoryStream())
            {
                store.Save(stream, password.ToCharArray(), random);
                certBytes = stream.ToArray();
            }

            var convertedCertificate =
                new X509Certificate2(certBytes, password, X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable);
            
            return convertedCertificate;
        }
        public X509Certificate2 GenerateSelfSignedCertificate(string name)
        {
            var randomGenerator = new CryptoApiRandomGenerator();
            var random = new SecureRandom(randomGenerator);

            var certificateGenerator = new X509V3CertificateGenerator();

            var serialNumber = BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(long.MaxValue), random);
            certificateGenerator.SetSerialNumber(serialNumber);

            const string signatureAlgorithm = "SHA256WithRSA";
            certificateGenerator.SetSignatureAlgorithm(signatureAlgorithm);

            var subjectDN = new X509Name(name);
            var issuerDN = subjectDN;
            certificateGenerator.SetIssuerDN(issuerDN);
            certificateGenerator.SetSubjectDN(subjectDN);

            var notBefore = DateTime.UtcNow.Date;
            var notAfter = notBefore.AddYears(ExpireTimeInYears);

            certificateGenerator.SetNotBefore(notBefore);
            certificateGenerator.SetNotAfter(notAfter);

            var keyGenerationParameters = new KeyGenerationParameters(random, KeyStrength);
            var keyPairGenerator = new RsaKeyPairGenerator();
            keyPairGenerator.Init(keyGenerationParameters);

            var subjectKeyPair = keyPairGenerator.GenerateKeyPair();
            certificateGenerator.SetPublicKey(subjectKeyPair.Public);

            var issuerKeyPair = subjectKeyPair;

            var certificate = certificateGenerator.Generate(issuerKeyPair.Private, random);

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

            var x509 = new 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);
            var rsaParameters = new RsaPrivateCrtKeyParameters(
                rsa.Modulus,
                rsa.PublicExponent,
                rsa.PrivateExponent,
                rsa.Prime1,
                rsa.Prime2,
                rsa.Exponent1,
                rsa.Exponent2,
                rsa.Coefficient);

            var privateKey = DotNetUtilities.ToRSA(rsaParameters);

            var csp = new CspParameters
            {
                KeyContainerName = "Shapeshifter"
            };

            var rsaPrivate = new RSACryptoServiceProvider(csp);
            rsaPrivate.ImportParameters(privateKey.ExportParameters(true));
            x509.PrivateKey = rsaPrivate;

            return x509;
        }
Exemplo n.º 27
0
 public static ECKey GenerateKey()
 {
     //mixing bouncy implementation
     var gen = new ECKeyPairGenerator();
     var keyGenParam = new KeyGenerationParameters(SecureRandom, 256);
     gen.Init(keyGenParam);
     var keyPair =  gen.GenerateKeyPair();
     var privateBytes = ((ECPrivateKeyParameters)keyPair.Private).D.ToByteArray();
     return new ECKey(privateBytes, true);
 }
Exemplo n.º 28
0
        public static AsymmetricKeyParameter GenerateCACertificate(string subjectName, int keyStrength = 2048)
        {
            // Generating Random Numbers
            var randomGenerator = new CryptoApiRandomGenerator();
            var random = new SecureRandom(randomGenerator);

            // The Certificate Generator
            var certificateGenerator = new X509V3CertificateGenerator();

            // Serial Number
            var serialNumber = BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(Int64.MaxValue), random);
            certificateGenerator.SetSerialNumber(serialNumber);

            // Signature Algorithm
            const string signatureAlgorithm = "SHA256WithRSA";
            certificateGenerator.SetSignatureAlgorithm(signatureAlgorithm);

            // Issuer and Subject Name
            var subjectDN = new X509Name(subjectName);
            var issuerDN = subjectDN;
            certificateGenerator.SetIssuerDN(issuerDN);
            certificateGenerator.SetSubjectDN(subjectDN);

            // Valid For
            var notBefore = DateTime.UtcNow.Date;
            var notAfter = notBefore.AddYears(100);

            certificateGenerator.SetNotBefore(notBefore);
            certificateGenerator.SetNotAfter(notAfter);

            // Subject Public Key
            AsymmetricCipherKeyPair subjectKeyPair;
            var keyGenerationParameters = new KeyGenerationParameters(random, keyStrength);
            var keyPairGenerator = new RsaKeyPairGenerator();
            keyPairGenerator.Init(keyGenerationParameters);
            subjectKeyPair = keyPairGenerator.GenerateKeyPair();

            certificateGenerator.SetPublicKey(subjectKeyPair.Public);

            // Generating the Certificate
            var issuerKeyPair = subjectKeyPair;

            // selfsign certificate
            var certificate = certificateGenerator.Generate(issuerKeyPair.Private, random);

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

            // Add CA certificate to Root store
            AddCertToStore(x509, StoreName.Root, StoreLocation.CurrentUser);

            return issuerKeyPair.Private;

        }
Exemplo n.º 29
0
        /// <summary>
        /// Generate a key pair.
        /// </summary>
        /// <param name="random">The random number generator.</param>
        /// <param name="strength">The key length in bits. For RSA, 2048 bits should be considered the minimum acceptable these days.</param>
        /// <returns></returns>
        private static AsymmetricCipherKeyPair GenerateKeyPair(SecureRandom random, int strength)
        {
            var keyGenerationParameters = new KeyGenerationParameters(random, strength);

            var keyPairGenerator = new RsaKeyPairGenerator();
            keyPairGenerator.Init(keyGenerationParameters);
            var subjectKeyPair = keyPairGenerator.GenerateKeyPair();
            return subjectKeyPair;
        }
Exemplo n.º 30
0
		/// <summary>
		/// Initialises the key generator.
		/// </summary>
		/// <remarks>
		/// Poly1305 keys are always 256 bits, so the key length in the provided parameters is ignored.
		/// </remarks>
		protected override void engineInit(KeyGenerationParameters param)
		{
			// Poly1305 keys are always 256 bits
			this.random = param.Random;
			this.strength = 32;
		}
Exemplo n.º 31
0
 /// <summary>
 /// The generate secret key.
 /// </summary>
 /// <returns>
 /// The <see cref="SecretKey"/>.
 /// </returns>
 public SecretKey GenerateSecretKey()
 {
     var kgp = new KeyGenerationParameters(new SecureRandom(), DesEdeParameters.DesEdeKeyLength * 8);
     var kg = new DesEdeKeyGenerator();
     kg.Init(kgp);
     var key = new SecretKey(kg.GenerateKey());
     return key;
 }
        /// <summary>
        /// Creates new certificate
        /// </summary>
        /// <returns></returns>
        public static void CreateSelfSignedCertificate(string subjectDirName, DateTime startDate, DateTime endDate, int signatureBits, int keyStrength, string password, string fileName)
        {
            string signatureAlgorithm;
            switch (signatureBits)
            {
                case 160:
                    signatureAlgorithm = "SHA1withRSA";
                    break;
                case 224:
                    signatureAlgorithm = "SHA224withRSA";
                    break;
                case 256:
                    signatureAlgorithm = "SHA256withRSA";
                    break;
                case 384:
                    signatureAlgorithm = "SHA384withRSA";
                    break;
                case 512:
                    signatureAlgorithm = "SHA512withRSA";
                    break;
                default:
                    throw new ArgumentException("Invalid signature bit size.", "signatureBits");
            }

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

            // Generate public/private keys.
            AsymmetricCipherKeyPair encryptionKeys;

            KeyGenerationParameters keyGenerationParameters = new KeyGenerationParameters(random, keyStrength);
            RsaKeyPairGenerator keyPairGenerator = new RsaKeyPairGenerator();
            keyPairGenerator.Init(keyGenerationParameters);
            encryptionKeys = keyPairGenerator.GenerateKeyPair();

            // The Certificate Generator
            X509V3CertificateGenerator certificateGenerator = new X509V3CertificateGenerator();
            certificateGenerator.SetSerialNumber(BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(Int64.MaxValue), random));
            certificateGenerator.SetSignatureAlgorithm(signatureAlgorithm);
            certificateGenerator.SetIssuerDN(new X509Name(subjectDirName));
            certificateGenerator.SetSubjectDN(new X509Name(subjectDirName));
            certificateGenerator.SetNotBefore(startDate);
            certificateGenerator.SetNotAfter(endDate);
            certificateGenerator.SetPublicKey(encryptionKeys.Public);

            // self-sign certificate
            Org.BouncyCastle.X509.X509Certificate certificate = certificateGenerator.Generate(encryptionKeys.Private, random);

            var store = new Pkcs12Store();
            string friendlyName = certificate.SubjectDN.ToString();
            var certificateEntry = new X509CertificateEntry(certificate);
            store.SetCertificateEntry(friendlyName, certificateEntry);
            store.SetKeyEntry(friendlyName, new AsymmetricKeyEntry(encryptionKeys.Private), new[] { certificateEntry });

            var stream = new MemoryStream();
            store.Save(stream, password.ToCharArray(), random);

            //Verify that the certificate is valid.
            var convertedCertificate = new X509Certificate2(stream.ToArray(), password, X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable);

            //Write the file.
            File.WriteAllBytes(fileName, stream.ToArray());

            File.WriteAllBytes(Path.ChangeExtension(fileName, ".cer"), certificate.GetEncoded());
        }