Inheritance: KeyGenerationParameters
		public override void PerformTest()
        {
            IAsymmetricCipherKeyPairGenerator pGen = GeneratorUtilities.GetKeyPairGenerator("RSA");
            RsaKeyGenerationParameters genParam = new RsaKeyGenerationParameters(
				BigInteger.ValueOf(0x10001), new SecureRandom(), 512, 25);

			pGen.Init(genParam);

			AsymmetricCipherKeyPair pair = pGen.GenerateKeyPair();

            //
            // set up the parameters
            //
            byte[] salt = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
            int iterationCount = 100;

			//
            // set up the key
            //
            char[] password1 = { 'h', 'e', 'l', 'l', 'o' };

            EncryptedPrivateKeyInfo  encInfo = EncryptedPrivateKeyInfoFactory.CreateEncryptedPrivateKeyInfo(alg, password1, salt, iterationCount, PrivateKeyInfoFactory.CreatePrivateKeyInfo(pair.Private));

            PrivateKeyInfo info = PrivateKeyInfoFactory.CreatePrivateKeyInfo(password1, encInfo);

            AsymmetricKeyParameter key = PrivateKeyFactory.CreateKey(info);

            if (!key.Equals(pair.Private))
            {
                Fail("Key corrupted");
            }

			doOpensslTestKeys();
		}
 private static AsymmetricCipherKeyPair GenerateKeyPairRsa()
 {
     var generator = GeneratorUtilities.GetKeyPairGenerator("RSA");
     var generatorParams = new RsaKeyGenerationParameters(
         new BigInteger("10001", 16), RandomUtil.SecureRandomBc, 2048, 112);
     generator.Init(generatorParams);
     return generator.GenerateKeyPair();
 }
Example #3
0
 public static AsymmetricCipherKeyPair GenerateKeyPair()
 {
     SecureRandom sr = new SecureRandom();
     BigInteger pubExp = new BigInteger("10001", 16);
     RsaKeyGenerationParameters RSAKeyGenPara = new RsaKeyGenerationParameters(pubExp, sr, 1024, 80);
     RsaKeyPairGenerator RSAKeyPairGen = new RsaKeyPairGenerator();
     RSAKeyPairGen.Init(RSAKeyGenPara);
     return RSAKeyPairGen.GenerateKeyPair();
 }
Example #4
0
        public override bool Equals(object obj)
        {
            RsaKeyGenerationParameters parameters = obj as RsaKeyGenerationParameters;

            if (parameters == null)
            {
                return(false);
            }
            return((this.certainty == parameters.certainty) && this.publicExponent.Equals(parameters.publicExponent));
        }
Example #5
0
        public override bool Equals(object obj)
        {
            RsaKeyGenerationParameters rsaKeyGenerationParameters = obj as RsaKeyGenerationParameters;

            if (rsaKeyGenerationParameters == null)
            {
                return(false);
            }
            return(certainty == rsaKeyGenerationParameters.certainty && publicExponent.Equals(rsaKeyGenerationParameters.publicExponent));
        }
Example #6
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);
			}
        }
        public override void PerformTest()
        {
            IAsymmetricCipherKeyPairGenerator pGen = GeneratorUtilities.GetKeyPairGenerator("RSA");
            RsaKeyGenerationParameters genParam = new RsaKeyGenerationParameters(
                BigInteger.ValueOf(0x10001), new SecureRandom(), 512, 25);

            pGen.Init(genParam);

            IAsymmetricCipherKeyPair pair = pGen.GenerateKeyPair();

            IDictionary attrs = new Hashtable();

            attrs.Add(X509Name.C, "AU");
            attrs.Add(X509Name.O, "The Legion of the Bouncy Castle");
            attrs.Add(X509Name.L, "Melbourne");
            attrs.Add(X509Name.ST, "Victoria");
            attrs.Add(X509Name.EmailAddress, "*****@*****.**");

            X509Name subject = new X509Name(new ArrayList(attrs.Keys), attrs);

            Pkcs10CertificationRequest req1 = new Pkcs10CertificationRequest(
                "SHA1withRSA",
                subject,
                pair.Public,
                null,
                pair.Private);

            byte[] bytes = req1.GetEncoded();

            Pkcs10CertificationRequest req2 = new Pkcs10CertificationRequest(bytes);

            if (!req2.Verify())
            {
                Fail("Failed verify check.");
            }

            if (!req2.GetPublicKey().Equals(req1.GetPublicKey()))
            {
                Fail("Failed public key check.");
            }
        }
Example #8
0
        public void GenAkey()
        {
            //RSA密钥对的构造器
            RsaKeyPairGenerator keyGenerator = new RsaKeyPairGenerator();

            //RSA密钥构造器的参数
            RsaKeyGenerationParameters param = new RsaKeyGenerationParameters(
                Org.BouncyCastle.Math.BigInteger.ValueOf(3),
                new Org.BouncyCastle.Security.SecureRandom(),
                1024,   //密钥长度
                25);
            //用参数初始化密钥构造器
            keyGenerator.Init(param);
            //产生密钥对
            AsymmetricCipherKeyPair keyPair = keyGenerator.GenerateKeyPair();
            //获取公钥和密钥
            AsymmetricKeyParameter publicKey = keyPair.Public;
            AsymmetricKeyParameter privateKey = keyPair.Private;

            _Uk.TbPass.Text = publicKey.ToString();
            _Uk.TbSalt.Text = privateKey.ToString();
        }
 public void Init(IKeyGenerationParameters parameters)
 {
     _param = parameters as RsaKeyGenerationParameters ??
              new RsaKeyGenerationParameters(_defaultPublicExponent, parameters.Random, parameters.Strength, DefaultTests);
 }
Example #10
0
		public override void PerformTest()
		{
			testSig(1, pub1, prv1, slt1a, msg1a, sig1a);
			testSig(2, pub1, prv1, slt1b, msg1b, sig1b);
			testSig(3, pub2, prv2, slt2a, msg2a, sig2a);
			testSig(4, pub2, prv2, slt2b, msg2b, sig2b);
			testSig(5, pub4, prv4, slt4a, msg4a, sig4a);
			testSig(6, pub4, prv4, slt4b, msg4b, sig4b);
			testSig(7, pub8, prv8, slt8a, msg8a, sig8a);
			testSig(8, pub8, prv8, slt8b, msg8b, sig8b);
			testSig(9, pub9, prv9, slt9a, msg9a, sig9a);
			testSig(10, pub9, prv9, slt9b, msg9b, sig9b);
	        
			//
			// loop test
			//
			int failed = 0;
			byte[] data = new byte[DATA_LENGTH];

			SecureRandom    random = new SecureRandom();


			RsaKeyParameters[] kprv ={prv1, prv2, prv4, prv8, prv9};
			RsaKeyParameters[] kpub ={pub1, pub2, pub4, pub8, pub9};

			for (int j = 0, i = 0; j < NUM_TESTS; j++, i++)
			{
        		if (i == kprv.Length)
				{
					i = 0;
				}

				if (!isProcessingOkay(kpub[i], kprv[i], data, random))
				{
            		failed++;
				}
			}

			if (failed != 0)
			{
				Fail("loop test failed - failures: " + failed);
			}

			//
			// key generation test
			//
			RsaKeyPairGenerator pGen = new RsaKeyPairGenerator();
			RsaKeyGenerationParameters genParam = new RsaKeyGenerationParameters(
				BigInteger.ValueOf(0x11), new SecureRandom(), 1024, 25);

			pGen.Init(genParam);
			failed = 0;

			for (int k = 0; k < NUM_TESTS_WITH_KEY_GENERATION; k++)
			{
        		AsymmetricCipherKeyPair pair = pGen.GenerateKeyPair();

				for (int j = 0; j < NUM_TESTS; j++)
				{
					if (!isProcessingOkay((RsaKeyParameters)pair.Public, (RsaKeyParameters)pair.Private, data, random))
					{
						failed++;
					}
				}
			}

			if (failed != 0)
			{
				Fail("loop test with key generation failed - failures: " + failed);
			}
		}
