public void TestNONEwithDSA()
        {
            byte[] dummySha1 = Hex.Decode("01020304050607080910111213141516");

            SecureRandom rand = new SecureRandom();

            DsaParametersGenerator pGen = new DsaParametersGenerator();
            pGen.Init(512, 80, rand);

            IAsymmetricCipherKeyPairGenerator g = GeneratorUtilities.GetKeyPairGenerator("DSA");
            g.Init(new DsaKeyGenerationParameters(rand, pGen.GenerateParameters()));

            IAsymmetricCipherKeyPair kp = g.GenerateKeyPair();

            ISigner sig = SignerUtilities.GetSigner("NONEwithDSA");
            sig.Init(true, kp.Private);
            sig.BlockUpdate(dummySha1, 0, dummySha1.Length);
            byte[] sigBytes = sig.GenerateSignature();

            sig.Init(false, kp.Public);
            sig.BlockUpdate(dummySha1, 0, dummySha1.Length);
            sig.VerifySignature(sigBytes);

            // reset test

            sig.BlockUpdate(dummySha1, 0, dummySha1.Length);

            if (!sig.VerifySignature(sigBytes))
            {
                Fail("NONEwithDSA failed to reset");
            }

            // lightweight test
            DsaSigner signer = new DsaSigner();
            Asn1Sequence derSig = Asn1Sequence.GetInstance(Asn1Object.FromByteArray(sigBytes));

            signer.Init(false, kp.Public);

            if (!signer.VerifySignature(dummySha1,
                DerInteger.GetInstance(derSig[0]).Value, DerInteger.GetInstance(derSig[1]).Value))
            {
                Fail("NONEwithDSA not really NONE!");
            }
        }
		public virtual void Init(int size, int certainty, SecureRandom random)
		{
			if (!DsaParametersGenerator.IsValidDsaStrength(size))
			{
				throw new ArgumentException("size must be from 512 - 1024 and a multiple of 64", "size");
			}
			this.use186_3 = false;
			this.L = size;
			this.N = DsaParametersGenerator.GetDefaultN(size);
			this.certainty = certainty;
			this.random = random;
		}
		protected virtual BigInteger CalculateGenerator_FIPS186_3_Verifiable(IDigest d, BigInteger p, BigInteger q, byte[] seed, int index)
		{
			BigInteger e = p.Subtract(BigInteger.One).Divide(q);
			byte[] array = Hex.Decode("6767656E");
			byte[] array2 = new byte[seed.Length + array.Length + 1 + 2];
			Array.Copy(seed, 0, array2, 0, seed.Length);
			Array.Copy(array, 0, array2, seed.Length, array.Length);
			array2[array2.Length - 3] = (byte)index;
			byte[] array3 = new byte[d.GetDigestSize()];
			for (int i = 1; i < 65536; i++)
			{
				DsaParametersGenerator.Inc(array2);
				DsaParametersGenerator.Hash(d, array2, array3);
				BigInteger bigInteger = new BigInteger(1, array3);
				BigInteger bigInteger2 = bigInteger.ModPow(e, p);
				if (bigInteger2.CompareTo(BigInteger.Two) >= 0)
				{
					return bigInteger2;
				}
			}
			return null;
		}
 public static IAsymmetricCipherKeyPairGenerator CreateGenerator(SecureRandom random, TypeWrapper kpGen,
                                                                 int keystrength)
 {
     var keypairGen = kpGen.Instance<IAsymmetricCipherKeyPairGenerator>();
     //var random = SecureRandomUtils.GetInstance(Model.RandomGenerator, Model.RandomGeneratorArgument);
     if (keypairGen is DsaKeyPairGenerator)
     {
         DsaParametersGenerator pGen = new DsaParametersGenerator();
         pGen.Init(keystrength, 80, random); //TODO:
         DsaParameters parameters = pGen.GenerateParameters();
         DsaKeyGenerationParameters genParam = new DsaKeyGenerationParameters(random, parameters);
         keypairGen.Init(genParam);
         return keypairGen;
     }
     if (keypairGen is ECKeyPairGenerator)
     {
         keypairGen.Init(new KeyGenerationParameters(random, keystrength));
         return keypairGen;
     }
     keypairGen.Init(new KeyGenerationParameters(random, keystrength));
     return keypairGen;
 }
Exemple #5
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");
              }
        }
        public void TestGeneration()
        {
            ISigner s = SignerUtilities.GetSigner("DSA");
            byte[] data = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
            SecureRandom rand = new SecureRandom();

            // KeyPairGenerator g = KeyPairGenerator.GetInstance("DSA");
            IAsymmetricCipherKeyPairGenerator g = GeneratorUtilities.GetKeyPairGenerator("DSA");

            // test exception
            //

            doTestBadStrength(513);
            doTestBadStrength(510);
            doTestBadStrength(1025);

            //g.initialize(512, rand);
            {
                DsaParametersGenerator pGen = new DsaParametersGenerator();
                pGen.Init(512, 80, rand);

                g.Init(new DsaKeyGenerationParameters(rand, pGen.GenerateParameters()));
            }

            IAsymmetricCipherKeyPair p = g.GenerateKeyPair();

            IAsymmetricKeyParameter sKey = p.Private;
            IAsymmetricKeyParameter vKey = p.Public;

            s.Init(true, sKey);

            s.BlockUpdate(data, 0, data.Length);

            byte[] sigBytes = s.GenerateSignature();

            s = SignerUtilities.GetSigner("DSA");

            s.Init(false, vKey);

            s.BlockUpdate(data, 0, data.Length);

            if (!s.VerifySignature(sigBytes))
            {
                Fail("DSA verification failed");
            }

            //
            // ECDSA Fp generation test
            //
            s = SignerUtilities.GetSigner("ECDSA");

            ECCurve curve = new FPCurve(
                new BigInteger("883423532389192164791648750360308885314476597252960362792450860609699839"), // q
                new BigInteger("7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc", 16), // a
                new BigInteger("6b016c3bdcf18941d0d654921475ca71a9db2fb27d1d37796185c2942c0a", 16)); // b

            ECDomainParameters ecSpec = new ECDomainParameters(
                curve,
                curve.DecodePoint(Hex.Decode("020ffa963cdca8816ccc33b8642bedf905c3d358573d3f27fbbd3b3cb9aaaf")), // G
                new BigInteger("883423532389192164791648750360308884807550341691627752275345424702807307")); // n

            g = GeneratorUtilities.GetKeyPairGenerator("ECDSA");
            g.Init(new ECKeyGenerationParameters(ecSpec, rand));

            p = g.GenerateKeyPair();

            sKey = p.Private;
            vKey = p.Public;

            s.Init(true, sKey);

            s.BlockUpdate(data, 0, data.Length);

            sigBytes = s.GenerateSignature();

            s = SignerUtilities.GetSigner("ECDSA");

            s.Init(false, vKey);

            s.BlockUpdate(data, 0, data.Length);

            if (!s.VerifySignature(sigBytes))
            {
                Fail("ECDSA verification failed");
            }

            //
            // ECDSA F2m generation test
            //
            s = SignerUtilities.GetSigner("ECDSA");

            curve = new F2MCurve(
                    239, // m
                    36, // k
                    new BigInteger("32010857077C5431123A46B808906756F543423E8D27877578125778AC76", 16), // a
                    new BigInteger("790408F2EEDAF392B012EDEFB3392F30F4327C0CA3F31FC383C422AA8C16", 16)); // b

            ecSpec = new ECDomainParameters(
                curve,
                curve.DecodePoint(Hex.Decode("0457927098FA932E7C0A96D3FD5B706EF7E5F5C156E16B7E7C86038552E91D61D8EE5077C33FECF6F1A16B268DE469C3C7744EA9A971649FC7A9616305")), // G
                new BigInteger("220855883097298041197912187592864814557886993776713230936715041207411783"), // n
                BigInteger.ValueOf(4)); // h

            g = GeneratorUtilities.GetKeyPairGenerator("ECDSA");
            g.Init(new ECKeyGenerationParameters(ecSpec, rand));

            p = g.GenerateKeyPair();

            sKey = p.Private;
            vKey = p.Public;

            s.Init(true, sKey);

            s.BlockUpdate(data, 0, data.Length);

            sigBytes = s.GenerateSignature();

            s = SignerUtilities.GetSigner("ECDSA");

            s.Init(false, vKey);

            s.BlockUpdate(data, 0, data.Length);

            if (!s.VerifySignature(sigBytes))
            {
                Fail("ECDSA verification failed");
            }
        }
		public static int Main(
            string[] args)
        {
            if (args.Length < 2)
            {
                Console.WriteLine("DsaElGamalKeyRingGenerator [-a] identity passPhrase");
                return 0;
            }

			IAsymmetricCipherKeyPairGenerator dsaKpg = GeneratorUtilities.GetKeyPairGenerator("DSA");
            DsaParametersGenerator pGen = new DsaParametersGenerator();
            pGen.Init(1024, 80, new SecureRandom());
            DsaParameters dsaParams = pGen.GenerateParameters();
            DsaKeyGenerationParameters kgp = new DsaKeyGenerationParameters(new SecureRandom(), dsaParams);
            dsaKpg.Init(kgp);


			//
            // this takes a while as the key generator has to Generate some DSA parameters
            // before it Generates the key.
            //
            AsymmetricCipherKeyPair dsaKp = dsaKpg.GenerateKeyPair();


			IAsymmetricCipherKeyPairGenerator elgKpg = GeneratorUtilities.GetKeyPairGenerator("ELGAMAL");

			BigInteger g = new BigInteger("153d5d6172adb43045b68ae8e1de1070b6137005686d29d3d73a7749199681ee5b212c9b96bfdcfa5b20cd5e3fd2044895d609cf9b410b7a0f12ca1cb9a428cc", 16);
            BigInteger p = new BigInteger("9494fec095f3b85ee286542b3836fc81a5dd0a0349b4c239dd38744d488cf8e31db8bcb7d33b41abb9e5a33cca9144b1cef332c94bf0573bf047a3aca98cdf3b", 16);

			ElGamalParameters elParams = new ElGamalParameters(p, g);
            ElGamalKeyGenerationParameters elKgp = new ElGamalKeyGenerationParameters(new SecureRandom(), elParams);
            elgKpg.Init(elKgp);

			//
            // this is quicker because we are using preGenerated parameters.
            //
            AsymmetricCipherKeyPair elgKp = elgKpg.GenerateKeyPair();

			Stream out1, out2;
			if (args[0].Equals("-a"))
            {
                if (args.Length < 3)
                {
                    Console.WriteLine("DSAElGamalKeyRingGenerator [-a] identity passPhrase");
                    return 0;
                }

				out1 = File.Create("secret.asc");
                out2 = File.Create("pub.asc");

				ExportKeyPair(out1, out2, dsaKp, elgKp, args[1], args[2].ToCharArray(), true);
            }
            else
            {
                out1 = File.Create("secret.bpg");
                out2 = File.Create("pub.bpg");

				ExportKeyPair(out1, out2, dsaKp, elgKp, args[0], args[1].ToCharArray(), false);
            }
			out1.Close();
			out2.Close();
			return 0;
        }
