Inheritance: KeyGenerationParameters
        public void Init(
			IKeyGenerationParameters parameters)
        {
            if (parameters == null)
                throw new ArgumentNullException("parameters");

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

            this.param = (DsaKeyGenerationParameters) parameters;
        }
Esempio n. 2
0
 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;
 }
        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");
            }
        }
Esempio n. 4
0
        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 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;
        }
Esempio n. 6
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);
        }
        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;
        }
Esempio n. 8
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;
        }
Esempio n. 9
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");
              }
        }