Example #11
0
 public void generateCSR(string electoralEampaign, string user, string password)
 {
     X509Name name = new X509Name("C=PL, ST=Mazowieckie, L=Warszawa, O=KBW, E=-, OU=" + electoralEampaign + ", CN=" + user);
     RsaKeyPairGenerator keyGenerator = new RsaKeyPairGenerator();
     RsaKeyGenerationParameters param = new RsaKeyGenerationParameters(BigInteger.ValueOf(3L), new SecureRandom(), 2048, 25);
     keyGenerator.Init(param);
     AsymmetricCipherKeyPair ackp = keyGenerator.GenerateKeyPair();
     Pkcs10CertificationRequest csr = new Pkcs10CertificationRequest("SHA1WITHRSA", name, ackp.Public, null, ackp.Private);
     System.Text.StringBuilder CSRPem = new System.Text.StringBuilder();
     PemWriter CSRPemWriter = new PemWriter(new System.IO.StringWriter(CSRPem));
     CSRPemWriter.WriteObject(csr);
     CSRPemWriter.Writer.Flush();
     this.generatedCSR = CSRPem.ToString();
     System.Text.StringBuilder PrivateKeyPem = new System.Text.StringBuilder();
     PemWriter PrivateKeyPemWriter = new PemWriter(new System.IO.StringWriter(PrivateKeyPem));
     PrivateKeyPemWriter.WriteObject(ackp.Private);
     CSRPemWriter.Writer.Flush();
     this.keys = PrivateKeyPem.ToString();
     AsymmetricKeyParameter publicKey = ackp.Public;
     AsymmetricKeyParameter privateKey = ackp.Private;
     System.IO.StringWriter sw = new System.IO.StringWriter();
     PemWriter pw = new PemWriter(sw);
     pw.WriteObject(privateKey, "AES-256-CBC", password.ToCharArray(), new SecureRandom());
     pw.Writer.Close();
     this.keys = sw.ToString();
     if (!System.IO.Directory.Exists(this.path + "\\Licenses"))
     {
         try
         {
             System.IO.Directory.CreateDirectory(this.path + "\\Licenses");
         }
         catch (System.ArgumentNullException)
         {
             MessageBox.Show("Nieprawidłowa ścieżka. Nie można utworzyć katalogu \"Licenses\"", "Error");
         }
         catch (System.ArgumentException)
         {
             MessageBox.Show("Nieprawidłowa ścieżka. Nie można utworzyć katalogu \"Licenses\"", "Error");
         }
         catch (System.UnauthorizedAccessException)
         {
             MessageBox.Show("Nie masz uprawnień do tworzenia katalogów. Otwórz aplikacje jako adnimistrator.", "Uwaga");
         }
         catch (System.IO.PathTooLongException)
         {
             MessageBox.Show("Nieprawidłowa ścieżka. Nie można utworzyć katalogu \"Licenses\"", "Error");
         }
         catch (System.IO.DirectoryNotFoundException)
         {
             MessageBox.Show("Nieprawidłowa ścieżka. Nie można utworzyć katalogu \"Licenses\"", "Error");
         }
         catch (System.NotSupportedException)
         {
             MessageBox.Show("Nieprawidłowy format ścieżki. Nie można utworzyć katalogu \"Licenses\"", "Error");
         }
         catch (System.IO.IOException)
         {
             MessageBox.Show("Nieprawidłowa ścieżka. Nie można utworzyć katalogu \"Licenses\"", "Error");
         }
     }
     string namefile = "";
     try
     {
         int tmp = System.IO.Directory.GetFiles(this.path + "\\Licenses", electoralEampaign.Replace("/", "_") + "_" + user + "*.csr").Length + 1;
         if (tmp > 1)
         {
             string num = tmp.ToString();
             namefile = string.Concat(new string[]
             {
                 electoralEampaign.Replace("/", "_"),
                 "_",
                 user,
                 " ",
                 num
             });
         }
         else
         {
             namefile = electoralEampaign.Replace("/", "_") + "_" + user;
         }
     }
     catch (System.Exception)
     {
         namefile = electoralEampaign.Replace("/", "_") + "_" + user;
     }
     try
     {
         System.IO.StreamWriter sw2 = new System.IO.StreamWriter(this.path + "\\Licenses\\" + namefile + ".csr", false);
         sw2.Write(this.generatedCSR);
         sw2.Close();
         sw2 = new System.IO.StreamWriter(this.path + "\\Licenses\\" + namefile + ".key", false);
         sw2.Write(this.keys);
         sw2.Close();
     }
     catch (System.ArgumentNullException)
     {
         MessageBox.Show("Błędna ścieżka", "Error");
     }
     catch (System.ArgumentException)
     {
         MessageBox.Show("Błędna ścieżka", "Error");
     }
     catch (System.IO.DirectoryNotFoundException)
     {
         MessageBox.Show("Nie znaleziono katalogu", "Error");
     }
     catch (System.IO.PathTooLongException)
     {
         MessageBox.Show("Zbyt długa ścieżka do katalogu", "Error");
     }
     catch (System.IO.IOException)
     {
         MessageBox.Show("Podano ścieżke do pliku zamiast katalogu", "Error");
     }
     catch (System.UnauthorizedAccessException)
     {
         MessageBox.Show("Program nie posiada uprawnień do zapisywania plików. Otwórz aplikacje jako Administrator", "Error");
     }
     catch (System.Exception e)
     {
         MessageBox.Show("Nie można zapisać pliku. Orginal error: " + e.Message, "Error");
     }
 }