Exemple #8
0
        private void GenerateDSA()
        {
            //DSA Key Parameter Generator
            DsaParametersGenerator paramgen = new DsaParametersGenerator();
            //Initialize Key Parameter Generator
            paramgen.Init(512, 100, new SecureRandom());

            //DSA KeyGeneration Parameters
            DsaKeyGenerationParameters param = new DsaKeyGenerationParameters(new SecureRandom(), paramgen.GenerateParameters());

            //DSA Key Pair Generator
            DsaKeyPairGenerator dsakpgen = new DsaKeyPairGenerator();
            //Initialize the Key Pair Generator
            dsakpgen.Init(param);

            //The DSA Keys!
            this.DSAKeys = dsakpgen.GenerateKeyPair();

            //Generate PEM format
            byte[] prvencoding = DSAHelper.EncodePrivateKey(this.DSAKeys.Private);
            this.PEMPrivateKey = Convert.ToBase64String(prvencoding);
            this.DERPrivateKey = new ArraySegment<byte>(prvencoding);

            byte[] pubencoding = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(this.DSAKeys.Public).GetDerEncoded();
            this.PEMPublicKey = Convert.ToBase64String(pubencoding);
            this.DERPublicKey = new ArraySegment<byte>(pubencoding);
        }
Exemple #9
0
        public void TestDsa2Parameters()
        {
            byte[] seed = Hex.Decode("4783081972865EA95D43318AB2EAF9C61A2FC7BBF1B772A09017BDF5A58F4FF0");

            //AlgorithmParameterGenerator a = AlgorithmParameterGenerator.getInstance("DSA", "BC");
            //a.init(2048, new DSATestSecureRandom(seed));
            DsaParametersGenerator a = new DsaParametersGenerator(new Sha256Digest());
            a.Init(new DsaParameterGenerationParameters(2048, 256, 80, new DsaTestSecureRandom(seed)));

            //AlgorithmParameters parameters = a.generateParameters();

            //DSAParameterSpec dsaP = (DSAParameterSpec)parameters.getParameterSpec(DSAParameterSpec.class);
            DsaParameters dsaP = a.GenerateParameters();

            if (!dsaP.Q.Equals(new BigInteger("C24ED361870B61E0D367F008F99F8A1F75525889C89DB1B673C45AF5867CB467", 16)))
            {
                Fail("Q incorrect");
            }

            if (!dsaP.P.Equals(new BigInteger(
                "F56C2A7D366E3EBDEAA1891FD2A0D099" +
                "436438A673FED4D75F594959CFFEBCA7BE0FC72E4FE67D91" +
                "D801CBA0693AC4ED9E411B41D19E2FD1699C4390AD27D94C" +
                "69C0B143F1DC88932CFE2310C886412047BD9B1C7A67F8A2" +
                "5909132627F51A0C866877E672E555342BDF9355347DBD43" +
                "B47156B2C20BAD9D2B071BC2FDCF9757F75C168C5D9FC431" +
                "31BE162A0756D1BDEC2CA0EB0E3B018A8B38D3EF2487782A" +
                "EB9FBF99D8B30499C55E4F61E5C7DCEE2A2BB55BD7F75FCD" +
                "F00E48F2E8356BDB59D86114028F67B8E07B127744778AFF" +
                "1CF1399A4D679D92FDE7D941C5C85C5D7BFF91BA69F9489D" +
                "531D1EBFA727CFDA651390F8021719FA9F7216CEB177BD75", 16)))
            {
                Fail("P incorrect");
            }

            if (!dsaP.G.Equals(new BigInteger(
                "8DC6CC814CAE4A1C05A3E186A6FE27EA" +
                "BA8CDB133FDCE14A963A92E809790CBA096EAA26140550C1" +
                "29FA2B98C16E84236AA33BF919CD6F587E048C52666576DB" +
                "6E925C6CBE9B9EC5C16020F9A44C9F1C8F7A8E611C1F6EC2" +
                "513EA6AA0B8D0F72FED73CA37DF240DB57BBB27431D61869" +
                "7B9E771B0B301D5DF05955425061A30DC6D33BB6D2A32BD0" +
                "A75A0A71D2184F506372ABF84A56AEEEA8EB693BF29A6403" +
                "45FA1298A16E85421B2208D00068A5A42915F82CF0B858C8" +
                "FA39D43D704B6927E0B2F916304E86FB6A1B487F07D8139E" +
                "428BB096C6D67A76EC0B8D4EF274B8A2CF556D279AD267CC" +
                "EF5AF477AFED029F485B5597739F5D0240F67C2D948A6279", 16)))
            {
                Fail("G incorrect");
            }

            //KeyPairGenerator    g = KeyPairGenerator.getInstance("DSA", "BC");
            IAsymmetricCipherKeyPairGenerator g = GeneratorUtilities.GetKeyPairGenerator("DSA");
            //g.initialize(dsaP, FixedSecureRandom.From(Hex.Decode("0CAF2EF547EC49C4F3A6FE6DF4223A174D01F2C115D49A6F73437C29A2A8458C")));
            g.Init(new DsaKeyGenerationParameters(FixedSecureRandom.From(Hex.Decode("0CAF2EF547EC49C4F3A6FE6DF4223A174D01F2C115D49A6F73437C29A2A8458C")), dsaP));
            //KeyPair p = g.generateKeyPair();
            AsymmetricCipherKeyPair p = g.GenerateKeyPair();

            //DSAPrivateKey  sKey = (DSAPrivateKey)p.getPrivate();
            //DSAPublicKey   vKey = (DSAPublicKey)p.getPublic();
            DsaPrivateKeyParameters sKey = (DsaPrivateKeyParameters)p.Private;
            DsaPublicKeyParameters vKey = (DsaPublicKeyParameters)p.Public;

            if (!vKey.Y.Equals(new BigInteger(
                "2828003D7C747199143C370FDD07A286" +
                "1524514ACC57F63F80C38C2087C6B795B62DE1C224BF8D1D" +
                "1424E60CE3F5AE3F76C754A2464AF292286D873A7A30B7EA" +
                "CBBC75AAFDE7191D9157598CDB0B60E0C5AA3F6EBE425500" +
                "C611957DBF5ED35490714A42811FDCDEB19AF2AB30BEADFF" +
                "2907931CEE7F3B55532CFFAEB371F84F01347630EB227A41" +
                "9B1F3F558BC8A509D64A765D8987D493B007C4412C297CAF" +
                "41566E26FAEE475137EC781A0DC088A26C8804A98C23140E" +
                "7C936281864B99571EE95C416AA38CEEBB41FDBFF1EB1D1D" +
                "C97B63CE1355257627C8B0FD840DDB20ED35BE92F08C49AE" +
                "A5613957D7E5C7A6D5A5834B4CB069E0831753ECF65BA02B", 16)))
            {
                Fail("Y value incorrect");
            }

            if (!sKey.X.Equals(
                new BigInteger("0CAF2EF547EC49C4F3A6FE6DF4223A174D01F2C115D49A6F73437C29A2A8458C", 16)))
            {
                Fail("X value incorrect");
            }

            //byte[] encodeParams = parameters.getEncoded();
            byte[] encodeParams = new DsaParameter(dsaP.P, dsaP.Q, dsaP.G).GetDerEncoded();

            //AlgorithmParameters a2 = AlgorithmParameters.getInstance("DSA", "BC");
            //a2.init(encodeParams);
            DsaParameter dsaP2 = DsaParameter.GetInstance(Asn1Object.FromByteArray(encodeParams));
            DsaParameters p2 = new DsaParameters(dsaP.P, dsaP.Q, dsaP.G);

            // a and a2 should be equivalent!
            //byte[] encodeParams_2 = a2.GetEncoded();
            byte[] encodeParams_2 = new DsaParameter(p2.P, p2.Q, p2.G).GetDerEncoded();

            if (!AreEqual(encodeParams, encodeParams_2))
            {
                Fail("encode/decode parameters failed");
            }

            ISigner s = SignerUtilities.GetSigner("DSA");
            byte[] data = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };

            s.Init(true, sKey);

            s.BlockUpdate(data, 0, data.Length);

            byte[] sigBytes = s.GenerateSignature();

            s = SignerUtilities.GetSigner("DSA");

            s.Init(false, vKey);

            s.BlockUpdate(data, 0, data.Length);

            if (!s.VerifySignature(sigBytes))
            {
                Fail("DSA verification failed");
            }
        }
        public void GenerateTest()
        {
            char[] passPhrase = "hello".ToCharArray();
            DsaParametersGenerator pGen = new DsaParametersGenerator();
            pGen.Init(512, 80, new SecureRandom());
            DsaParameters dsaParams = pGen.GenerateParameters();
            DsaKeyGenerationParameters dsaKgp = new DsaKeyGenerationParameters(new SecureRandom(), dsaParams);
            IAsymmetricCipherKeyPairGenerator dsaKpg = GeneratorUtilities.GetKeyPairGenerator("DSA");
            dsaKpg.Init(dsaKgp);

            //
            // this takes a while as the key generator has to Generate some DSA parameters
            // before it Generates the key.
            //
            AsymmetricCipherKeyPair dsaKp = dsaKpg.GenerateKeyPair();
            IAsymmetricCipherKeyPairGenerator elgKpg = GeneratorUtilities.GetKeyPairGenerator("ELGAMAL");

            BigInteger g = new BigInteger("153d5d6172adb43045b68ae8e1de1070b6137005686d29d3d73a7749199681ee5b212c9b96bfdcfa5b20cd5e3fd2044895d609cf9b410b7a0f12ca1cb9a428cc", 16);
            BigInteger p = new BigInteger("9494fec095f3b85ee286542b3836fc81a5dd0a0349b4c239dd38744d488cf8e31db8bcb7d33b41abb9e5a33cca9144b1cef332c94bf0573bf047a3aca98cdf3b", 16);

            ElGamalParameters elParams = new ElGamalParameters(p, g);
            ElGamalKeyGenerationParameters elKgp = new ElGamalKeyGenerationParameters(new SecureRandom(), elParams);
            elgKpg.Init(elKgp);

            //
            // this is quicker because we are using preGenerated parameters.
            //
            AsymmetricCipherKeyPair elgKp = elgKpg.GenerateKeyPair();
            PgpKeyPair dsaKeyPair = new PgpKeyPair(PublicKeyAlgorithmTag.Dsa, dsaKp, DateTime.UtcNow);
            PgpKeyPair elgKeyPair = new PgpKeyPair(PublicKeyAlgorithmTag.ElGamalEncrypt, elgKp, DateTime.UtcNow);

            PgpKeyRingGenerator keyRingGen = new PgpKeyRingGenerator(PgpSignature.PositiveCertification, dsaKeyPair,
                "test", SymmetricKeyAlgorithmTag.Aes256, passPhrase, null, null, new SecureRandom());

            keyRingGen.AddSubKey(elgKeyPair);

            PgpSecretKeyRing keyRing = keyRingGen.GenerateSecretKeyRing();

            keyRing.GetSecretKey().ExtractPrivateKey(passPhrase);

            PgpPublicKeyRing pubRing = keyRingGen.GeneratePublicKeyRing();

            PgpPublicKey vKey = null;
            PgpPublicKey sKey = null;

            foreach (PgpPublicKey pk in pubRing.GetPublicKeys())
            {
                if (pk.IsMasterKey)
                {
                    vKey = pk;
                }
                else
                {
                    sKey = pk;
                }
            }

            foreach (PgpSignature sig in sKey.GetSignatures())
            {
                if (sig.KeyId == vKey.KeyId
                    && sig.SignatureType == PgpSignature.SubkeyBinding)
                {
                    sig.InitVerify(vKey);

                    if (!sig.VerifyCertification(vKey, sKey))
                    {
                        Fail("failed to verify sub-key signature.");
                    }
                }
            }
        }
        public override void PerformTest()
        {
            //
            // Read the public key
            //
            PgpPublicKeyRing pgpPub = new PgpPublicKeyRing(testPubKey);

            var pubKey = pgpPub.GetPublicKey();

            //
            // Read the private key
            //
            PgpSecretKeyRing sKey = new PgpSecretKeyRing(testPrivKey);
            IPgpSecretKey secretKey = sKey.GetSecretKey();
            IPgpPrivateKey pgpPrivKey = secretKey.ExtractPrivateKey(pass);

            //
            // 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(pubKey);

            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");
            }

            //
            // signature generation
            //
            GenerateTest(sKey, pubKey, pgpPrivKey);

            //
            // signature generation - canonical text
            //
            const string data = "hello world!";
            byte[] dataBytes = Encoding.ASCII.GetBytes(data);
            MemoryStream bOut = new MemoryStream();
            MemoryStream testIn = new MemoryStream(dataBytes, false);
            PgpSignatureGenerator sGen = new PgpSignatureGenerator(
                PublicKeyAlgorithmTag.Dsa, HashAlgorithmTag.Sha1);

            sGen.InitSign(PgpSignature.CanonicalTextDocument, 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.Text,
                "_CONSOLE",
                dataBytes.Length,
                testDateTime);

            while ((ch = testIn.ReadByte()) >= 0)
            {
                lOut.WriteByte((byte) ch);
                sGen.Update((byte)ch);
            }

            lGen.Close();

            sGen.Generate().Encode(bcOut);

            cGen.Close();

            //
            // verify Generated signature - canconical text
            //
            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(pubKey);

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

            p3 = (PgpSignatureList) pgpFact.NextPgpObject();

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

            //
            // Read the public key with user attributes
            //
            pgpPub = new PgpPublicKeyRing(testPubWithUserAttr);

            pubKey = pgpPub.GetPublicKey();

            int count = 0;
            foreach (PgpUserAttributeSubpacketVector attributes in pubKey.GetUserAttributes())
            {
                int sigCount = 0;
                foreach (object sigs in pubKey.GetSignaturesForUserAttribute(attributes))
                {
                    if (sigs == null)
                        Fail("null signature found");

                    sigCount++;
                }

                if (sigCount != 1)
                {
                    Fail("Failed user attributes signature check");
                }

                count++;
            }

            if (count != 1)
            {
                Fail("Failed user attributes check");
            }

            byte[]  pgpPubBytes = pgpPub.GetEncoded();
            pgpPub = new PgpPublicKeyRing(pgpPubBytes);
            pubKey = pgpPub.GetPublicKey();
            count = 0;

            foreach (object ua in pubKey.GetUserAttributes())
            {
                if (ua == null)
                    Fail("null user attribute found");

                count++;
            }

            if (count != 1)
            {
                Fail("Failed user attributes reread");
            }

            //
            // reading test extra data - key with edge condition for DSA key password.
            //
            char[] passPhrase = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };

            sKey = new PgpSecretKeyRing(testPrivKey2);
            pgpPrivKey = sKey.GetSecretKey().ExtractPrivateKey(passPhrase);

            //
            // reading test - aes256 encrypted passphrase.
            //
            sKey = new PgpSecretKeyRing(aesSecretKey);
            pgpPrivKey = sKey.GetSecretKey().ExtractPrivateKey(pass);

            //
            // reading test - twofish encrypted passphrase.
            //
            sKey = new PgpSecretKeyRing(twofishSecretKey);
            pgpPrivKey = sKey.GetSecretKey().ExtractPrivateKey(pass);

            //
            // use of PgpKeyPair
            //
            DsaParametersGenerator pGen = new DsaParametersGenerator();
            pGen.Init(512, 80, new SecureRandom()); // TODO Is the certainty okay?
            DsaParameters dsaParams = pGen.GenerateParameters();
            DsaKeyGenerationParameters kgp = new DsaKeyGenerationParameters(new SecureRandom(), dsaParams);
            IAsymmetricCipherKeyPairGenerator kpg = GeneratorUtilities.GetKeyPairGenerator("DSA");
            kpg.Init(kgp);

            IAsymmetricCipherKeyPair kp = kpg.GenerateKeyPair();

            PgpKeyPair pgpKp = new PgpKeyPair(PublicKeyAlgorithmTag.Dsa,
                kp.Public, kp.Private, DateTime.UtcNow);

            PgpPublicKey k1 = pgpKp.PublicKey;
            PgpPrivateKey k2 = pgpKp.PrivateKey;
        }