Example #12
0
 public void RsaKeysGenerate(string PrivateKeyFilename, string PublicKeyFilename, string passw)
 {
     RsaKeyPairGenerator keyGenerator = new RsaKeyPairGenerator();
     RsaKeyGenerationParameters param = new RsaKeyGenerationParameters(BigInteger.ValueOf(3L), new SecureRandom(), 1024, 25);
     keyGenerator.Init(param);
     AsymmetricCipherKeyPair keyPair = keyGenerator.GenerateKeyPair();
     AsymmetricKeyParameter publicKey = keyPair.Public;
     AsymmetricKeyParameter privateKey = keyPair.Private;
     SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(publicKey);
     Asn1Object aobject = publicKeyInfo.ToAsn1Object();
     byte[] pubInfoByte = aobject.GetEncoded();
     System.IO.FileStream fs = new System.IO.FileStream(PublicKeyFilename, System.IO.FileMode.Create, System.IO.FileAccess.Write);
     fs.Write(pubInfoByte, 0, pubInfoByte.Length);
     fs.Close();
     string alg = "1.2.840.113549.1.12.1.3";
     byte[] salt = new byte[]
     {
         1,
         2,
         3,
         4,
         5,
         6,
         7,
         8,
         9,
         10
     };
     int count = 1000;
     char[] password = passw.ToCharArray();
     EncryptedPrivateKeyInfo enPrivateKeyInfo = EncryptedPrivateKeyInfoFactory.CreateEncryptedPrivateKeyInfo(alg, password, salt, count, privateKey);
     byte[] priInfoByte = enPrivateKeyInfo.ToAsn1Object().GetEncoded();
     fs = new System.IO.FileStream(PrivateKeyFilename, System.IO.FileMode.Create, System.IO.FileAccess.Write);
     fs.Write(priInfoByte, 0, priInfoByte.Length);
     fs.Close();
 }
Example #13
0
		public override void PerformTest()
		{
			RsaKeyParameters pubParameters = new RsaKeyParameters(false, mod, pubExp);
			RsaKeyParameters privParameters = new RsaPrivateCrtKeyParameters(mod, pubExp, privExp, p, q, pExp, qExp, crtCoef);
			byte[] data = Hex.Decode(edgeInput);

			//
			// RAW
			//
			IAsymmetricBlockCipher eng = new RsaBlindedEngine();

			eng.Init(true, pubParameters);

			try
			{
				data = eng.ProcessBlock(data, 0, data.Length);
			}
			catch (Exception e)
			{
				Fail("RSA: failed - exception " + e.ToString(), e);
			}

			eng.Init(false, privParameters);

			try
			{
				data = eng.ProcessBlock(data, 0, data.Length);
			}
			catch (Exception e)
			{
				Fail("failed - exception " + e.ToString(), e);
			}

			if (!edgeInput.Equals(Hex.ToHexString(data)))
			{
				Fail("failed RAW edge Test");
			}

			data = Hex.Decode(input);

			eng.Init(true, pubParameters);

			try
			{
				data = eng.ProcessBlock(data, 0, data.Length);
			}
			catch (Exception e)
			{
				Fail("failed - exception " + e.ToString(), e);
			}

			eng.Init(false, privParameters);

			try
			{
				data = eng.ProcessBlock(data, 0, data.Length);
			}
			catch (Exception e)
			{
				Fail("failed - exception " + e.ToString(), e);
			}

			if (!input.Equals(Hex.ToHexString(data)))
			{
				Fail("failed RAW Test");
			}

			//
			// PKCS1 - public encrypt, private decrypt
			//
			eng = new Pkcs1Encoding(eng);

			eng.Init(true, pubParameters);

			if (eng.GetOutputBlockSize() != ((Pkcs1Encoding)eng).GetUnderlyingCipher().GetOutputBlockSize())
			{
				Fail("PKCS1 output block size incorrect");
			}

			try
			{
				data = eng.ProcessBlock(data, 0, data.Length);
			}
			catch (Exception e)
			{
				Fail("failed - exception " + e.ToString(), e);
			}

			eng.Init(false, privParameters);

			try
			{
				data = eng.ProcessBlock(data, 0, data.Length);
			}
			catch (Exception e)
			{
				Fail("failed - exception " + e.ToString(), e);
			}

			if (!input.Equals(Hex.ToHexString(data)))
			{
				Fail("failed PKCS1 public/private Test");
			}

			//
			// PKCS1 - private encrypt, public decrypt
			//
			eng = new Pkcs1Encoding(((Pkcs1Encoding)eng).GetUnderlyingCipher());

			eng.Init(true, privParameters);

			try
			{
				data = eng.ProcessBlock(data, 0, data.Length);
			}
			catch (Exception e)
			{
				Fail("failed - exception " + e.ToString(), e);
			}

			eng.Init(false, pubParameters);

			try
			{
				data = eng.ProcessBlock(data, 0, data.Length);
			}
			catch (Exception e)
			{
				Fail("failed - exception " + e.ToString(), e);
			}

			if (!input.Equals(Hex.ToHexString(data)))
			{
				Fail("failed PKCS1 private/public Test");
			}

			//
			// key generation test
			//
			RsaKeyPairGenerator pGen = new RsaKeyPairGenerator();
			RsaKeyGenerationParameters genParam = new RsaKeyGenerationParameters(
				BigInteger.ValueOf(0x11), new SecureRandom(), 768, 25);

			pGen.Init(genParam);

			AsymmetricCipherKeyPair pair = pGen.GenerateKeyPair();

			eng = new RsaBlindedEngine();

			if (((RsaKeyParameters)pair.Public).Modulus.BitLength < 768)
			{
				Fail("failed key generation (768) length test");
			}

			eng.Init(true, pair.Public);

			try
			{
				data = eng.ProcessBlock(data, 0, data.Length);
			}
			catch (Exception e)
			{
				Fail("failed - exception " + e.ToString(), e);
			}

			eng.Init(false, pair.Private);

			try
			{
				data = eng.ProcessBlock(data, 0, data.Length);
			}
			catch (Exception e)
			{
				Fail("failed - exception " + e.ToString(), e);
			}

			if (!input.Equals(Hex.ToHexString(data)))
			{
				Fail("failed key generation (768) Test");
			}

			genParam = new RsaKeyGenerationParameters(BigInteger.ValueOf(0x11), new SecureRandom(), 1024, 25);

			pGen.Init(genParam);
			pair = pGen.GenerateKeyPair();

			eng.Init(true, pair.Public);

			if (((RsaKeyParameters)pair.Public).Modulus.BitLength < 1024)
			{
				Fail("failed key generation (1024) length test");
			}

			try
			{
				data = eng.ProcessBlock(data, 0, data.Length);
			}
			catch (Exception e)
			{
				Fail("failed - exception " + e.ToString(), e);
			}

			eng.Init(false, pair.Private);

			try
			{
				data = eng.ProcessBlock(data, 0, data.Length);
			}
			catch (Exception e)
			{
				Fail("failed - exception " + e.ToString(), e);
			}

			if (!input.Equals(Hex.ToHexString(data)))
			{
				Fail("failed key generation (1024) test");
			}

			doTestOaep(pubParameters, privParameters);
			doTestStrictPkcs1Length(pubParameters, privParameters);
			doTestDudPkcs1Block(pubParameters, privParameters);
			doTestMissingDataPkcs1Block(pubParameters, privParameters);
			doTestTruncatedPkcs1Block(pubParameters, privParameters);
			doTestWrongPaddingPkcs1Block(pubParameters, privParameters);

			try
			{
				new RsaBlindedEngine().ProcessBlock(new byte[]{ 1 }, 0, 1);
				Fail("failed initialisation check");
			}
			catch (InvalidOperationException)
			{
				// expected
			}
		}
Example #14
0
        private static void RsaKeyGeneratorTest()
        {
            //RSA密钥对的构造器
            RsaKeyPairGenerator keyGenerator = new RsaKeyPairGenerator();
            //RSA密钥构造器的参数
            RsaKeyGenerationParameters param = new RsaKeyGenerationParameters(
                Org.BouncyCastle.Math.BigInteger.ValueOf(3),
                new Org.BouncyCastle.Security.SecureRandom(),
                1024,   //密钥长度
                25);
            //用参数初始化密钥构造器
            keyGenerator.Init(param);
            //产生密钥对
            AsymmetricCipherKeyPair keyPair = keyGenerator.GenerateKeyPair();
            //获取公钥和私钥
            AsymmetricKeyParameter publicKey = keyPair.Public;
            AsymmetricKeyParameter privateKey = keyPair.Private;

            if (((RsaKeyParameters)publicKey).Modulus.BitLength < 1024)
            {
                Console.WriteLine("failed key generation (1024) length test");
            }
            savetheKey(publicKey, privateKey);

            //一个测试……………………
            //输入,十六进制的字符串,解码为byte[]
            //string input = "4e6f77206973207468652074696d6520666f7220616c6c20676f6f64206d656e";
            //byte[] testData = Org.BouncyCastle.Utilities.Encoders.Hex.Decode(input);
            string input = "popozh RSA test";
            byte[] testData = Encoding.UTF8.GetBytes(input);
            //非对称加密算法,加解密用
            IAsymmetricBlockCipher engine = new RsaEngine();
            //公钥加密
            //从保存在本地的磁盘文件中读取公钥
            Asn1Object aobject = Asn1Object.FromStream(new FileStream(pubKeyFile, FileMode.Open, FileAccess.Read));  //a.puk??
            SubjectPublicKeyInfo pubInfo = SubjectPublicKeyInfo.GetInstance(aobject);
            AsymmetricKeyParameter testpublicKey = (RsaKeyParameters)PublicKeyFactory.CreateKey(pubInfo);
            FileStream fs;
            engine.Init(true, testpublicKey);
            try
            {
                //Console.WriteLine("加密前:" + Convert.ToBase64String(testData) + Environment.NewLine);
                testData = engine.ProcessBlock(testData, 0, testData.Length);
                Console.WriteLine("加密完成!" + Environment.NewLine);
                fs = new FileStream(ecyFile, FileMode.Create, FileAccess.Write);
                fs.Write(testData, 0, testData.Length);
                fs.Close();
                Console.WriteLine("保存密文成功" + Environment.NewLine);
            }
            catch (Exception ex)
            {
                Console.WriteLine("failed - exception " + Environment.NewLine + ex.ToString());
            }
            //私钥解密
            //获取加密的私钥,进行解密,获得私钥
            fs = new FileStream(ecyFile, FileMode.Open, FileAccess.Read);
            byte[] anothertestdata = new byte[1024];
            fs.Read(anothertestdata, 0, anothertestdata.Length);
            fs.Close();
            Asn1Object aobj = Asn1Object.FromStream(new FileStream(priKeyFile, FileMode.Open, FileAccess.Read));   //a.pvk??
            EncryptedPrivateKeyInfo enpri = EncryptedPrivateKeyInfo.GetInstance(aobj);
            char[] password = "******".ToCharArray();
            PrivateKeyInfo priKey = PrivateKeyInfoFactory.CreatePrivateKeyInfo(password, enpri);    //解密
            AsymmetricKeyParameter anotherprivateKey = PrivateKeyFactory.CreateKey(priKey);    //私钥
            engine.Init(false, anotherprivateKey);
            try
            {
                anothertestdata = engine.ProcessBlock(anothertestdata, 0, testData.Length);
                Console.WriteLine("解密后密文为:" + Encoding.UTF8.GetString(anothertestdata) + Environment.NewLine);
            }
            catch (Exception e)
            {
                Console.WriteLine("failed - exception " + e.ToString());
            }

            Console.Read();
        }
Example #15
0
		public static AsymmetricCipherKeyPair GenerateBouncyKeyPair()
		{
			// Construct a new public/private key pair (RSA 2048 bits)
			IAsymmetricCipherKeyPairGenerator KeyGen = GeneratorUtilities.GetKeyPairGenerator("RSA");
			RsaKeyGenerationParameters KeyParams = new RsaKeyGenerationParameters(BigInteger.ValueOf(0x10001), new SecureRandom(), 2048, 25);
			KeyGen.Init(KeyParams);

			AsymmetricCipherKeyPair KeyPair = KeyGen.GenerateKeyPair();

			return KeyPair;
		}
Example #16
0
        /// <summary>
        /// Generates a new RSA key pair for the certificate and subsequent signing operation with the key strength parameter
        /// </summary>
        /// <param name="keyStrength">Can take values of 1024, 2048, 3072 or 4096</param>
        internal void GenerateKeys(int keyStrength)
        {
            if (keyStrength % 1024 != 0 && keyStrength > 4096)
            {
                throw new ApplicationException("bit strengths greater than 4096 not supported and key size must be a multiple of 1024");
            }

            SecureRandom random = new SecureRandom();
            RsaKeyGenerationParameters parameters = new RsaKeyGenerationParameters(
                BigInteger.One, random, keyStrength, 25);

            generator.Init(parameters);
            keyPair = generator.GenerateKeyPair();
        }
        public override bool Equals(object obj)
        {
            RsaKeyGenerationParameters rsaKeyGenerationParameters = obj as RsaKeyGenerationParameters;

            return(rsaKeyGenerationParameters != null && this.certainty == rsaKeyGenerationParameters.certainty && this.publicExponent.Equals(rsaKeyGenerationParameters.publicExponent));
        }
 public KeyRingParams()
 {
     //Org.BouncyCastle.Crypto.Tls.EncryptionAlgorithm
     RsaParams = new RsaKeyGenerationParameters(BigInteger.ValueOf(0x10001), new SecureRandom(), 2048, 12);
 }