Exemple #12
0
        private void Dsa2Test4()
        {
            byte[] seed = Hex.Decode("193AFCA7C1E77B3C1ECC618C81322E47B8B8B997C9C83515C59CC446C2D9BD47");

            DsaParametersGenerator pGen = new DsaParametersGenerator(new Sha256Digest());

            pGen.Init(new DsaParameterGenerationParameters(3072, 256, 80, new DsaTestSecureRandom(seed)));

            DsaParameters parameters = pGen.GenerateParameters();

            DsaValidationParameters pv = parameters.ValidationParameters;

            if (pv.Counter != 20)
            {
                Fail("counter incorrect");
            }

            if (!AreEqual(seed, pv.GetSeed()))
            {
                Fail("seed incorrect");
            }

            if (!parameters.Q.Equals(new BigInteger("CFA0478A54717B08CE64805B76E5B14249A77A4838469DF7F7DC987EFCCFB11D", 16)))
            {
                Fail("Q incorrect");
            }

            if (!parameters.P.Equals(new BigInteger(
                "90066455B5CFC38F9CAA4A48B4281F292C260FEEF01FD610" +
                "37E56258A7795A1C7AD46076982CE6BB956936C6AB4DCFE0" +
                "5E6784586940CA544B9B2140E1EB523F009D20A7E7880E4E" +
                "5BFA690F1B9004A27811CD9904AF70420EEFD6EA11EF7DA1" +
                "29F58835FF56B89FAA637BC9AC2EFAAB903402229F491D8D" +
                "3485261CD068699B6BA58A1DDBBEF6DB51E8FE34E8A78E54" +
                "2D7BA351C21EA8D8F1D29F5D5D15939487E27F4416B0CA63" +
                "2C59EFD1B1EB66511A5A0FBF615B766C5862D0BD8A3FE7A0" +
                "E0DA0FB2FE1FCB19E8F9996A8EA0FCCDE538175238FC8B0E" +
                "E6F29AF7F642773EBE8CD5402415A01451A840476B2FCEB0" +
                "E388D30D4B376C37FE401C2A2C2F941DAD179C540C1C8CE0" +
                "30D460C4D983BE9AB0B20F69144C1AE13F9383EA1C08504F" +
                "B0BF321503EFE43488310DD8DC77EC5B8349B8BFE97C2C56" +
                "0EA878DE87C11E3D597F1FEA742D73EEC7F37BE43949EF1A" +
                "0D15C3F3E3FC0A8335617055AC91328EC22B50FC15B941D3" +
                "D1624CD88BC25F3E941FDDC6200689581BFEC416B4B2CB73", 16)))
            {
                Fail("P incorrect");
            }

            if (!parameters.G.Equals(new BigInteger(
                "5E5CBA992E0A680D885EB903AEA78E4A45A469103D448EDE" +
                "3B7ACCC54D521E37F84A4BDD5B06B0970CC2D2BBB715F7B8" +
                "2846F9A0C393914C792E6A923E2117AB805276A975AADB52" +
                "61D91673EA9AAFFEECBFA6183DFCB5D3B7332AA19275AFA1" +
                "F8EC0B60FB6F66CC23AE4870791D5982AAD1AA9485FD8F4A" +
                "60126FEB2CF05DB8A7F0F09B3397F3937F2E90B9E5B9C9B6" +
                "EFEF642BC48351C46FB171B9BFA9EF17A961CE96C7E7A7CC" +
                "3D3D03DFAD1078BA21DA425198F07D2481622BCE45969D9C" +
                "4D6063D72AB7A0F08B2F49A7CC6AF335E08C4720E31476B6" +
                "7299E231F8BD90B39AC3AE3BE0C6B6CACEF8289A2E2873D5" +
                "8E51E029CAFBD55E6841489AB66B5B4B9BA6E2F784660896" +
                "AFF387D92844CCB8B69475496DE19DA2E58259B090489AC8" +
                "E62363CDF82CFD8EF2A427ABCD65750B506F56DDE3B98856" +
                "7A88126B914D7828E2B63A6D7ED0747EC59E0E0A23CE7D8A" +
                "74C1D2C2A7AFB6A29799620F00E11C33787F7DED3B30E1A2" +
                "2D09F1FBDA1ABBBFBF25CAE05A13F812E34563F99410E73B", 16)))
            {
                Fail("G incorrect");
            }

            DsaKeyPairGenerator kpGen = new DsaKeyPairGenerator();

            kpGen.Init(new DsaKeyGenerationParameters(
                FixedSecureRandom.From(Hex.Decode("3ABC1587297CE7B9EA1AD6651CF2BC4D7F92ED25CABC8553F567D1B40EBB8764")), parameters));

            AsymmetricCipherKeyPair kp = kpGen.GenerateKeyPair();

            DsaPublicKeyParameters pub = (DsaPublicKeyParameters)kp.Public;
            DsaPrivateKeyParameters priv = (DsaPrivateKeyParameters)kp.Private;

            if (!pub.Y.Equals(new BigInteger(
                "8B891C8692D3DE875879390F2698B26FBECCA6B075535DCE" +
                "6B0C862577F9FA0DEF6074E7A7624121224A595896ABD4CD" +
                "A56B2CEFB942E025D2A4282FFAA98A48CDB47E1A6FCB5CFB" +
                "393EF35AF9DF913102BB303C2B5C36C3F8FC04ED7B8B69FE" +
                "FE0CF3E1FC05CFA713B3435B2656E913BA8874AEA9F93600" +
                "6AEB448BCD005D18EC3562A33D04CF25C8D3D69844343442" +
                "FA3DB7DE618C5E2DA064573E61E6D5581BFB694A23AC87FD" +
                "5B52D62E954E1376DB8DDB524FFC0D469DF978792EE44173" +
                "8E5DB05A7DC43E94C11A2E7A4FBE383071FA36D2A7EC8A93" +
                "88FE1C4F79888A99D3B6105697C2556B79BB4D7E781CEBB3" +
                "D4866AD825A5E830846072289FDBC941FA679CA82F5F78B7" +
                "461B2404DB883D215F4E0676CF5493950AC5591697BFEA8D" +
                "1EE6EC016B89BA51CAFB5F9C84C989FA117375E94578F28B" +
                "E0B34CE0545DA46266FD77F62D8F2CEE92AB77012AFEBC11" +
                "008985A821CD2D978C7E6FE7499D1AAF8DE632C21BB48CA5" +
                "CBF9F31098FD3FD3854C49A65D9201744AACE540354974F9", 16)))
            {
                Fail("Y value incorrect");
            }

            if (!priv.X.Equals(
                new BigInteger("3ABC1587297CE7B9EA1AD6651CF2BC4D7F92ED25CABC8553F567D1B40EBB8764", 16)))
            {
                Fail("X value incorrect");
            }

            DsaSigner signer = new DsaSigner();

            signer.Init(true, new ParametersWithRandom(kp.Private,
                FixedSecureRandom.From(Hex.Decode("A6902C1E6E3943C5628061588A8B007BCCEA91DBF12915483F04B24AB0678BEE"))));

            byte[] msg = Hex.Decode("BA7816BF8F01CFEA414140DE5DAE2223B00361A396177A9CB410FF61F20015AD");

            BigInteger[] sig = signer.GenerateSignature(msg);

            if (!sig[0].Equals(new BigInteger("5F184E645A38BE8FB4A6871B6503A9D12924C7ABE04B71410066C2ECA6E3BE3E", 16)))
            {
                Fail("R value incorrect");
            }

            if (!sig[1].Equals(new BigInteger("91EB0C7BA3D4B9B60B825C3D9F2CADA8A2C9D7723267B033CBCDCF8803DB9C18", 16)))
            {
                Fail("S value incorrect");
            }

            signer.Init(false, kp.Public);

            if (!signer.VerifySignature(msg, sig[0], sig[1]))
            {
                Fail("signature not verified");
            }
        }
		protected virtual DsaParameters GenerateParameters_FIPS186_3()
		{
			IDigest digest = this.digest;
			int num = digest.GetDigestSize() * 8;
			int n = this.N;
			byte[] array = new byte[n / 8];
			int num2 = (this.L - 1) / num;
			int n2 = (this.L - 1) % num;
			byte[] array2 = new byte[digest.GetDigestSize()];
			BigInteger bigInteger2;
			int i;
			BigInteger bigInteger7;
			while (true)
			{
				this.random.NextBytes(array);
				DsaParametersGenerator.Hash(digest, array, array2);
				BigInteger bigInteger = new BigInteger(1, array2).Mod(BigInteger.One.ShiftLeft(this.N - 1));
				bigInteger2 = BigInteger.One.ShiftLeft(this.N - 1).Add(bigInteger).Add(BigInteger.One).Subtract(bigInteger.Mod(BigInteger.Two));
				if (bigInteger2.IsProbablePrime(this.certainty))
				{
					byte[] array3 = Arrays.Clone(array);
					int num3 = 4 * this.L;
					for (i = 0; i < num3; i++)
					{
						BigInteger bigInteger3 = BigInteger.Zero;
						int j = 0;
						int num4 = 0;
						while (j <= num2)
						{
							DsaParametersGenerator.Inc(array3);
							DsaParametersGenerator.Hash(digest, array3, array2);
							BigInteger bigInteger4 = new BigInteger(1, array2);
							if (j == num2)
							{
								bigInteger4 = bigInteger4.Mod(BigInteger.One.ShiftLeft(n2));
							}
							bigInteger3 = bigInteger3.Add(bigInteger4.ShiftLeft(num4));
							j++;
							num4 += num;
						}
						BigInteger bigInteger5 = bigInteger3.Add(BigInteger.One.ShiftLeft(this.L - 1));
						BigInteger bigInteger6 = bigInteger5.Mod(bigInteger2.ShiftLeft(1));
						bigInteger7 = bigInteger5.Subtract(bigInteger6.Subtract(BigInteger.One));
						if (bigInteger7.BitLength == this.L && bigInteger7.IsProbablePrime(this.certainty))
						{
							goto Block_5;
						}
					}
				}
			}
			Block_5:
			if (this.usageIndex >= 0)
			{
				BigInteger bigInteger8 = this.CalculateGenerator_FIPS186_3_Verifiable(digest, bigInteger7, bigInteger2, array, this.usageIndex);
				if (bigInteger8 != null)
				{
					return new DsaParameters(bigInteger7, bigInteger2, bigInteger8, new DsaValidationParameters(array, i, this.usageIndex));
				}
			}
			BigInteger g = this.CalculateGenerator_FIPS186_3_Unverifiable(bigInteger7, bigInteger2, this.random);
			return new DsaParameters(bigInteger7, bigInteger2, g, new DsaValidationParameters(array, i));
		}