Example #19
0
        public override void PerformTest()
        {
            //
            // Read the public key
            //
            PgpPublicKeyRing pgpPub = new PgpPublicKeyRing(testPubKey);

            AsymmetricKeyParameter pubKey = pgpPub.GetPublicKey().GetKey();

            IEnumerator enumerator = pgpPub.GetPublicKey().GetUserIds().GetEnumerator();
            enumerator.MoveNext();
            string uid = (string) enumerator.Current;


            enumerator = pgpPub.GetPublicKey().GetSignaturesForId(uid).GetEnumerator();
            enumerator.MoveNext();
            PgpSignature sig = (PgpSignature) enumerator.Current;

            sig.InitVerify(pgpPub.GetPublicKey());

            if (!sig.VerifyCertification(uid, pgpPub.GetPublicKey()))
            {
                Fail("failed to verify certification");
            }

            //
            // write a public key
            //
            MemoryStream bOut = new UncloseableMemoryStream();
            BcpgOutputStream pOut = new BcpgOutputStream(bOut);

            pgpPub.Encode(pOut);

            if (!Arrays.AreEqual(bOut.ToArray(), testPubKey))
            {
                Fail("public key rewrite failed");
            }

            //
            // Read the public key
            //
            PgpPublicKeyRing pgpPubV3 = new PgpPublicKeyRing(testPubKeyV3);
            AsymmetricKeyParameter pubKeyV3 = pgpPub.GetPublicKey().GetKey();

            //
            // write a V3 public key
            //
            bOut = new UncloseableMemoryStream();
            pOut = new BcpgOutputStream(bOut);

            pgpPubV3.Encode(pOut);

            //
            // Read a v3 private key
            //
            char[] passP = "FIXCITY_QA".ToCharArray();

            {
                PgpSecretKeyRing pgpPriv2 = new PgpSecretKeyRing(testPrivKeyV3);
                PgpSecretKey pgpPrivSecretKey = pgpPriv2.GetSecretKey();
                PgpPrivateKey pgpPrivKey2 = pgpPrivSecretKey.ExtractPrivateKey(passP);

                //
                // write a v3 private key
                //
                bOut = new UncloseableMemoryStream();
                pOut = new BcpgOutputStream(bOut);

                pgpPriv2.Encode(pOut);

                byte[] result = bOut.ToArray();
                if (!Arrays.AreEqual(result, testPrivKeyV3))
                {
                    Fail("private key V3 rewrite failed");
                }
            }

            //
            // Read the private key
            //
            PgpSecretKeyRing pgpPriv = new PgpSecretKeyRing(testPrivKey);
            PgpPrivateKey pgpPrivKey = pgpPriv.GetSecretKey().ExtractPrivateKey(pass);

            //
            // write a private key
            //
            bOut = new UncloseableMemoryStream();
            pOut = new BcpgOutputStream(bOut);

            pgpPriv.Encode(pOut);

            if (!Arrays.AreEqual(bOut.ToArray(), testPrivKey))
            {
                Fail("private key rewrite failed");
            }

            //
            // test encryption
            //
            IBufferedCipher c = CipherUtilities.GetCipher("RSA");

//                c.Init(Cipher.ENCRYPT_MODE, pubKey);
            c.Init(true, pubKey);

            byte[] inBytes = Encoding.ASCII.GetBytes("hello world");
            byte[] outBytes = c.DoFinal(inBytes);

//                c.Init(Cipher.DECRYPT_MODE, pgpPrivKey.GetKey());
            c.Init(false, pgpPrivKey.Key);

            outBytes = c.DoFinal(outBytes);

            if (!Arrays.AreEqual(inBytes, outBytes))
            {
                Fail("decryption failed.");
            }

            //
            // test signature message
            //
            PgpObjectFactory pgpFact = new PgpObjectFactory(sig1);

            PgpCompressedData c1 = (PgpCompressedData)pgpFact.NextPgpObject();

            pgpFact = new PgpObjectFactory(c1.GetDataStream());

            PgpOnePassSignatureList p1 = (PgpOnePassSignatureList)pgpFact.NextPgpObject();

            PgpOnePassSignature ops = p1[0];

            PgpLiteralData p2 = (PgpLiteralData)pgpFact.NextPgpObject();

            Stream dIn = p2.GetInputStream();

            ops.InitVerify(pgpPub.GetPublicKey(ops.KeyId));

            int ch;
            while ((ch = dIn.ReadByte()) >= 0)
            {
                ops.Update((byte)ch);
            }

            PgpSignatureList p3 = (PgpSignatureList)pgpFact.NextPgpObject();

            if (!ops.Verify(p3[0]))
            {
                Fail("Failed signature check");
            }

            //
            // encrypted message - read subkey
            //
            pgpPriv = new PgpSecretKeyRing(subKey);

            //
            // encrypted message
            //
            byte[] text = Encoding.ASCII.GetBytes("hello world!\n");

            PgpObjectFactory pgpF = new PgpObjectFactory(enc1);

            PgpEncryptedDataList encList = (PgpEncryptedDataList)pgpF.NextPgpObject();

            PgpPublicKeyEncryptedData encP = (PgpPublicKeyEncryptedData)encList[0];

            pgpPrivKey = pgpPriv.GetSecretKey(encP.KeyId).ExtractPrivateKey(pass);

            Stream clear = encP.GetDataStream(pgpPrivKey);

            pgpFact = new PgpObjectFactory(clear);

            c1 = (PgpCompressedData)pgpFact.NextPgpObject();

            pgpFact = new PgpObjectFactory(c1.GetDataStream());

            PgpLiteralData ld = (PgpLiteralData)pgpFact.NextPgpObject();

            if (!ld.FileName.Equals("test.txt"))
            {
                throw new Exception("wrong filename in packet");
            }

            Stream inLd = ld.GetDataStream();
            byte[] bytes = Streams.ReadAll(inLd);

            if (!Arrays.AreEqual(bytes, text))
            {
                Fail("wrong plain text in decrypted packet");
            }

            //
            // encrypt - short message
            //
            byte[] shortText = { (byte)'h', (byte)'e', (byte)'l', (byte)'l', (byte)'o' };

            MemoryStream cbOut = new UncloseableMemoryStream();
            PgpEncryptedDataGenerator cPk = new PgpEncryptedDataGenerator(SymmetricKeyAlgorithmTag.Cast5, new SecureRandom());
            PgpPublicKey puK = pgpPriv.GetSecretKey(encP.KeyId).PublicKey;

            cPk.AddMethod(puK);

            Stream cOut = cPk.Open(new UncloseableStream(cbOut), shortText.Length);

            cOut.Write(shortText, 0, shortText.Length);

            cOut.Close();

            pgpF = new PgpObjectFactory(cbOut.ToArray());

            encList = (PgpEncryptedDataList)pgpF.NextPgpObject();

            encP = (PgpPublicKeyEncryptedData)encList[0];

            pgpPrivKey = pgpPriv.GetSecretKey(encP.KeyId).ExtractPrivateKey(pass);

            if (encP.GetSymmetricAlgorithm(pgpPrivKey) != SymmetricKeyAlgorithmTag.Cast5)
            {
                Fail("symmetric algorithm mismatch");
            }

            clear = encP.GetDataStream(pgpPrivKey);
            outBytes = Streams.ReadAll(clear);

            if (!Arrays.AreEqual(outBytes, shortText))
            {
                Fail("wrong plain text in generated short text packet");
            }

            //
            // encrypt
            //
            cbOut = new UncloseableMemoryStream();
            cPk = new PgpEncryptedDataGenerator(SymmetricKeyAlgorithmTag.Cast5, new SecureRandom());
            puK = pgpPriv.GetSecretKey(encP.KeyId).PublicKey;

            cPk.AddMethod(puK);

            cOut = cPk.Open(new UncloseableStream(cbOut), text.Length);

            cOut.Write(text, 0, text.Length);

            cOut.Close();

            pgpF = new PgpObjectFactory(cbOut.ToArray());

            encList = (PgpEncryptedDataList)pgpF.NextPgpObject();

            encP = (PgpPublicKeyEncryptedData)encList[0];

            pgpPrivKey = pgpPriv.GetSecretKey(encP.KeyId).ExtractPrivateKey(pass);

            clear = encP.GetDataStream(pgpPrivKey);
            outBytes = Streams.ReadAll(clear);

            if (!Arrays.AreEqual(outBytes, text))
            {
                Fail("wrong plain text in generated packet");
            }

            //
            // read public key with sub key.
            //
            pgpF = new PgpObjectFactory(subPubKey);
            object o;
            while ((o = pgpFact.NextPgpObject()) != null)
            {
                // TODO Should something be tested here?
                // Console.WriteLine(o);
            }

            //
            // key pair generation - CAST5 encryption
            //
            char[] passPhrase = "hello".ToCharArray();
            IAsymmetricCipherKeyPairGenerator kpg = GeneratorUtilities.GetKeyPairGenerator("RSA");
            RsaKeyGenerationParameters genParam = new RsaKeyGenerationParameters(
                BigInteger.ValueOf(0x10001), new SecureRandom(), 1024, 25);

            kpg.Init(genParam);


            AsymmetricCipherKeyPair kp = kpg.GenerateKeyPair();

            PgpSecretKey secretKey = new PgpSecretKey(
                PgpSignature.DefaultCertification,
                PublicKeyAlgorithmTag.RsaGeneral,
                kp.Public,
                kp.Private,
                DateTime.UtcNow,
                "fred",
                SymmetricKeyAlgorithmTag.Cast5,
                passPhrase,
                null,
                null,
                new SecureRandom()
                );

            PgpPublicKey key = secretKey.PublicKey;


            enumerator = key.GetUserIds().GetEnumerator();
            enumerator.MoveNext();
            uid = (string) enumerator.Current;


            enumerator = key.GetSignaturesForId(uid).GetEnumerator();
            enumerator.MoveNext();
            sig = (PgpSignature) enumerator.Current;

            sig.InitVerify(key);

            if (!sig.VerifyCertification(uid, key))
            {
                Fail("failed to verify certification");
            }

            pgpPrivKey = secretKey.ExtractPrivateKey(passPhrase);

            key = PgpPublicKey.RemoveCertification(key, uid, sig);

            if (key == null)
            {
                Fail("failed certification removal");
            }

            byte[] keyEnc = key.GetEncoded();

            key = PgpPublicKey.AddCertification(key, uid, sig);

            keyEnc = key.GetEncoded();

            PgpSignatureGenerator sGen = new PgpSignatureGenerator(PublicKeyAlgorithmTag.RsaGeneral, HashAlgorithmTag.Sha1);

            sGen.InitSign(PgpSignature.KeyRevocation, secretKey.ExtractPrivateKey(passPhrase));

            sig = sGen.GenerateCertification(key);

            key = PgpPublicKey.AddCertification(key, sig);

            keyEnc = key.GetEncoded();

            PgpPublicKeyRing tmpRing = new PgpPublicKeyRing(keyEnc);

            key = tmpRing.GetPublicKey();

            IEnumerator sgEnum = key.GetSignaturesOfType(PgpSignature.KeyRevocation).GetEnumerator();
            sgEnum.MoveNext();
            sig = (PgpSignature) sgEnum.Current;

            sig.InitVerify(key);

            if (!sig.VerifyCertification(key))
            {
                Fail("failed to verify revocation certification");
            }

            //
            // use of PgpKeyPair
            //
            PgpKeyPair pgpKp = new PgpKeyPair(PublicKeyAlgorithmTag.RsaGeneral,
                kp.Public, kp.Private, DateTime.UtcNow);

            PgpPublicKey k1 = pgpKp.PublicKey;
            PgpPrivateKey k2 = pgpKp.PrivateKey;

            k1.GetEncoded();

            MixedTest(k2, k1);

            //
            // key pair generation - AES_256 encryption.
            //
            kp = kpg.GenerateKeyPair();

            secretKey = new PgpSecretKey(PgpSignature.DefaultCertification, PublicKeyAlgorithmTag.RsaGeneral, kp.Public, kp.Private, DateTime.UtcNow, "fred", SymmetricKeyAlgorithmTag.Aes256, passPhrase, null, null, new SecureRandom());

            secretKey.ExtractPrivateKey(passPhrase);

            secretKey.Encode(new UncloseableMemoryStream());

            //
            // secret key password changing.
            //
            const string newPass = "******";

            secretKey = PgpSecretKey.CopyWithNewPassword(secretKey, passPhrase, newPass.ToCharArray(), secretKey.KeyEncryptionAlgorithm, new SecureRandom());

            secretKey.ExtractPrivateKey(newPass.ToCharArray());

            secretKey.Encode(new UncloseableMemoryStream());

            key = secretKey.PublicKey;

            key.Encode(new UncloseableMemoryStream());


            enumerator = key.GetUserIds().GetEnumerator();
            enumerator.MoveNext();
            uid = (string) enumerator.Current;


            enumerator = key.GetSignaturesForId(uid).GetEnumerator();
            enumerator.MoveNext();
            sig = (PgpSignature) enumerator.Current;

            sig.InitVerify(key);

            if (!sig.VerifyCertification(uid, key))
            {
                Fail("failed to verify certification");
            }

            pgpPrivKey = secretKey.ExtractPrivateKey(newPass.ToCharArray());

            //
            // signature generation
            //
            const string data = "hello world!";
            byte[] dataBytes = Encoding.ASCII.GetBytes(data);

            bOut = new UncloseableMemoryStream();

            MemoryStream testIn = new MemoryStream(dataBytes, false);

            sGen = new PgpSignatureGenerator(
                PublicKeyAlgorithmTag.RsaGeneral, HashAlgorithmTag.Sha1);

            sGen.InitSign(PgpSignature.BinaryDocument, pgpPrivKey);

            PgpCompressedDataGenerator cGen = new PgpCompressedDataGenerator(
                CompressionAlgorithmTag.Zip);

            BcpgOutputStream bcOut = new BcpgOutputStream(cGen.Open(new UncloseableStream(bOut)));

            sGen.GenerateOnePassVersion(false).Encode(bcOut);

            PgpLiteralDataGenerator lGen = new PgpLiteralDataGenerator();

            DateTime testDateTime = new DateTime(1973, 7, 27);
            Stream lOut = lGen.Open(new UncloseableStream(bcOut), PgpLiteralData.Binary, "_CONSOLE",
                dataBytes.Length, testDateTime);

            // TODO Need a stream object to automatically call Update?
            // (via ISigner implementation of PgpSignatureGenerator)
            while ((ch = testIn.ReadByte()) >= 0)
            {
                lOut.WriteByte((byte)ch);
                sGen.Update((byte)ch);
            }

            lOut.Close();

            sGen.Generate().Encode(bcOut);

            bcOut.Close();

            //
            // verify generated signature
            //
            pgpFact = new PgpObjectFactory(bOut.ToArray());

            c1 = (PgpCompressedData)pgpFact.NextPgpObject();

            pgpFact = new PgpObjectFactory(c1.GetDataStream());

            p1 = (PgpOnePassSignatureList)pgpFact.NextPgpObject();

            ops = p1[0];

            p2 = (PgpLiteralData)pgpFact.NextPgpObject();
            if (!p2.ModificationTime.Equals(testDateTime))
            {
                Fail("Modification time not preserved");
            }

            dIn = p2.GetInputStream();

            ops.InitVerify(secretKey.PublicKey);

            // TODO Need a stream object to automatically call Update?
            // (via ISigner implementation of PgpSignatureGenerator)
            while ((ch = dIn.ReadByte()) >= 0)
            {
                ops.Update((byte)ch);
            }

            p3 = (PgpSignatureList)pgpFact.NextPgpObject();

            if (!ops.Verify(p3[0]))
            {
                Fail("Failed generated signature check");
            }

            //
            // signature generation - version 3
            //
            bOut = new UncloseableMemoryStream();

            testIn = new MemoryStream(dataBytes);
            PgpV3SignatureGenerator sGenV3 = new PgpV3SignatureGenerator(
                PublicKeyAlgorithmTag.RsaGeneral, HashAlgorithmTag.Sha1);

            sGen.InitSign(PgpSignature.BinaryDocument, pgpPrivKey);

            cGen = new PgpCompressedDataGenerator(CompressionAlgorithmTag.Zip);

            bcOut = new BcpgOutputStream(cGen.Open(new UncloseableStream(bOut)));

            sGen.GenerateOnePassVersion(false).Encode(bcOut);

            lGen = new PgpLiteralDataGenerator();
            lOut = lGen.Open(
                new UncloseableStream(bcOut),
                PgpLiteralData.Binary,
                "_CONSOLE",
                dataBytes.Length,
                testDateTime);

            // TODO Need a stream object to automatically call Update?
            // (via ISigner implementation of PgpSignatureGenerator)
            while ((ch = testIn.ReadByte()) >= 0)
            {
                lOut.WriteByte((byte) ch);
                sGen.Update((byte)ch);
            }

            lOut.Close();

            sGen.Generate().Encode(bcOut);

            bcOut.Close();

            //
            // verify generated signature
            //
            pgpFact = new PgpObjectFactory(bOut.ToArray());

            c1 = (PgpCompressedData)pgpFact.NextPgpObject();

            pgpFact = new PgpObjectFactory(c1.GetDataStream());

            p1 = (PgpOnePassSignatureList)pgpFact.NextPgpObject();

            ops = p1[0];

            p2 = (PgpLiteralData)pgpFact.NextPgpObject();
            if (!p2.ModificationTime.Equals(testDateTime))
            {
                Fail("Modification time not preserved");
            }

            dIn = p2.GetInputStream();

            ops.InitVerify(secretKey.PublicKey);

            // TODO Need a stream object to automatically call Update?
            // (via ISigner implementation of PgpSignatureGenerator)
            while ((ch = dIn.ReadByte()) >= 0)
            {
                ops.Update((byte)ch);
            }

            p3 = (PgpSignatureList)pgpFact.NextPgpObject();

            if (!ops.Verify(p3[0]))
            {
                Fail("Failed v3 generated signature check");
            }

            //
            // extract PGP 8 private key
            //
            pgpPriv = new PgpSecretKeyRing(pgp8Key);

            secretKey = pgpPriv.GetSecretKey();

            pgpPrivKey = secretKey.ExtractPrivateKey(pgp8Pass);

            //
            // other sig tests
            //
            PerformTestSig(HashAlgorithmTag.Sha256, secretKey.PublicKey, pgpPrivKey);
            PerformTestSig(HashAlgorithmTag.Sha384, secretKey.PublicKey, pgpPrivKey);
            PerformTestSig(HashAlgorithmTag.Sha512, secretKey.PublicKey, pgpPrivKey);
            FingerPrintTest();
            ExistingEmbeddedJpegTest();
            EmbeddedJpegTest();
        }
            public KeyRingParams()
            {
                var randomGenerator = new CryptoApiRandomGenerator();
                var random = new SecureRandom(randomGenerator);

                //Org.BouncyCastle.Crypto.Tls.EncryptionAlgorithm
                RsaParams = new RsaKeyGenerationParameters(BigInteger.ValueOf(0x10001), random, 4096, 12); //new SecureRandom(), 2048, 12);
            }
Example #21
0
        /// <summary>
        /// Create the actual certificate
        /// </summary>
        public static bool CreateCertificate(ICertificateSettings settings, Action<string> log, out string thumbprint, out string errorMessage)
        {
            errorMessage = string.Empty;
            thumbprint = string.Empty;

            try
            {
                var keyStore = new Pkcs12Store();

                log(Strings.GeneratingKeys);
                var pGen = new RsaKeyPairGenerator();
                var genParam = new
                    RsaKeyGenerationParameters(
                    BigInteger.ValueOf(0x10001),
                    new SecureRandom(),
                    1024,
                    10);
                pGen.Init(genParam);
                var keyPair = pGen.GenerateKeyPair();

                log(Strings.GeneratingCertificate);
                var attrs = new Dictionary<DerObjectIdentifier, string>();
                var oids = new List<DerObjectIdentifier> { X509Name.O, X509Name.L, X509Name.C, X509Name.CN, X509Name.EmailAddress, X509Name.OU, X509Name.ST };
                oids.Reverse();
                if (!string.IsNullOrEmpty(settings.OrgName)) attrs.Add(X509Name.O, settings.OrgName); else oids.Remove(X509Name.O);
                if (!string.IsNullOrEmpty(settings.OrgUnit)) attrs.Add(X509Name.OU, settings.OrgUnit); else oids.Remove(X509Name.OU);
                if (!string.IsNullOrEmpty(settings.City)) attrs.Add(X509Name.L, settings.City); else oids.Remove(X509Name.L);
                if (!string.IsNullOrEmpty(settings.CountryCode)) attrs.Add(X509Name.C, settings.CountryCode); else oids.Remove(X509Name.C);
                if (!string.IsNullOrEmpty(settings.State)) attrs.Add(X509Name.ST, settings.State); else oids.Remove(X509Name.ST);
                if (!string.IsNullOrEmpty(settings.Email)) attrs.Add(X509Name.EmailAddress, settings.Email); else oids.Remove(X509Name.EmailAddress);
                if (!string.IsNullOrEmpty(settings.UserName)) attrs.Add(X509Name.CN, settings.UserName); else oids.Remove(X509Name.CN);

                var certGen = new X509V3CertificateGenerator();
                var random = new SecureRandom();

                certGen.SetSerialNumber(BigInteger.ValueOf(Math.Abs(random.NextInt())));
                certGen.SetIssuerDN(new X509Name(oids, attrs));
                certGen.SetNotBefore(DateTime.Today.Subtract(new TimeSpan(1, 0, 0, 0)));
                var years = Math.Min(settings.MaxYears, 50);
                certGen.SetNotAfter(DateTime.Today.AddYears(years));
                certGen.SetSubjectDN(new X509Name(oids, attrs));
                certGen.SetPublicKey(keyPair.Public);
                certGen.SetSignatureAlgorithm("SHA1WithRSAEncryption");

                var cert = certGen.Generate(keyPair.Private);

                // Save
                log(Strings.SavingCertificate);
                var keyEntry = new AsymmetricKeyEntry(keyPair.Private);
                var certEntry = new X509CertificateEntry(cert);
                const string alias = "alias";
                keyStore.SetKeyEntry(alias, keyEntry, new[] { certEntry });

                var password = settings.Password;
                var memoryStream = new MemoryStream();
                keyStore.Save(memoryStream, password.ToCharArray(), random);
                memoryStream.Position = 0;

                // Save certificate
                var path = settings.Path;
                var folder = Path.GetDirectoryName(path);
                if (!string.IsNullOrEmpty(folder))
                    Directory.CreateDirectory(folder);

                // Set path in finished page.
                using (var fileStream = new FileStream(path, FileMode.Create, FileAccess.Write))
                {
                    memoryStream.WriteTo(fileStream);
                }

                if (settings.ImportInCertificateStore)
                {
                    log("Importing certificate in My Certificates store");
                    var certificate = new X509Certificate2(path, password,
                                                           X509KeyStorageFlags.Exportable |
                                                           X509KeyStorageFlags.PersistKeySet);
                    thumbprint = certificate.Thumbprint;
                    var x509Store2 = new X509Store(StoreName.My, StoreLocation.CurrentUser);
                    try
                    {
                        x509Store2.Open(OpenFlags.ReadWrite);
                        x509Store2.Add(certificate);
                        x509Store2.Close();
                    }
                    catch (Exception ex)
                    {
                        errorMessage = string.Format("Failed to import certificate because: {0}", ex.Message);
                        return false;
                    }
                }

                if (years < 30)
                {
                    log("Certificate is intended for evaluation purposes. It cannot be used to deploy to the market.");
                }
                return true;
            }
            catch (Exception ex)
            {
                ErrorLog.DumpError(ex);
                errorMessage = string.Format("Failed to create certificate because {0}.", ex.Message);
                return false;
            }
        }
        //PrivateKey priv, PublicKey pub)
        // TODO Move this when other JCE tests are ported from Java
        /**
         * signature with a "forged signature" (sig block not at end of plain text)
         */
        private void doTestBadSig()
        {
            //			Signature           sig = Signature.getInstance("SHA1WithRSAEncryption", "BC");
            ISigner sig = SignerUtilities.GetSigner("SHA1WithRSAEncryption");
            //			KeyPairGenerator    fact;
            //			KeyPair             keyPair;
            //			byte[]              data = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };

            //			fact = KeyPairGenerator.getInstance("RSA", "BC");
            RsaKeyPairGenerator fact = new RsaKeyPairGenerator();

            //			fact.initialize(768, new SecureRandom());
            RsaKeyGenerationParameters factParams = new RsaKeyGenerationParameters(
            //				BigInteger.ValueOf(0x11), new SecureRandom(), 768, 25);
                BigInteger.ValueOf(3), new SecureRandom(), 768, 25);
            fact.Init(factParams);

            //			keyPair = fact.generateKeyPair();
            //
            //			PrivateKey  signingKey = keyPair.getPrivate();
            //			PublicKey   verifyKey = keyPair.getPublic();
            IAsymmetricCipherKeyPair keyPair = fact.GenerateKeyPair();

            IAsymmetricKeyParameter priv = keyPair.Private;
            IAsymmetricKeyParameter pub = keyPair.Public;

            //			testBadSig(signingKey, verifyKey);

            //			MessageDigest sha1 = MessageDigest.getInstance("SHA1", "BC");
            IDigest sha1 = DigestUtilities.GetDigest("SHA1");

            //			Cipher signer = Cipher.getInstance("RSA/ECB/PKCS1Padding", "BC");
            //			IBufferedCipher signer = CipherUtilities.GetCipher("RSA/ECB/PKCS1Padding");
            IAsymmetricBlockCipher signer = new Pkcs1Encoding(new RsaEngine());

            //			signer.init(Cipher.ENCRYPT_MODE, priv);
            signer.Init(true, priv);

            //			byte[] block = new byte[signer.getBlockSize()];
            //			byte[] block = new byte[signer.GetBlockSize()];
            byte[] block = new byte[signer.GetInputBlockSize()];

            //			sha1.update((byte)0);
            sha1.Update(0);

            //			byte[] sigHeader = Hex.decode("3021300906052b0e03021a05000414");
            byte[] sigHeader = Hex.Decode("3021300906052b0e03021a05000414");
            //			System.arraycopy(sigHeader, 0, block, 0, sigHeader.length);
            Array.Copy(sigHeader, 0, block, 0, sigHeader.Length);

            //			sha1.digest(block, sigHeader.length, sha1.getDigestLength());
            sha1.DoFinal(block, sigHeader.Length);

            //			System.arraycopy(sigHeader, 0, block,
            //				sigHeader.length + sha1.getDigestLength(), sigHeader.length);
            Array.Copy(sigHeader, 0, block,
                sigHeader.Length + sha1.GetDigestSize(), sigHeader.Length);

            //			byte[] sigBytes = signer.doFinal(block);
            byte[] sigBytes = signer.ProcessBlock(block, 0, block.Length);

            //			Signature verifier = Signature.getInstance("SHA1WithRSA", "BC");
            ISigner verifier = SignerUtilities.GetSigner("SHA1WithRSA");

            //			verifier.initVerify(pub);
            verifier.Init(false, pub);

            //			verifier.update((byte)0);
            verifier.Update(0);

            //			if (verifier.verify(sig))
            if (verifier.VerifySignature(sigBytes))
            {
            //				fail("bad signature passed");
                Fail("bad signature passed");
            }
        }