Exemple #14
0
        private void Dsa2Test3()
        {
            byte[] seed = Hex.Decode("4783081972865EA95D43318AB2EAF9C61A2FC7BBF1B772A09017BDF5A58F4FF0");

            DsaParametersGenerator pGen = new DsaParametersGenerator(new Sha256Digest());

            pGen.Init(new DsaParameterGenerationParameters(2048, 256, 80, new DsaTestSecureRandom(seed)));

            DsaParameters parameters = pGen.GenerateParameters();

            DsaValidationParameters pv = parameters.ValidationParameters;

            if (pv.Counter != 12)
            {
                Fail("counter incorrect");
            }

            if (!AreEqual(seed, pv.GetSeed()))
            {
                Fail("seed incorrect");
            }

            if (!parameters.Q.Equals(new BigInteger("C24ED361870B61E0D367F008F99F8A1F75525889C89DB1B673C45AF5867CB467", 16)))
            {
                Fail("Q incorrect");
            }

            if (!parameters.P.Equals(new BigInteger(
                "F56C2A7D366E3EBDEAA1891FD2A0D099" +
                "436438A673FED4D75F594959CFFEBCA7BE0FC72E4FE67D91" +
                "D801CBA0693AC4ED9E411B41D19E2FD1699C4390AD27D94C" +
                "69C0B143F1DC88932CFE2310C886412047BD9B1C7A67F8A2" +
                "5909132627F51A0C866877E672E555342BDF9355347DBD43" +
                "B47156B2C20BAD9D2B071BC2FDCF9757F75C168C5D9FC431" +
                "31BE162A0756D1BDEC2CA0EB0E3B018A8B38D3EF2487782A" +
                "EB9FBF99D8B30499C55E4F61E5C7DCEE2A2BB55BD7F75FCD" +
                "F00E48F2E8356BDB59D86114028F67B8E07B127744778AFF" +
                "1CF1399A4D679D92FDE7D941C5C85C5D7BFF91BA69F9489D" +
                "531D1EBFA727CFDA651390F8021719FA9F7216CEB177BD75", 16)))
            {
                Fail("P incorrect");
            }

            if (!parameters.G.Equals(new BigInteger(
                "8DC6CC814CAE4A1C05A3E186A6FE27EA" +
                "BA8CDB133FDCE14A963A92E809790CBA096EAA26140550C1" +
                "29FA2B98C16E84236AA33BF919CD6F587E048C52666576DB" +
                "6E925C6CBE9B9EC5C16020F9A44C9F1C8F7A8E611C1F6EC2" +
                "513EA6AA0B8D0F72FED73CA37DF240DB57BBB27431D61869" +
                "7B9E771B0B301D5DF05955425061A30DC6D33BB6D2A32BD0" +
                "A75A0A71D2184F506372ABF84A56AEEEA8EB693BF29A6403" +
                "45FA1298A16E85421B2208D00068A5A42915F82CF0B858C8" +
                "FA39D43D704B6927E0B2F916304E86FB6A1B487F07D8139E" +
                "428BB096C6D67A76EC0B8D4EF274B8A2CF556D279AD267CC" +
                "EF5AF477AFED029F485B5597739F5D0240F67C2D948A6279", 16)))
            {
                Fail("G incorrect");
            }

            DsaKeyPairGenerator kpGen = new DsaKeyPairGenerator();

            kpGen.Init(new DsaKeyGenerationParameters(
                FixedSecureRandom.From(Hex.Decode("0CAF2EF547EC49C4F3A6FE6DF4223A174D01F2C115D49A6F73437C29A2A8458C")), parameters));

            AsymmetricCipherKeyPair kp = kpGen.GenerateKeyPair();

            DsaPublicKeyParameters pub = (DsaPublicKeyParameters)kp.Public;
            DsaPrivateKeyParameters priv = (DsaPrivateKeyParameters)kp.Private;

            if (!pub.Y.Equals(new BigInteger(
                "2828003D7C747199143C370FDD07A286" +
                "1524514ACC57F63F80C38C2087C6B795B62DE1C224BF8D1D" +
                "1424E60CE3F5AE3F76C754A2464AF292286D873A7A30B7EA" +
                "CBBC75AAFDE7191D9157598CDB0B60E0C5AA3F6EBE425500" +
                "C611957DBF5ED35490714A42811FDCDEB19AF2AB30BEADFF" +
                "2907931CEE7F3B55532CFFAEB371F84F01347630EB227A41" +
                "9B1F3F558BC8A509D64A765D8987D493B007C4412C297CAF" +
                "41566E26FAEE475137EC781A0DC088A26C8804A98C23140E" +
                "7C936281864B99571EE95C416AA38CEEBB41FDBFF1EB1D1D" +
                "C97B63CE1355257627C8B0FD840DDB20ED35BE92F08C49AE" +
                "A5613957D7E5C7A6D5A5834B4CB069E0831753ECF65BA02B", 16)))
            {
                Fail("Y value incorrect");
            }

            if (!priv.X.Equals(
                new BigInteger("0CAF2EF547EC49C4F3A6FE6DF4223A174D01F2C115D49A6F73437C29A2A8458C", 16)))
            {
                Fail("X value incorrect");
            }

            DsaSigner signer = new DsaSigner();

            signer.Init(true, new ParametersWithRandom(kp.Private,
                FixedSecureRandom.From(Hex.Decode("0CAF2EF547EC49C4F3A6FE6DF4223A174D01F2C115D49A6F73437C29A2A8458C"))));

            byte[] msg = Hex.Decode("BA7816BF8F01CFEA414140DE5DAE2223B00361A396177A9CB410FF61F20015AD");

            BigInteger[] sig = signer.GenerateSignature(msg);

            if (!sig[0].Equals(new BigInteger("315C875DCD4850E948B8AC42824E9483A32D5BA5ABE0681B9B9448D444F2BE3C", 16)))
            {
                Fail("R value incorrect");
            }

            if (!sig[1].Equals(new BigInteger("89718D12E54A8D9ED066E4A55F7ED5A2229CD23B9A3CEE78F83ED6AA61F6BCB9", 16)))
            {
                Fail("S value incorrect");
            }

            signer.Init(false, kp.Public);

            if (!signer.VerifySignature(msg, sig[0], sig[1]))
            {
                Fail("signature not verified");
            }
        }
Exemple #15
0
        private void Dsa2Test2()
        {
            byte[] seed = Hex.Decode("5AFCC1EFFC079A9CCA6ECA86D6E3CC3B18642D9BE1CC6207C84002A9");

            DsaParametersGenerator pGen = new DsaParametersGenerator(new Sha224Digest());

            pGen.Init(new DsaParameterGenerationParameters(2048, 224, 80, new DsaTestSecureRandom(seed)));

            DsaParameters parameters = pGen.GenerateParameters();

            DsaValidationParameters pv = parameters.ValidationParameters;

            if (pv.Counter != 21)
            {
                Fail("counter incorrect");
            }

            if (!AreEqual(seed, pv.GetSeed()))
            {
                Fail("seed incorrect");
            }

            if (!parameters.Q.Equals(new BigInteger("90EAF4D1AF0708B1B612FF35E0A2997EB9E9D263C9CE659528945C0D", 16)))
            {
                Fail("Q incorrect");
            }

            if (!parameters.P.Equals(new BigInteger(
                "C196BA05AC29E1F9C3C72D56DFFC6154" +
                "A033F1477AC88EC37F09BE6C5BB95F51C296DD20D1A28A06" +
                "7CCC4D4316A4BD1DCA55ED1066D438C35AEBAABF57E7DAE4" +
                "28782A95ECA1C143DB701FD48533A3C18F0FE23557EA7AE6" +
                "19ECACC7E0B51652A8776D02A425567DED36EABD90CA33A1" +
                "E8D988F0BBB92D02D1D20290113BB562CE1FC856EEB7CDD9" +
                "2D33EEA6F410859B179E7E789A8F75F645FAE2E136D252BF" +
                "FAFF89528945C1ABE705A38DBC2D364AADE99BE0D0AAD82E" +
                "5320121496DC65B3930E38047294FF877831A16D5228418D" +
                "E8AB275D7D75651CEFED65F78AFC3EA7FE4D79B35F62A040" +
                "2A1117599ADAC7B269A59F353CF450E6982D3B1702D9CA83", 16)))
            {
                Fail("P incorrect");
            }

            if (!parameters.G.Equals(new BigInteger(
                "A59A749A11242C58C894E9E5A91804E8"+
                "FA0AC64B56288F8D47D51B1EDC4D65444FECA0111D78F35F"+
                "C9FDD4CB1F1B79A3BA9CBEE83A3F811012503C8117F98E50"+
                "48B089E387AF6949BF8784EBD9EF45876F2E6A5A495BE64B"+
                "6E770409494B7FEE1DBB1E4B2BC2A53D4F893D418B715959"+
                "2E4FFFDF6969E91D770DAEBD0B5CB14C00AD68EC7DC1E574"+
                "5EA55C706C4A1C5C88964E34D09DEB753AD418C1AD0F4FDF"+
                "D049A955E5D78491C0B7A2F1575A008CCD727AB376DB6E69"+
                "5515B05BD412F5B8C2F4C77EE10DA48ABD53F5DD498927EE"+
                "7B692BBBCDA2FB23A516C5B4533D73980B2A3B60E384ED20"+
                "0AE21B40D273651AD6060C13D97FD69AA13C5611A51B9085", 16)))
            {
                Fail("G incorrect");
            }

            DsaKeyPairGenerator kpGen = new DsaKeyPairGenerator();

            kpGen.Init(new DsaKeyGenerationParameters(
                FixedSecureRandom.From(Hex.Decode("00D0F09ED3E2568F6CADF9224117DA2AEC5A4300E009DE1366023E17")), parameters));

            AsymmetricCipherKeyPair kp = kpGen.GenerateKeyPair();

            DsaPublicKeyParameters pub = (DsaPublicKeyParameters)kp.Public;
            DsaPrivateKeyParameters priv = (DsaPrivateKeyParameters)kp.Private;

            if (!pub.Y.Equals(new BigInteger(
                "70035C9A3B225B258F16741F3941FBF0" +
                "6F3D056CD7BD864604CBB5EE9DD85304EE8E8E4ABD5E9032" +
                "11DDF25CE149075510ACE166970AFDC7DF552B7244F342FA" +
                "02F7A621405B754909D757F97290E1FE5036E904CF593446" +
                "0C046D95659821E1597ED9F2B1F0E20863A6BBD0CE74DACB" +
                "A5D8C68A90B29C2157CDEDB82EC12B81EE3068F9BF5F7F34" +
                "6ECA41ED174CCCD7D154FA4F42F80FFE1BF46AE9D8125DEB" +
                "5B4BA08A72BDD86596DBEDDC9550FDD650C58F5AE5133509" +
                "A702F79A31ECB490F7A3C5581631F7C5BE4FF7F9E9F27FA3" +
                "90E47347AD1183509FED6FCF198BA9A71AB3335B4F38BE8D" +
                "15496A00B6DC2263E20A5F6B662320A3A1EC033AA61E3B68", 16)))
            {
                Fail("Y value incorrect");
            }

            if (!priv.X.Equals(
                new BigInteger("00D0F09ED3E2568F6CADF9224117DA2AEC5A4300E009DE1366023E17", 16)))
            {
                Fail("X value incorrect");
            }

            DsaSigner signer = new DsaSigner();

            signer.Init(true, new ParametersWithRandom(kp.Private,
                FixedSecureRandom.From(Hex.Decode("735959CC4463B8B440E407EECA8A473BF6A6D1FE657546F67D401F05"))));

            byte[] msg = Hex.Decode("23097D223405D8228642A477BDA255B32AADBCE4BDA0B3F7E36C9DA7");

            BigInteger[] sig = signer.GenerateSignature(msg);

            if (!sig[0].Equals(new BigInteger("4400138D05F9639CAF54A583CAAF25D2B76D0C3EAD752CE17DBC85FE", 16)))
            {
                Fail("R value incorrect");
            }

            if (!sig[1].Equals(new BigInteger("874D4F12CB13B61732D398445698CFA9D92381D938AA57EE2C9327B3", 16)))
            {
                Fail("S value incorrect");
            }

            signer.Init(false, kp.Public);

            if (!signer.VerifySignature(msg, sig[0], sig[1]))
            {
                Fail("signature not verified");
            }
        }
Exemple #16
0
        private void Dsa2Test1()
        {
            byte[] seed = Hex.Decode("ED8BEE8D1CB89229D2903CBF0E51EE7377F48698");

            DsaParametersGenerator pGen = new DsaParametersGenerator();

            pGen.Init(new DsaParameterGenerationParameters(1024, 160, 80, new DsaTestSecureRandom(seed)));

            DsaParameters parameters = pGen.GenerateParameters();

            DsaValidationParameters pv = parameters.ValidationParameters;

            if (pv.Counter != 5)
            {
                Fail("counter incorrect");
            }

            if (!AreEqual(seed, pv.GetSeed()))
            {
                Fail("seed incorrect");
            }

            if (!parameters.Q.Equals(new BigInteger("E950511EAB424B9A19A2AEB4E159B7844C589C4F", 16)))
            {
                Fail("Q incorrect");
            }

            if (!parameters.P.Equals(new BigInteger(
                "E0A67598CD1B763B" +
                "C98C8ABB333E5DDA0CD3AA0E5E1FB5BA8A7B4EABC10BA338" +
                "FAE06DD4B90FDA70D7CF0CB0C638BE3341BEC0AF8A7330A3" +
                "307DED2299A0EE606DF035177A239C34A912C202AA5F83B9" +
                "C4A7CF0235B5316BFC6EFB9A248411258B30B839AF172440" +
                "F32563056CB67A861158DDD90E6A894C72A5BBEF9E286C6B", 16)))
            {
                Fail("P incorrect");
            }

            if (!parameters.G.Equals(new BigInteger(
                "D29D5121B0423C27" +
                "69AB21843E5A3240FF19CACC792264E3BB6BE4F78EDD1B15" +
                "C4DFF7F1D905431F0AB16790E1F773B5CE01C804E509066A" +
                "9919F5195F4ABC58189FD9FF987389CB5BEDF21B4DAB4F8B" +
                "76A055FFE2770988FE2EC2DE11AD92219F0B351869AC24DA" +
                "3D7BA87011A701CE8EE7BFE49486ED4527B7186CA4610A75", 16)))
            {
                Fail("G incorrect");
            }

            DsaKeyPairGenerator kpGen = new DsaKeyPairGenerator();

            kpGen.Init(new DsaKeyGenerationParameters(FixedSecureRandom.From(Hex.Decode("D0EC4E50BB290A42E9E355C73D8809345DE2E139")), parameters));

            AsymmetricCipherKeyPair kp = kpGen.GenerateKeyPair();

            DsaPublicKeyParameters pub = (DsaPublicKeyParameters)kp.Public;
            DsaPrivateKeyParameters priv = (DsaPrivateKeyParameters)kp.Private;

            if (!pub.Y.Equals(new BigInteger(
                "25282217F5730501" +
                "DD8DBA3EDFCF349AAFFEC20921128D70FAC44110332201BB" +
                "A3F10986140CBB97C726938060473C8EC97B4731DB004293" +
                "B5E730363609DF9780F8D883D8C4D41DED6A2F1E1BBBDC97" +
                "9E1B9D6D3C940301F4E978D65B19041FCF1E8B518F5C0576" +
                "C770FE5A7A485D8329EE2914A2DE1B5DA4A6128CEAB70F79", 16)))
            {
                Fail("Y value incorrect");
            }

            if (!priv.X.Equals(
                new BigInteger("D0EC4E50BB290A42E9E355C73D8809345DE2E139", 16)))
            {
                Fail("X value incorrect");
            }

            DsaSigner signer = new DsaSigner();

            signer.Init(true, new ParametersWithRandom(kp.Private, FixedSecureRandom.From(Hex.Decode("349C55648DCF992F3F33E8026CFAC87C1D2BA075"))));

            byte[] msg = Hex.Decode("A9993E364706816ABA3E25717850C26C9CD0D89D");

            BigInteger[] sig = signer.GenerateSignature(msg);

            if (!sig[0].Equals(new BigInteger("636155AC9A4633B4665D179F9E4117DF68601F34", 16)))
            {
                Fail("R value incorrect");
            }

            if (!sig[1].Equals(new BigInteger("6C540B02D9D4852F89DF8CFC99963204F4347704", 16)))
            {
                Fail("S value incorrect");
            }

            signer.Init(false, kp.Public);

            if (!signer.VerifySignature(msg, sig[0], sig[1]))
            {
                Fail("signature not verified");
            }

        }
        public void TestParameters()
        {
            //			AlgorithmParameterGenerator a = AlgorithmParameterGenerator.GetInstance("DSA");
            //			a.init(512, random);
            DsaParametersGenerator a = new DsaParametersGenerator();
            a.Init(512, 20, random);

            //			AlgorithmParameters parameters = a.generateParameters();
            DsaParameters p = a.GenerateParameters();

            //			byte[] encodeParams = parameters.GetEncoded();
            byte[] encodeParams = new DsaParameter(p.P, p.Q, p.G).GetDerEncoded();

            //			AlgorithmParameters a2 = AlgorithmParameters.GetInstance("DSA");
            //			a2.init(encodeParams);
            DsaParameter dsaP = DsaParameter.GetInstance(Asn1Object.FromByteArray(encodeParams));
            DsaParameters p2 = new DsaParameters(dsaP.P, dsaP.Q, dsaP.G);

            // a and a2 should be equivalent!
            //			byte[] encodeParams_2 = a2.GetEncoded();
            byte[] encodeParams_2 = new DsaParameter(p2.P, p2.Q, p2.G).GetDerEncoded();

            if (!AreEqual(encodeParams, encodeParams_2))
            {
                Fail("encode/Decode parameters failed");
            }

            //			DSAParameterSpec dsaP = (DSAParameterSpec)parameters.getParameterSpec(typeof(DSAParameterSpec));

            //			KeyPairGenerator g = KeyPairGenerator.GetInstance("DSA");
            IAsymmetricCipherKeyPairGenerator g = GeneratorUtilities.GetKeyPairGenerator("DSA");
            //			g.initialize(dsaP, new SecureRandom());
            g.Init(new DsaKeyGenerationParameters(new SecureRandom(), p));
            //			KeyPair p = g.generateKeyPair();
            IAsymmetricCipherKeyPair pair = g.GenerateKeyPair();

            //			PrivateKey sKey = p.Private;
            //			PublicKey vKey = p.Public;
            IAsymmetricKeyParameter sKey = pair.Private;
            IAsymmetricKeyParameter vKey = pair.Public;

            ISigner s = SignerUtilities.GetSigner("DSA");
            byte[] data = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };

            s.Init(true, sKey);

            s.BlockUpdate(data, 0, data.Length);

            byte[] sigBytes = s.GenerateSignature();

            s = SignerUtilities.GetSigner("DSA");

            s.Init(false, vKey);

            s.BlockUpdate(data, 0, data.Length);

            if (!s.VerifySignature(sigBytes))
            {
                Fail("DSA verification failed");
            }
        }
Exemple #18
0
        /**
         * we Generate a self signed certificate for the sake of testing - DSA
         */
        internal void checkCreation2()
        {
            //
            // set up the keys
            //
            AsymmetricKeyParameter privKey;
            AsymmetricKeyParameter pubKey;

            try
            {
//				KeyPairGenerator g = KeyPairGenerator.GetInstance("DSA", "SUN");
//				g.initialize(512, new SecureRandom());
//				KeyPair p = g.generateKeyPair();
                IAsymmetricCipherKeyPairGenerator g = GeneratorUtilities.GetKeyPairGenerator("DSA");
                DsaParametersGenerator dpg = new DsaParametersGenerator();
                dpg.Init(512, 25, new SecureRandom());
                g.Init(new DsaKeyGenerationParameters(new SecureRandom(), dpg.GenerateParameters()));
                AsymmetricCipherKeyPair p = g.GenerateKeyPair();

                privKey = p.Private;
                pubKey = p.Public;
            }
            catch (Exception e)
            {
                Fail("error setting up keys - " + e.ToString());
                return;
            }

            //
            // distinguished name table.
            //
            IList ord = new ArrayList();
            ord.Add(X509Name.C);
            ord.Add(X509Name.O);
            ord.Add(X509Name.L);
            ord.Add(X509Name.ST);
            ord.Add(X509Name.E);

            IList values = new ArrayList();
            values.Add("AU");
            values.Add("The Legion of the Bouncy Castle");
            values.Add("Melbourne");
            values.Add("Victoria");
            values.Add("*****@*****.**");

            //
            // extensions
            //

            //
            // create the certificate - version 3
            //
            X509V3CertificateGenerator  certGen = new X509V3CertificateGenerator();

            certGen.SetSerialNumber(BigInteger.One);
            certGen.SetIssuerDN(new X509Name(ord, values));
            certGen.SetNotBefore(DateTime.UtcNow.AddSeconds(-50));
            certGen.SetNotAfter(DateTime.UtcNow.AddSeconds(50));
            certGen.SetSubjectDN(new X509Name(ord, values));
            certGen.SetPublicKey(pubKey);
            certGen.SetSignatureAlgorithm("SHA1withDSA");

            try
            {
                X509Certificate cert = certGen.Generate(privKey);

                cert.CheckValidity(DateTime.UtcNow);

                cert.Verify(pubKey);

                cert = new X509CertificateParser().ReadCertificate(cert.GetEncoded());

                // Console.WriteLine(cert);
            }
            catch (Exception e)
            {
                Fail("error setting generating cert - " + e.ToString());
            }

            //
            // create the certificate - version 1
            //
            X509V1CertificateGenerator certGen1 = new X509V1CertificateGenerator();

            certGen1.SetSerialNumber(BigInteger.One);
            certGen1.SetIssuerDN(new X509Name(ord, values));
            certGen1.SetNotBefore(DateTime.UtcNow.AddSeconds(-50));
            certGen1.SetNotAfter(DateTime.UtcNow.AddSeconds(50));
            certGen1.SetSubjectDN(new X509Name(ord, values));
            certGen1.SetPublicKey(pubKey);
            certGen1.SetSignatureAlgorithm("SHA1withDSA");

            try
            {
                X509Certificate cert = certGen1.Generate(privKey);

                cert.CheckValidity(DateTime.UtcNow);

                cert.Verify(pubKey);

                cert = new X509CertificateParser().ReadCertificate(cert.GetEncoded());

                //Console.WriteLine(cert);
            }
            catch (Exception e)
            {
                Fail("error setting generating cert - " + e.ToString());
            }

            //
            // exception test
            //
            try
            {
                certGen.SetPublicKey(dudPublicKey);

                Fail("key without encoding not detected in v1");
            }
            catch (ArgumentException)
            {
                // expected
            }
        }
        private void doTestBadStrength(
			int strength)
        {
            //			IAsymmetricCipherKeyPairGenerator g = GeneratorUtilities.GetKeyPairGenerator("DSA");

            // test exception
            //
            try
            {
                SecureRandom rand = new SecureRandom();

                DsaParametersGenerator pGen = new DsaParametersGenerator();
                pGen.Init(strength, 80, rand);

            //				g.Init(new DsaKeyGenerationParameters(rand, pGen.GenerateParameters()));

                Fail("illegal parameter " + strength + " check failed.");
            }
            catch (ArgumentException)
            {
                // expected
            }
        }
Exemple #20
0
        private void InitKey()
        {
            _secure_random = new SecureRandom();
            DsaParametersGenerator _dsa_param_gen = new DsaParametersGenerator();
            DsaKeyPairGenerator _dsa_key_pair_gen = new DsaKeyPairGenerator();
            _dsa_param_gen.Init(1024, 80, _secure_random);

            DsaKeyGenerationParameters _dsa_key_gen_params = new DsaKeyGenerationParameters(_secure_random, _dsa_param_gen.GenerateParameters());

            _dsa_key_pair_gen.Init(_dsa_key_gen_params);
            _key_pair = _dsa_key_pair_gen.GenerateKeyPair();

            _private_key_param = (DsaPrivateKeyParameters)_key_pair.Private;
            _public_key_param = (DsaPublicKeyParameters)_key_pair.Public;
        }
        public override void PerformTest()
        {
            byte[] k1 = Hex.Decode("d5014e4b60ef2ba8b6211b4062ba3224e0427dd3");
            byte[] k2 = Hex.Decode("345e8d05c075c3a508df729a1685690e68fcfb8c8117847e89063bca1f85d968fd281540b6e13bd1af989a1fbf17e06462bf511f9d0b140fb48ac1b1baa5bded");

            SecureRandom random = FixedSecureRandom.From(k1, k2);

            byte[] keyData = Hex.Decode("b5014e4b60ef2ba8b6211b4062ba3224e0427dd3");

            SecureRandom keyRandom = FixedSecureRandom.From(keyData, keyData);

            IBigInteger r = new BigInteger("68076202252361894315274692543577577550894681403");
            IBigInteger s = new BigInteger("1089214853334067536215539335472893651470583479365");
            DsaParametersGenerator pGen = new DsaParametersGenerator();

            pGen.Init(512, 80, random);

            DsaParameters parameters = pGen.GenerateParameters();
            DsaValidationParameters pValid = parameters.ValidationParameters;

            if (pValid.Counter != 105)
            {
                Fail("Counter wrong");
            }

            if (!pValue.Equals(parameters.P) || !qValue.Equals(parameters.Q))
            {
                Fail("p or q wrong");
            }

            DsaKeyPairGenerator dsaKeyGen = new DsaKeyPairGenerator();
            DsaKeyGenerationParameters genParam = new DsaKeyGenerationParameters(keyRandom, parameters);

            dsaKeyGen.Init(genParam);

            IAsymmetricCipherKeyPair pair = dsaKeyGen.GenerateKeyPair();

            ParametersWithRandom param = new ParametersWithRandom(pair.Private, keyRandom);

            DsaSigner dsa = new DsaSigner();

            dsa.Init(true, param);

            byte[] message = new BigInteger("968236873715988614170569073515315707566766479517").ToByteArrayUnsigned();
            IBigInteger[] sig = dsa.GenerateSignature(message);

            if (!r.Equals(sig[0]))
            {
                Fail("r component wrong." + SimpleTest.NewLine
                    + " expecting: " + r + SimpleTest.NewLine
                    + " got      : " + sig[0]);
            }

            if (!s.Equals(sig[1]))
            {
                Fail("s component wrong." + SimpleTest.NewLine
                    + " expecting: " + s + SimpleTest.NewLine
                    + " got      : " + sig[1]);
            }

            dsa.Init(false, pair.Public);

            if (!dsa.VerifySignature(message, sig[0], sig[1]))
            {
                Fail("verification fails");
            }
        }
		protected virtual DsaParameters GenerateParameters_FIPS186_2()
		{
			byte[] array = new byte[20];
			byte[] array2 = new byte[20];
			byte[] array3 = new byte[20];
			byte[] array4 = new byte[20];
			int num = (this.L - 1) / 160;
			byte[] array5 = new byte[this.L / 8];
			if (!(this.digest is Sha1Digest))
			{
				throw new InvalidOperationException("can only use SHA-1 for generating FIPS 186-2 parameters");
			}
			BigInteger bigInteger;
			int i;
			BigInteger bigInteger4;
			while (true)
			{
				this.random.NextBytes(array);
				DsaParametersGenerator.Hash(this.digest, array, array2);
				Array.Copy(array, 0, array3, 0, array.Length);
				DsaParametersGenerator.Inc(array3);
				DsaParametersGenerator.Hash(this.digest, array3, array3);
				for (int num2 = 0; num2 != array4.Length; num2++)
				{
					array4[num2] = (array2[num2] ^ array3[num2]);
				}
				byte[] expr_B6_cp_0 = array4;
				int expr_B6_cp_1 = 0;
				expr_B6_cp_0[expr_B6_cp_1] |= 128;
				byte[] expr_D0_cp_0 = array4;
				int expr_D0_cp_1 = 19;
				expr_D0_cp_0[expr_D0_cp_1] |= 1;
				bigInteger = new BigInteger(1, array4);
				if (bigInteger.IsProbablePrime(this.certainty))
				{
					byte[] array6 = Arrays.Clone(array);
					DsaParametersGenerator.Inc(array6);
					for (i = 0; i < 4096; i++)
					{
						for (int j = 0; j < num; j++)
						{
							DsaParametersGenerator.Inc(array6);
							DsaParametersGenerator.Hash(this.digest, array6, array2);
							Array.Copy(array2, 0, array5, array5.Length - (j + 1) * array2.Length, array2.Length);
						}
						DsaParametersGenerator.Inc(array6);
						DsaParametersGenerator.Hash(this.digest, array6, array2);
						Array.Copy(array2, array2.Length - (array5.Length - num * array2.Length), array5, 0, array5.Length - num * array2.Length);
						byte[] expr_18F_cp_0 = array5;
						int expr_18F_cp_1 = 0;
						expr_18F_cp_0[expr_18F_cp_1] |= 128;
						BigInteger bigInteger2 = new BigInteger(1, array5);
						BigInteger bigInteger3 = bigInteger2.Mod(bigInteger.ShiftLeft(1));
						bigInteger4 = bigInteger2.Subtract(bigInteger3.Subtract(BigInteger.One));
						if (bigInteger4.BitLength == this.L && bigInteger4.IsProbablePrime(this.certainty))
						{
							goto Block_6;
						}
					}
				}
			}
			Block_6:
			BigInteger g = this.CalculateGenerator_FIPS186_2(bigInteger4, bigInteger, this.random);
			return new DsaParameters(bigInteger4, bigInteger, g, new DsaValidationParameters(array, i));
		}
        public override void PerformTest()
        {
            IPasswordFinder pGet = new Password("secret".ToCharArray());
            PemReader pemRd = OpenPemResource("test.pem", pGet);
            IAsymmetricCipherKeyPair pair;

            object o;
            while ((o = pemRd.ReadObject()) != null)
            {
            //				if (o is AsymmetricCipherKeyPair)
            //				{
            //					ackp = (AsymmetricCipherKeyPair)o;
            //
            //					Console.WriteLine(ackp.Public);
            //					Console.WriteLine(ackp.Private);
            //				}
            //				else
            //				{
            //					Console.WriteLine(o.ToString());
            //				}
            }

            //
            // pkcs 7 data
            //
            pemRd = OpenPemResource("pkcs7.pem", null);

            ContentInfo d = (ContentInfo)pemRd.ReadObject();

            if (!d.ContentType.Equals(CmsObjectIdentifiers.EnvelopedData))
            {
                Fail("failed envelopedData check");
            }

            /*
            {
                //
                // ECKey
                //
                pemRd = OpenPemResource("eckey.pem", null);

                // TODO Resolve return type issue with EC keys and fix PemReader to return parameters
            //				ECNamedCurveParameterSpec spec = (ECNamedCurveParameterSpec)pemRd.ReadObject();

                pair = (AsymmetricCipherKeyPair)pemRd.ReadObject();
                ISigner sgr = SignerUtilities.GetSigner("ECDSA");

                sgr.Init(true, pair.Private);

                byte[] message = new byte[] { (byte)'a', (byte)'b', (byte)'c' };

                sgr.BlockUpdate(message, 0, message.Length);

                byte[] sigBytes = sgr.GenerateSignature();

                sgr.Init(false, pair.Public);

                sgr.BlockUpdate(message, 0, message.Length);

                if (!sgr.VerifySignature(sigBytes))
                {
                    Fail("EC verification failed");
                }

                // TODO Resolve this issue with the algorithm name, study Java version
            //				if (!((ECPublicKeyParameters) pair.Public).AlgorithmName.Equals("ECDSA"))
            //				{
            //					Fail("wrong algorithm name on public got: " + ((ECPublicKeyParameters) pair.Public).AlgorithmName);
            //				}
            //
            //				if (!((ECPrivateKeyParameters) pair.Private).AlgorithmName.Equals("ECDSA"))
            //				{
            //					Fail("wrong algorithm name on private got: " + ((ECPrivateKeyParameters) pair.Private).AlgorithmName);
            //				}
            }
            */

            //
            // writer/parser test
            //
            IAsymmetricCipherKeyPairGenerator kpGen = GeneratorUtilities.GetKeyPairGenerator("RSA");
            kpGen.Init(
                new RsaKeyGenerationParameters(
                BigInteger.ValueOf(0x10001),
                new SecureRandom(),
                768,
                25));

            pair = kpGen.GenerateKeyPair();

            keyPairTest("RSA", pair);

            //			kpGen = KeyPairGenerator.getInstance("DSA");
            //			kpGen.initialize(512, new SecureRandom());
            DsaParametersGenerator pGen = new DsaParametersGenerator();
            pGen.Init(512, 80, new SecureRandom());

            kpGen = GeneratorUtilities.GetKeyPairGenerator("DSA");
            kpGen.Init(
                new DsaKeyGenerationParameters(
                    new SecureRandom(),
                    pGen.GenerateParameters()));

            pair = kpGen.GenerateKeyPair();

            keyPairTest("DSA", pair);

            //
            // PKCS7
            //
            MemoryStream bOut = new MemoryStream();
            PemWriter pWrt = new PemWriter(new StreamWriter(bOut));

            pWrt.WriteObject(d);
            pWrt.Writer.Close();

            pemRd = new PemReader(new StreamReader(new MemoryStream(bOut.ToArray(), false)));
            d = (ContentInfo)pemRd.ReadObject();

            if (!d.ContentType.Equals(CmsObjectIdentifiers.EnvelopedData))
            {
                Fail("failed envelopedData recode check");
            }

            // OpenSSL test cases (as embedded resources)
            doOpenSslDsaTest("unencrypted");
            doOpenSslRsaTest("unencrypted");

            doOpenSslTests("aes128");
            doOpenSslTests("aes192");
            doOpenSslTests("aes256");
            doOpenSslTests("blowfish");
            doOpenSslTests("des1");
            doOpenSslTests("des2");
            doOpenSslTests("des3");
            doOpenSslTests("rc2_128");

            doOpenSslDsaTest("rc2_40_cbc");
            doOpenSslRsaTest("rc2_40_cbc");
            doOpenSslDsaTest("rc2_64_cbc");
            doOpenSslRsaTest("rc2_64_cbc");

            // TODO Figure out why exceptions differ for commented out cases
            doDudPasswordTest("7fd98", 0, "Corrupted stream - out of bounds length found");
            doDudPasswordTest("ef677", 1, "Corrupted stream - out of bounds length found");
            //			doDudPasswordTest("800ce", 2, "cannot recognise object in stream");
            doDudPasswordTest("b6cd8", 3, "DEF length 81 object truncated by 56");
            doDudPasswordTest("28ce09", 4, "DEF length 110 object truncated by 28");
            doDudPasswordTest("2ac3b9", 5, "DER length more than 4 bytes: 11");
            doDudPasswordTest("2cba96", 6, "DEF length 100 object truncated by 35");
            doDudPasswordTest("2e3354", 7, "DEF length 42 object truncated by 9");
            doDudPasswordTest("2f4142", 8, "DER length more than 4 bytes: 14");
            doDudPasswordTest("2fe9bb", 9, "DER length more than 4 bytes: 65");
            doDudPasswordTest("3ee7a8", 10, "DER length more than 4 bytes: 57");
            doDudPasswordTest("41af75", 11, "malformed sequence in DSA private key");
            doDudPasswordTest("1704a5", 12, "corrupted stream detected");
            //			doDudPasswordTest("1c5822", 13, "corrupted stream detected");
            //			doDudPasswordTest("5a3d16", 14, "corrupted stream detected");
            doDudPasswordTest("8d0c97", 15, "corrupted stream detected");
            doDudPasswordTest("bc0daf", 16, "corrupted stream detected");
            doDudPasswordTest("aaf9c4d",17, "Corrupted stream - out of bounds length found");

            // encrypted private key test
            pGet = new Password("password".ToCharArray());
            pemRd = OpenPemResource("enckey.pem", pGet);

            RsaPrivateCrtKeyParameters privKey = (RsaPrivateCrtKeyParameters)pemRd.ReadObject();

            if (!privKey.PublicExponent.Equals(new BigInteger("10001", 16)))
            {
                Fail("decryption of private key data check failed");
            }

            // general PKCS8 test
            pGet = new Password("password".ToCharArray());
            pemRd = OpenPemResource("pkcs8test.pem", pGet);

            while ((privKey = (RsaPrivateCrtKeyParameters)pemRd.ReadObject()) != null)
            {
                if (!privKey.PublicExponent.Equals(new BigInteger("10001", 16)))
                {
                    Fail("decryption of private key data check failed");
                }
            }
        }
		/// <summary>
		///   Creates a new signing key pair
		/// </summary>
		/// <param name="name">The name of the key or zone</param>
		/// <param name="recordClass">The record class of the DnsKeyRecord</param>
		/// <param name="timeToLive">The TTL in seconds to the DnsKeyRecord</param>
		/// <param name="flags">The Flags of the DnsKeyRecord</param>
		/// <param name="protocol">The protocol version</param>
		/// <param name="algorithm">The key algorithm</param>
		/// <param name="keyStrength">The key strength or 0 for default strength</param>
		/// <returns></returns>
		public static DnsKeyRecord CreateSigningKey(DomainName name, RecordClass recordClass, int timeToLive, DnsKeyFlags flags, byte protocol, DnsSecAlgorithm algorithm, int keyStrength = 0)
		{
			byte[] privateKey;
			byte[] publicKey;

			switch (algorithm)
			{
				case DnsSecAlgorithm.RsaSha1:
				case DnsSecAlgorithm.RsaSha1Nsec3Sha1:
				case DnsSecAlgorithm.RsaSha256:
				case DnsSecAlgorithm.RsaSha512:
					if (keyStrength == 0)
						keyStrength = (flags == (DnsKeyFlags.Zone | DnsKeyFlags.SecureEntryPoint)) ? 2048 : 1024;

					RsaKeyPairGenerator rsaKeyGen = new RsaKeyPairGenerator();
					rsaKeyGen.Init(new KeyGenerationParameters(_secureRandom, keyStrength));
					var rsaKey = rsaKeyGen.GenerateKeyPair();
					privateKey = PrivateKeyInfoFactory.CreatePrivateKeyInfo(rsaKey.Private).GetDerEncoded();
					var rsaPublicKey = (RsaKeyParameters) rsaKey.Public;
					var rsaExponent = rsaPublicKey.Exponent.ToByteArrayUnsigned();
					var rsaModulus = rsaPublicKey.Modulus.ToByteArrayUnsigned();

					int offset = 1;
					if (rsaExponent.Length > 255)
					{
						publicKey = new byte[3 + rsaExponent.Length + rsaModulus.Length];
						DnsMessageBase.EncodeUShort(publicKey, ref offset, (ushort) publicKey.Length);
					}
					else
					{
						publicKey = new byte[1 + rsaExponent.Length + rsaModulus.Length];
						publicKey[0] = (byte) rsaExponent.Length;
					}
					DnsMessageBase.EncodeByteArray(publicKey, ref offset, rsaExponent);
					DnsMessageBase.EncodeByteArray(publicKey, ref offset, rsaModulus);
					break;

				case DnsSecAlgorithm.Dsa:
				case DnsSecAlgorithm.DsaNsec3Sha1:
					if (keyStrength == 0)
						keyStrength = 1024;

					DsaParametersGenerator dsaParamsGen = new DsaParametersGenerator();
					dsaParamsGen.Init(keyStrength, 12, _secureRandom);
					DsaKeyPairGenerator dsaKeyGen = new DsaKeyPairGenerator();
					dsaKeyGen.Init(new DsaKeyGenerationParameters(_secureRandom, dsaParamsGen.GenerateParameters()));
					var dsaKey = dsaKeyGen.GenerateKeyPair();
					privateKey = PrivateKeyInfoFactory.CreatePrivateKeyInfo(dsaKey.Private).GetDerEncoded();
					var dsaPublicKey = (DsaPublicKeyParameters) dsaKey.Public;

					var dsaY = dsaPublicKey.Y.ToByteArrayUnsigned();
					var dsaP = dsaPublicKey.Parameters.P.ToByteArrayUnsigned();
					var dsaQ = dsaPublicKey.Parameters.Q.ToByteArrayUnsigned();
					var dsaG = dsaPublicKey.Parameters.G.ToByteArrayUnsigned();
					var dsaT = (byte) ((dsaY.Length - 64) / 8);

					publicKey = new byte[21 + 3 * dsaY.Length];
					publicKey[0] = dsaT;
					dsaQ.CopyTo(publicKey, 1);
					dsaP.CopyTo(publicKey, 21);
					dsaG.CopyTo(publicKey, 21 + dsaY.Length);
					dsaY.CopyTo(publicKey, 21 + 2 * dsaY.Length);
					break;

				case DnsSecAlgorithm.EccGost:
					ECDomainParameters gostEcDomainParameters = ECGost3410NamedCurves.GetByOid(CryptoProObjectIdentifiers.GostR3410x2001CryptoProA);

					var gostKeyGen = new ECKeyPairGenerator();
					gostKeyGen.Init(new ECKeyGenerationParameters(gostEcDomainParameters, _secureRandom));

					var gostKey = gostKeyGen.GenerateKeyPair();
					privateKey = PrivateKeyInfoFactory.CreatePrivateKeyInfo(gostKey.Private).GetDerEncoded();
					var gostPublicKey = (ECPublicKeyParameters) gostKey.Public;

					publicKey = new byte[64];

					gostPublicKey.Q.X.ToBigInteger().ToByteArrayUnsigned().CopyTo(publicKey, 32);
					gostPublicKey.Q.Y.ToBigInteger().ToByteArrayUnsigned().CopyTo(publicKey, 0);

					publicKey = publicKey.Reverse().ToArray();
					break;

				case DnsSecAlgorithm.EcDsaP256Sha256:
				case DnsSecAlgorithm.EcDsaP384Sha384:
					int ecDsaDigestSize;
					X9ECParameters ecDsaCurveParameter;

					if (algorithm == DnsSecAlgorithm.EcDsaP256Sha256)
					{
						ecDsaDigestSize = new Sha256Digest().GetDigestSize();
						ecDsaCurveParameter = NistNamedCurves.GetByOid(SecObjectIdentifiers.SecP256r1);
					}
					else
					{
						ecDsaDigestSize = new Sha384Digest().GetDigestSize();
						ecDsaCurveParameter = NistNamedCurves.GetByOid(SecObjectIdentifiers.SecP384r1);
					}

					ECDomainParameters ecDsaP384EcDomainParameters = new ECDomainParameters(
						ecDsaCurveParameter.Curve,
						ecDsaCurveParameter.G,
						ecDsaCurveParameter.N,
						ecDsaCurveParameter.H,
						ecDsaCurveParameter.GetSeed());

					var ecDsaKeyGen = new ECKeyPairGenerator();
					ecDsaKeyGen.Init(new ECKeyGenerationParameters(ecDsaP384EcDomainParameters, _secureRandom));

					var ecDsaKey = ecDsaKeyGen.GenerateKeyPair();
					privateKey = PrivateKeyInfoFactory.CreatePrivateKeyInfo(ecDsaKey.Private).GetDerEncoded();
					var ecDsaPublicKey = (ECPublicKeyParameters) ecDsaKey.Public;

					publicKey = new byte[ecDsaDigestSize * 2];

					ecDsaPublicKey.Q.X.ToBigInteger().ToByteArrayUnsigned().CopyTo(publicKey, 0);
					ecDsaPublicKey.Q.Y.ToBigInteger().ToByteArrayUnsigned().CopyTo(publicKey, ecDsaDigestSize);
					break;

				default:
					throw new NotSupportedException();
			}

			return new DnsKeyRecord(name, recordClass, timeToLive, flags, protocol, algorithm, publicKey, privateKey);
		}