Exemple #1
0
        public override void PerformTest()
        {
            IAsymmetricCipherKeyPairGenerator g = GeneratorUtilities.GetKeyPairGenerator("ECIES");

            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.Init(
                new ECKeyGenerationParameters(
                    ecSpec,
                    new SecureRandom()));

            IBufferedCipher c1 = CipherUtilities.GetCipher("ECIES");
            IBufferedCipher c2 = CipherUtilities.GetCipher("ECIES");

            doTest(g, c1, c2);

            g = GeneratorUtilities.GetKeyPairGenerator("ECIES");

            g.Init(new KeyGenerationParameters(new SecureRandom(), 192));

            doTest(g, c1, c2);

            g = GeneratorUtilities.GetKeyPairGenerator("ECIES");

            g.Init(new KeyGenerationParameters(new SecureRandom(), 239));

            doTest(g, c1, c2);

            g = GeneratorUtilities.GetKeyPairGenerator("ECIES");

            g.Init(new KeyGenerationParameters(new SecureRandom(), 256));

            doTest(g, c1, c2);

            doDefTest(g, c1, c2);

            c1 = CipherUtilities.GetCipher("IES");
            c2 = CipherUtilities.GetCipher("IES");

            g = GeneratorUtilities.GetKeyPairGenerator("DH");

//			DHParameterSpec dhParams = new DHParameterSpec(p512, g512);
//			g.initialize(dhParams);
            g.Init(
                new DHKeyGenerationParameters(
                    new SecureRandom(),
                    new DHParameters(p512, g512)));

            doTest(g, c1, c2);

            doDefTest(g, c1, c2);
        }
Exemple #2
0
        private void Generate()
        {
            SecureRandom random = SecureRandom.GetInstance("SHA1PRNG");

            //
            // Generate a master key
            //
            IAsymmetricCipherKeyPairGenerator keyGen = GeneratorUtilities.GetKeyPairGenerator("ECDSA");

            keyGen.Init(new ECKeyGenerationParameters(SecObjectIdentifiers.SecP256r1, random));

            AsymmetricCipherKeyPair kpSign = keyGen.GenerateKeyPair();

            PgpKeyPair ecdsaKeyPair = new PgpKeyPair(PublicKeyAlgorithmTag.ECDsa, kpSign, DateTime.UtcNow);

            //
            // Generate an encryption key
            //
            keyGen = GeneratorUtilities.GetKeyPairGenerator("ECDH");
            keyGen.Init(new ECKeyGenerationParameters(SecObjectIdentifiers.SecP256r1, random));

            AsymmetricCipherKeyPair kpEnc = keyGen.GenerateKeyPair();

            PgpKeyPair ecdhKeyPair = new PgpKeyPair(PublicKeyAlgorithmTag.ECDH, kpEnc, DateTime.UtcNow);

            //
            // Generate a key ring
            //
            char[] passPhrase = "test".ToCharArray();
            PgpKeyRingGenerator keyRingGen = new PgpKeyRingGenerator(PgpSignature.PositiveCertification, ecdsaKeyPair,
                                                                     "*****@*****.**", SymmetricKeyAlgorithmTag.Aes256, passPhrase, true, null, null, random);

            keyRingGen.AddSubKey(ecdhKeyPair);

            PgpPublicKeyRing pubRing = keyRingGen.GeneratePublicKeyRing();

            // TODO: add check of KdfParameters
            DoBasicKeyRingCheck(pubRing);

            PgpSecretKeyRing secRing = keyRingGen.GenerateSecretKeyRing();

            PgpPublicKeyRing pubRingEnc = new PgpPublicKeyRing(pubRing.GetEncoded());

            if (!Arrays.AreEqual(pubRing.GetEncoded(), pubRingEnc.GetEncoded()))
            {
                Fail("public key ring encoding failed");
            }

            PgpSecretKeyRing secRingEnc = new PgpSecretKeyRing(secRing.GetEncoded());

            if (!Arrays.AreEqual(secRing.GetEncoded(), secRingEnc.GetEncoded()))
            {
                Fail("secret key ring encoding failed");
            }

            PgpPrivateKey pgpPrivKey = secRing.GetSecretKey().ExtractPrivateKey(passPhrase);
        }
Exemple #3
0
        public override void PerformTest()
        {
            IAsymmetricCipherKeyPairGenerator g = GeneratorUtilities.GetKeyPairGenerator("ECIES");

            X9ECParameters     x9     = ECNamedCurveTable.GetByName("prime239v1");
            ECDomainParameters ecSpec = new ECDomainParameters(x9.Curve, x9.G, x9.N, x9.H);

            g.Init(
                new ECKeyGenerationParameters(
                    ecSpec,
                    new SecureRandom()));

            IBufferedCipher c1 = CipherUtilities.GetCipher("ECIES");
            IBufferedCipher c2 = CipherUtilities.GetCipher("ECIES");

            doTest(g, c1, c2);

            g = GeneratorUtilities.GetKeyPairGenerator("ECIES");

            g.Init(new KeyGenerationParameters(new SecureRandom(), 192));

            doTest(g, c1, c2);

            g = GeneratorUtilities.GetKeyPairGenerator("ECIES");

            g.Init(new KeyGenerationParameters(new SecureRandom(), 239));

            doTest(g, c1, c2);

            g = GeneratorUtilities.GetKeyPairGenerator("ECIES");

            g.Init(new KeyGenerationParameters(new SecureRandom(), 256));

            doTest(g, c1, c2);

            doDefTest(g, c1, c2);

            c1 = CipherUtilities.GetCipher("IES");
            c2 = CipherUtilities.GetCipher("IES");

            g = GeneratorUtilities.GetKeyPairGenerator("DH");

//			DHParameterSpec dhParams = new DHParameterSpec(p512, g512);
//			g.initialize(dhParams);
            g.Init(
                new DHKeyGenerationParameters(
                    new SecureRandom(),
                    new DHParameters(p512, g512)));

            doTest(g, c1, c2);

            doDefTest(g, c1, c2);
        }
        public KeyAgreement()
        {
            _curve = new FpCurve(
                new BigInteger("BDB6F4FE3E8B1D9E0DA8C0D46F4C318CEFE4AFE3B6B8551F", 16), // q
                new BigInteger("BB8E5E8FBC115E139FE6A814FE48AAA6F0ADA1AA5DF91985", 16), // a
                new BigInteger("1854BEBDC31B21B7AEFC80AB0ECD10D5B1B3308E6DBF11C1", 16)  // b
                );

            _ecSpec = new ECDomainParameters(
                _curve,
                new FpPoint(_curve,
                        new FpFieldElement(
                            _curve.Q,
                            new BigInteger("4AD5F7048DE709AD51236DE65E4D4B482C836DC6E4106640", 16)
                        ),
                        new FpFieldElement(
                            _curve.Q,
                            new BigInteger("02BB3A02D4AAADACAE24817A4CA3A1B014B5270432DB27D2", 16))
                        ), // G
                        new BigInteger("BDB6F4FE3E8B1D9E0DA8C0D40FC962195DFAE76F56564677", 16), // n
                        BigInteger.One// h
                );
            _keyGen = GeneratorUtilities.GetKeyPairGenerator("ECDH");
            _keyGen.Init(new ECKeyGenerationParameters(_ecSpec, new SecureRandom()));
        }
Exemple #5
0
        private void GetRsaWithPem(Int32 strength, Boolean usePkcs8, out string pirvKey, out string pubKey)
        {
            IAsymmetricCipherKeyPairGenerator kpGen = GeneratorUtilities.GetKeyPairGenerator("RSA");

            kpGen.Init(new KeyGenerationParameters(new SecureRandom(), strength));

            var privKeyParam = kpGen.GenerateKeyPair().Private;
            var pubKeyParam  = kpGen.GenerateKeyPair().Public;

            using (StringWriter sw = new StringWriter())
            {
                PemWriter pWrt = new PemWriter(sw);
                if (usePkcs8)
                {
                    var pkcs8 = new Pkcs8Generator(privKeyParam);
                    pWrt.WriteObject(pkcs8);
                }
                else
                {
                    pWrt.WriteObject(privKeyParam);
                }

                pirvKey = sw.ToString();
            }

            using (StringWriter sw = new StringWriter())
            {
                PemWriter pWrt = new PemWriter(sw);
                pWrt.WriteObject(pubKeyParam);
                pubKey = sw.ToString();
            }
        }
Exemple #6
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Crypto"/> class.
        ///   May I have a new Crypto?
        /// </summary>
        public Crypto()
        {
            _random = new SecureRandom();

            _keyGen = GeneratorUtilities.GetKeyPairGenerator("ElGamal");
            var parameterGenerator = new ElGamalParametersGenerator();

            parameterGenerator.Init(512, 10, _random);
            var parameters = parameterGenerator.GenerateParameters();

            _keyGen.Init(new ElGamalKeyGenerationParameters(_random, parameters));
            _keys    = _keyGen.GenerateKeyPair();
            _aCipher = CipherUtilities.GetCipher("ElGamal/NONE/PKCS1Padding");

            _cipher = CipherUtilities.GetCipher("AES/CBC/PKCS7Padding");
            //new PaddedBufferedBlockCipher(new CbcBlockCipher(new AesEngine()));

            Iv = new byte[_cipher.GetBlockSize()];
            _random.NextBytes(Iv);

            _hasher = new Sha256Digest();

            KeyPair = new AsymmetricCipherKeyPair(
                new AsymmetricKey(_keys.Public), new AsymmetricKey(_keys.Private));
        }
        public static void GenerateKey(string username, string password, string keyStoreUrl)
        {
            IAsymmetricCipherKeyPairGenerator kpg = GeneratorUtilities.GetKeyPairGenerator("RSA");

            // new RsaKeyPairGenerator();

            kpg.Init(new RsaKeyGenerationParameters(BigInteger.ValueOf(0x13), new SecureRandom(), 1024, 8));

            AsymmetricCipherKeyPair kp = kpg.GenerateKeyPair();

            FileStream out1 = new FileInfo(string.Format("{0}_PrivateKey.txt", keyStoreUrl)).OpenWrite();
            FileStream out2 = new FileInfo(string.Format("{0}_PublicKey.txt", keyStoreUrl)).OpenWrite();

            ExportKeyPair(out1, out2, kp.Public, kp.Private, PublicKeyAlgorithmTag.RsaGeneral, SymmetricKeyAlgorithmTag.Cast5, username, password.ToCharArray(), true);

            out1.Close();
            out2.Close();

            /*
             *
             * 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");
             *
             * ElGamalParametersGenerator eGen = new ElGamalParametersGenerator();
             *
             * eGen.Init(1024,80,new SecureRandom());
             *
             * ElGamalParameters elParams = eGen.GenerateParameters();
             *
             * ElGamalKeyGenerationParameters elKgp = new ElGamalKeyGenerationParameters(new SecureRandom(), elParams);
             *
             * elgKpg.Init(elKgp);
             *
             * //
             * // this is quicker because we are using preGenerated parameters.
             * //
             * AsymmetricCipherKeyPair elgKp = elgKpg.GenerateKeyPair();
             *
             * FileStream out3 = new FileInfo(string.Format("{0}_PrivateKey_ELGMAL.txt", keyStoreUrl)).OpenWrite();
             * FileStream out4 = new FileInfo(string.Format("{0}_PublicKey_ELGMAL.txt", keyStoreUrl)).OpenWrite();
             *
             * ExportKeyPair(out3, out4, dsaKp, elgKp, username, password.ToCharArray(), true);
             *
             * out3.Close();
             * out4.Close();
             *
             */
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="KeyGenerator"/> class
 /// with the specified key size.
 /// </summary>
 /// <remarks>Following key sizes are supported:
 /// - 192
 /// - 224
 /// - 239
 /// - 256 (default)
 /// - 384
 /// - 521</remarks>
 /// <param name="keySize">The key size.</param>
 public KeyGenerator(int keySize)
 {
     var secureRandom = SecureRandom.GetInstance("SHA256PRNG");
     var keyParams = new KeyGenerationParameters(secureRandom, keySize);
     keyGenerator = new ECKeyPairGenerator();
     keyGenerator.Init(keyParams);
 }
Exemple #9
0
        private static AsymmetricCipherKeyPair GetEcCipherKeyPair(string algorithm, DerObjectIdentifier identifier)
        {
            IAsymmetricCipherKeyPairGenerator kpg = GeneratorUtilities.GetKeyPairGenerator(algorithm);

            kpg.Init(new ECKeyGenerationParameters(identifier, new SecureRandom()));
            return(kpg.GenerateKeyPair());
        }
Exemple #10
0
        // previous code found to cause a NullPointerException
        private void nullPointerTest()
        {
            IAsymmetricCipherKeyPairGenerator keyGen = GeneratorUtilities.GetKeyPairGenerator("RSA");

            keyGen.Init(new KeyGenerationParameters(new SecureRandom(), 1024));

            AsymmetricCipherKeyPair pair = keyGen.GenerateKeyPair();

            IList oids   = new ArrayList();
            IList values = new ArrayList();

            oids.Add(X509Extensions.BasicConstraints);
            values.Add(new X509Extension(true, new DerOctetString(new BasicConstraints(true))));
            oids.Add(X509Extensions.KeyUsage);
            values.Add(new X509Extension(true, new DerOctetString(
                                             new KeyUsage(KeyUsage.KeyCertSign | KeyUsage.CrlSign))));
            SubjectKeyIdentifier subjectKeyIdentifier = new SubjectKeyIdentifierStructure(pair.Public);
            X509Extension        ski = new X509Extension(false, new DerOctetString(subjectKeyIdentifier));

            oids.Add(X509Extensions.SubjectKeyIdentifier);
            values.Add(ski);

            AttributePkcs attribute = new AttributePkcs(PkcsObjectIdentifiers.Pkcs9AtExtensionRequest,
                                                        new DerSet(new X509Extensions(oids, values)));

            Pkcs10CertificationRequest p1 = new Pkcs10CertificationRequest(
                "SHA1WithRSA", new X509Name("cn=csr"), pair.Public, new DerSet(attribute), pair.Private);
            Pkcs10CertificationRequest p2 = new Pkcs10CertificationRequest(
                "SHA1WithRSA", new X509Name("cn=csr"), pair.Public, new DerSet(attribute), pair.Private);

            if (!p1.Equals(p2))
            {
                Fail("cert request comparison failed");
            }
        }
Exemple #11
0
        static TspTestUtil()
        {
            rand = new SecureRandom();

            kpg = GeneratorUtilities.GetKeyPairGenerator("RSA");
            kpg.Init(new RsaKeyGenerationParameters(
                         BigInteger.ValueOf(0x10001), rand, 1024, 25));

            desede128kg = GeneratorUtilities.GetKeyGenerator("DESEDE");
            desede128kg.Init(new KeyGenerationParameters(rand, 112));

            desede192kg = GeneratorUtilities.GetKeyGenerator("DESEDE");
            desede192kg.Init(new KeyGenerationParameters(rand, 168));

            rc240kg = GeneratorUtilities.GetKeyGenerator("RC2");
            rc240kg.Init(new KeyGenerationParameters(rand, 40));

            rc264kg = GeneratorUtilities.GetKeyGenerator("RC2");
            rc264kg.Init(new KeyGenerationParameters(rand, 64));

            rc2128kg = GeneratorUtilities.GetKeyGenerator("RC2");
            rc2128kg.Init(new KeyGenerationParameters(rand, 128));

            serialNumber = BigInteger.One;
        }
Exemple #12
0
        public KeyAgreement()
        {
            _curve = new FpCurve(
                new BigInteger("BDB6F4FE3E8B1D9E0DA8C0D46F4C318CEFE4AFE3B6B8551F", 16), // q
                new BigInteger("BB8E5E8FBC115E139FE6A814FE48AAA6F0ADA1AA5DF91985", 16), // a
                new BigInteger("1854BEBDC31B21B7AEFC80AB0ECD10D5B1B3308E6DBF11C1", 16)  // b
                );

            _ecSpec = new ECDomainParameters(
                _curve,
                new FpPoint(_curve,
                            new FpFieldElement(
                                _curve.Q,
                                new BigInteger("4AD5F7048DE709AD51236DE65E4D4B482C836DC6E4106640", 16)
                                ),
                            new FpFieldElement(
                                _curve.Q,
                                new BigInteger("02BB3A02D4AAADACAE24817A4CA3A1B014B5270432DB27D2", 16))
                            ),                                                          // G
                new BigInteger("BDB6F4FE3E8B1D9E0DA8C0D40FC962195DFAE76F56564677", 16), // n
                BigInteger.One                                                          // h
                );
            _keyGen = GeneratorUtilities.GetKeyPairGenerator("ECDH");
            _keyGen.Init(new ECKeyGenerationParameters(_ecSpec, new SecureRandom()));
        }
Exemple #13
0
        public PgpSecretKey GenerateKeyPair(string identity, string passPhrase)
        {
            if (string.IsNullOrEmpty(identity))
            {
                throw new ArgumentException("Identity must be supplied", nameof(identity));
            }
            if (string.IsNullOrEmpty(passPhrase))
            {
                throw new ArgumentException("Pass phrase must be supplied", nameof(passPhrase));
            }

            IAsymmetricCipherKeyPairGenerator kpg = GeneratorUtilities.GetKeyPairGenerator("RSA");

            kpg.Init(new RsaKeyGenerationParameters(BigInteger.ValueOf(0x10001), new SecureRandom(), 1024, 25));

            AsymmetricCipherKeyPair kp = kpg.GenerateKeyPair();

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

            return(secretKey);
            //return new PgpKeyPair(secretKey.PublicKey, secretKey.ExtractPrivateKey(passPhrase.ToCharArray()));
        }
Exemple #14
0
		static TspTestUtil()
		{
			rand = new SecureRandom();

			kpg = GeneratorUtilities.GetKeyPairGenerator("RSA");
			kpg.Init(new RsaKeyGenerationParameters(
				BigInteger.ValueOf(0x10001), rand, 1024, 25));

			desede128kg = GeneratorUtilities.GetKeyGenerator("DESEDE");
			desede128kg.Init(new KeyGenerationParameters(rand, 112));

			desede192kg = GeneratorUtilities.GetKeyGenerator("DESEDE");
			desede192kg.Init(new KeyGenerationParameters(rand, 168));

			rc240kg = GeneratorUtilities.GetKeyGenerator("RC2");
			rc240kg.Init(new KeyGenerationParameters(rand, 40));

			rc264kg = GeneratorUtilities.GetKeyGenerator("RC2");
			rc264kg.Init(new KeyGenerationParameters(rand, 64));

			rc2128kg = GeneratorUtilities.GetKeyGenerator("RC2");
			rc2128kg.Init(new KeyGenerationParameters(rand, 128));

			serialNumber = BigInteger.One;
		}
        public override void PerformTest()
        {
            IAsymmetricCipherKeyPairGenerator dsaKpg = GeneratorUtilities.GetKeyPairGenerator("DSA");

            dsaKpg.Init(new DsaKeyGenerationParameters(random, testDsaParams));
            AsymmetricCipherKeyPair testDsaKp  = dsaKpg.GenerateKeyPair();
            AsymmetricKeyParameter  testDsaKey = testDsaKp.Private;

            doWriteReadTest(testDsaKey);
            doWriteReadTests(testDsaKey, algorithms);

            doWriteReadTest(testRsaKey);
            doWriteReadTests(testRsaKey, algorithms);

            AsymmetricKeyParameter ecPriv = PrivateKeyFactory.CreateKey(testEcDsaKeyBytes);

            doWriteReadTest(ecPriv);
            doWriteReadTests(ecPriv, algorithms);

            IAsymmetricCipherKeyPairGenerator ecKpg = GeneratorUtilities.GetKeyPairGenerator("ECDSA");

            ecKpg.Init(new KeyGenerationParameters(random, 239));
            ecPriv = ecKpg.GenerateKeyPair().Private;
            doWriteReadTest(ecPriv);
            doWriteReadTests(ecPriv, algorithms);

            // override test
            PemWriter pWrt = new PemWriter(new StringWriter());

            object o = new PemObject("FRED", new byte[100]);

            pWrt.WriteObject(o);

            pWrt.Writer.Close();
        }
        public override void PerformTest()
        {
            IAsymmetricCipherKeyPairGenerator pGen     = GeneratorUtilities.GetKeyPairGenerator("RSA");
            RsaKeyGenerationParameters        genParam = new RsaKeyGenerationParameters(
                BigInteger.ValueOf(0x10001), new SecureRandom(), 512, 25);

            pGen.Init(genParam);

            AsymmetricCipherKeyPair pair = pGen.GenerateKeyPair();

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

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

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

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

            AsymmetricKeyParameter key = PrivateKeyFactory.CreateKey(info);

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

            doOpensslTestKeys();
        }
Exemple #17
0
        public void TestPkcs8Plain()
        {
            IAsymmetricCipherKeyPairGenerator kpGen = GeneratorUtilities.GetKeyPairGenerator("RSA");

            kpGen.Init(new KeyGenerationParameters(new SecureRandom(), 1024));

            AsymmetricKeyParameter privKey = kpGen.GenerateKeyPair().Private;

            StringWriter sw   = new StringWriter();
            PemWriter    pWrt = new PemWriter(sw);

            Pkcs8Generator pkcs8 = new Pkcs8Generator(privKey);

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

            string result = sw.ToString();

            PemReader pRd = new PemReader(new StringReader(result), new Password("hello".ToCharArray()));

            AsymmetricKeyParameter rdKey = (AsymmetricKeyParameter)pRd.ReadObject();

            pRd.Reader.Close();

            Assert.AreEqual(privKey, rdKey);
        }
Exemple #18
0
        /**
         * Create a random 1024 bit RSA key pair
         */
        public static IAsymmetricCipherKeyPair GenerateRsaKeyPair()
        {
            IAsymmetricCipherKeyPairGenerator kpGen = GeneratorUtilities.GetKeyPairGenerator("RSA");

            kpGen.Init(new KeyGenerationParameters(new SecureRandom(), 1024));

            return(kpGen.GenerateKeyPair());
        }
        public static void ECDHKeyExchangeExample()
        {
            /*NOTE: this should represent an example of ECDH. As there are no mechanisms used in order to ensure if Alice is Alice and Bob is Bob as now
             * certificate is used in this example. */

            /* Define used key exchange algorithm. In our case this is elliptic curve diffie hellmann. */
            const string Algorithm = "ECDH";

            /* ALICE starts the key exchange. She sends the the X and Y coordinates of her public key as well as the used curve to BOB */

            const string Alicebase16strpubX = "0x14CC3B7FBEF441E21DE27CA72F5E2BB60EFEA474A5973028589016D36DB11E267A1F49FD2DC1F42553E0A6BB4E66CA9E8C2667074A7EABAD1A10545626B53F4ECC9";
            const string Alicebase16strY    = "0x190E33894B32DD6FDFDF8E560630B2419CC45A7FF770530CD564354A5D4D7E76DB1F4A1C0DC9E7D5720F257C5A8D2D908C342217300ACD78D258D00EEDDB2C441F5";
            const string curve = "P-521";//"SECP521R1";

            /****************************************************************************/

            /* BOB starts the actions. Bob uses the public public key coordinates as well as the curve to generate an ephemeral key
             * pair on his side.
             */

            X9ECParameters ecP = NistNamedCurves.GetByName(curve);

            FpCurve c = (FpCurve)ecP.Curve;

            ECFieldElement x = c.FromBigInteger(new BigInteger(System.Numerics.BigInteger.Parse(Alicebase16strpubX, NumberStyles.HexNumber).ToString()));
            ECFieldElement y = c.FromBigInteger(new BigInteger(System.Numerics.BigInteger.Parse(Alicebase16strY, NumberStyles.HexNumber).ToString()));

            Org.BouncyCastle.Math.EC.ECPoint q    = new FpPoint(c, x, y);
            ECPublicKeyParameters            xxpk = new ECPublicKeyParameters("ECDH", q, SecObjectIdentifiers.SecP521r1);

            IAsymmetricCipherKeyPairGenerator KeyGen       = GeneratorUtilities.GetKeyPairGenerator(Algorithm);
            KeyGenerationParameters           keygenParams = new ECKeyGenerationParameters(new ECDomainParameters(ecP.Curve, ecP.G, ecP.N), new SecureRandom());

            KeyGen.Init(keygenParams);

            AsymmetricCipherKeyPair KeyPair  = KeyGen.GenerateKeyPair();
            IBasicAgreement         KeyAgree = AgreementUtilities.GetBasicAgreement(Algorithm);

            /*****************************************************************************/

            /* BOB calculates the SHARED SECRET */
            KeyAgree.Init(KeyPair.Private);
            BigInteger Agree = KeyAgree.CalculateAgreement(xxpk);
            /*****************************************************************************/

            /*BOB encrypts his secret message. Using the Encryption helper method with AES 256 CBC. The helper method is using the last
             * 16 bytes of the generated secret and a generated initial vector of 16 byte to encrypt*/
            string ciphertext             = Encryption.EncryptString("Hallo Alice, this is an important message to you.", Agree.ToByteArray());
            ECPublicKeyParameters params2 = (ECPublicKeyParameters)KeyPair.Public;

            /*****************************************************************************/

            /*BOB is sending the x and y coordinates of his public key and the encrypted message to Alice on a public (not secured) channel*/
            Console.WriteLine("PublicKeyX Base(16): " + params2.Q.XCoord.ToBigInteger().ToString(16).ToUpper());
            Console.WriteLine("PublicKeyY Base(16): " + params2.Q.YCoord.ToBigInteger().ToString(16).ToUpper());
            Console.WriteLine("Ciphertext: " + ciphertext);
            /*****************************************************************************/
        }
Exemple #20
0
        public static void TestMethod()
        {
            //BEGIN SETUP ALICE
            IAsymmetricCipherKeyPairGenerator aliceKeyGen    = GeneratorUtilities.GetKeyPairGenerator(Algorithm);
            DHParametersGenerator             aliceGenerator = new DHParametersGenerator();

            aliceGenerator.Init(KeyBitSize, DefaultPrimeProbability, new SecureRandom());
            DHParameters aliceParameters = aliceGenerator.GenerateParameters();

            KeyGenerationParameters aliceKGP = new DHKeyGenerationParameters(new SecureRandom(), aliceParameters);

            aliceKeyGen.Init(aliceKGP);

            AsymmetricCipherKeyPair aliceKeyPair  = aliceKeyGen.GenerateKeyPair();
            IBasicAgreement         aliceKeyAgree = AgreementUtilities.GetBasicAgreement(Algorithm);

            aliceKeyAgree.Init(aliceKeyPair.Private);

            //END SETUP ALICE

            /////AT THIS POINT, Alice's Public Key, Alice's Parameter P and Alice's Parameter G are sent unsecure to BOB

            //BEGIN SETUP BOB
            IAsymmetricCipherKeyPairGenerator bobKeyGen = GeneratorUtilities.GetKeyPairGenerator(Algorithm);
            DHParameters bobParameters = new DHParameters(aliceParameters.P, aliceParameters.G);

            KeyGenerationParameters bobKGP = new DHKeyGenerationParameters(new SecureRandom(), bobParameters);

            bobKeyGen.Init(bobKGP);

            AsymmetricCipherKeyPair bobKeyPair  = bobKeyGen.GenerateKeyPair();
            IBasicAgreement         bobKeyAgree = AgreementUtilities.GetBasicAgreement(Algorithm);

            bobKeyAgree.Init(bobKeyPair.Private);
            //END SETUP BOB

            BigInteger aliceAgree = aliceKeyAgree.CalculateAgreement(bobKeyPair.Public);
            BigInteger bobAgree   = bobKeyAgree.CalculateAgreement(aliceKeyPair.Public);

            if (!aliceAgree.Equals(bobAgree))
            {
                throw new Exception("Keys do not match.");
            }

            byte[] nonSecretMessage = GetBytes("HeaderMessageForASDF");
            byte[] secretMessage    = GetBytes("Secret message contents");
            byte[] decNonSecretBytes;

            KeyParameter sharedKey = new KeyParameter(aliceAgree.ToByteArrayUnsigned());

            var encMessage = EncryptMessage(sharedKey, nonSecretMessage, secretMessage);
            var decMessage = DecryptMessage(sharedKey, encMessage, out decNonSecretBytes);

            var decNonSecretMessage = GetString(decNonSecretBytes);
            var decSecretMessage    = GetString(decMessage);

            Debug.WriteLine(decNonSecretMessage + " - " + decSecretMessage);
        }
Exemple #21
0
        private void parametersTest()
        {
//	        AlgorithmParameterGenerator a = AlgorithmParameterGenerator.getInstance("GOST3410");
//	        a.init(512, random);
//	        AlgorithmParameters params = a.generateParameters();
//
//	        byte[] encodeParams = params.getEncoded();
//
//	        AlgorithmParameters a2 = AlgorithmParameters.getInstance("GOST3410");
//	        a2.init(encodeParams);
//
//	        // a and a2 should be equivalent!
//	        byte[] encodeParams_2 = a2.getEncoded();
//
//	        if (!arrayEquals(encodeParams, encodeParams_2))
//	        {
//	            Fail("encode/decode parameters failed");
//	        }

//			GOST3410ParameterSpec gost3410P = new GOST3410ParameterSpec(
//				CryptoProObjectIdentifiers.gostR3410_94_CryptoPro_B.getId());
//			g.initialize(gost3410P, new SecureRandom());
            IAsymmetricCipherKeyPairGenerator g = GeneratorUtilities.GetKeyPairGenerator("GOST3410");

            g.Init(
                new Gost3410KeyGenerationParameters(
                    new SecureRandom(),
                    CryptoProObjectIdentifiers.GostR3410x94CryptoProB));

            IAsymmetricCipherKeyPair p = g.GenerateKeyPair();

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

            ISigner s = SignerUtilities.GetSigner("GOST3410");

            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("GOST3410");

            s.Init(false, vKey);

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

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

            keyStoreTest(sKey, vKey);
        }
Exemple #22
0
        /// <summary>
        /// Generates a new pgp key pair
        /// </summary>
        /// <returns>Generated pgp key pair</returns>
        public override PgpKeyPair Generate()
        {
            IAsymmetricCipherKeyPairGenerator generator = GeneratorUtilities.GetKeyPairGenerator("RSA");

            generator.Init(new RsaKeyGenerationParameters(BigInteger.ValueOf(0x10001), pgpRandom, 2048, 12));
            PgpKeyPair keyPair = new PgpKeyPair(PublicKeyAlgorithmTag.RsaGeneral, generator.GenerateKeyPair(), DateTime.Now);

            return(keyPair);
        }
Exemple #23
0
        public DHProvider(DHParameters parameters)
        {
            _parameters = parameters;

            IAsymmetricCipherKeyPairGenerator keyGen = GeneratorUtilities.GetKeyPairGenerator("DH");
            KeyGenerationParameters           kgp    = new DHKeyGenerationParameters(new SecureRandom(), _parameters);

            keyGen.Init(kgp);
            _kp = keyGen.GenerateKeyPair();
        }
 public BouncyCastleKeyGenerator(int bits)
 {
     _keyPairGenerator = GeneratorUtilities.GetKeyPairGenerator(Algorithm);
     _keyPairGenerator.Init(
         new RsaKeyGenerationParameters(
             BigInteger.ValueOf(17),
             new SecureRandom(),
             bits,
             25));
 }
        public static AsymmetricCipherKeyPair GenerateKeys()
        {
            X9ECParameters     ecParameters = NistNamedCurves.GetByName("P-256");
            ECDomainParameters ecSpec       = new ECDomainParameters(ecParameters.Curve, ecParameters.G, ecParameters.N, ecParameters.H, ecParameters.GetSeed());
            IAsymmetricCipherKeyPairGenerator keyPairGenerator = GeneratorUtilities.GetKeyPairGenerator("ECDH");

            keyPairGenerator.Init(new ECKeyGenerationParameters(ecSpec, new SecureRandom()));

            return(keyPairGenerator.GenerateKeyPair());
        }
        internal static AsymmetricCipherKeyPair GenerateAsymmetricCipherKeyPair()
        {
            X9ECParameters     ecParameters       = NistNamedCurves.GetByName(P256_CURVE_NAME);
            ECDomainParameters ecDomainParameters = new ECDomainParameters(ecParameters.Curve, ecParameters.G, ecParameters.N, ecParameters.H, ecParameters.GetSeed());

            IAsymmetricCipherKeyPairGenerator keyPairGenerator = GeneratorUtilities.GetKeyPairGenerator(ECDH_ALGORITHM_NAME);

            keyPairGenerator.Init(new ECKeyGenerationParameters(ecDomainParameters, new SecureRandom()));

            return(keyPairGenerator.GenerateKeyPair());
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="KeyGenerator"/> class
        /// with the specified key size and seed.
        /// </summary>
        /// <remarks>Following key sizes are supported:
        /// - 192
        /// - 224
        /// - 239
        /// - 256 (default)
        /// - 384
        /// - 521</remarks>
        /// <param name="keySize">The key size.</param>
        /// <param name="seed">The seed.</param>
        public KeyGenerator(int keySize, byte[] seed)
        {
            var secureRandom = SecureRandom.GetInstance("SHA256PRNG");

            secureRandom.SetSeed(seed);

            var keyParams = new KeyGenerationParameters(secureRandom, keySize);

            keyGenerator = new ECKeyPairGenerator();
            keyGenerator.Init(keyParams);
        }
Exemple #28
0
        /// <summary>
        /// Generate a key pair.
        /// </summary>
        /// <param name="keygen">an instance of IAsymmetricCipherKeyPairGenerator</param>
        /// <param name="keySize">iKeySize Key size of key pair</param>
        /// <param name="random">an instance of IRandomGenerator</param>
        /// <returns>A key pair</returns>
        public static AsymmetricCipherKeyPair GenerateKeyPair(IAsymmetricCipherKeyPairGenerator keygen, int keySize, IRandomGenerator random)
        {
            // Create a SecureRandom
            var rand = new SecureRandom(random);

            // Initialize key pair generator with key strength and a randomness
            keygen.Init(new KeyGenerationParameters(rand, keySize));

            // Generate and return the key pair
            return(keygen.GenerateKeyPair());
        }
        /// <summary>
        /// Generate a key pair.
        /// </summary>
        /// <param name="keygen">an instance of IAsymmetricCipherKeyPairGenerator</param>
        /// <param name="keySize">iKeySize Key size of key pair</param>
        /// <param name="random">an instance of IRandomGenerator</param>
        /// <returns>A key pair</returns>
        public static AsymmetricCipherKeyPair GenerateKeyPair(IAsymmetricCipherKeyPairGenerator keygen, int keySize, IRandomGenerator random)
        {
            // Create a SecureRandom
            var rand = new SecureRandom(random);

            // Initialize key pair generator with key strength and a randomness
            keygen.Init(new KeyGenerationParameters(rand, keySize));

            // Generate and return the key pair
            return keygen.GenerateKeyPair();
        }
Exemple #30
0
        private void doTestDesAndDesEde(
            IBigInteger g,
            IBigInteger p)
        {
            DHParameters dhParams = new DHParameters(p, g, null, 256);

            IAsymmetricCipherKeyPairGenerator keyGen = GeneratorUtilities.GetKeyPairGenerator("DH");

            keyGen.Init(new DHKeyGenerationParameters(new SecureRandom(), dhParams));

            IAsymmetricCipherKeyPair kp = keyGen.GenerateKeyPair();

            IBasicAgreement keyAgreement = AgreementUtilities.GetBasicAgreement("DH");

            keyAgreement.Init(kp.Private);
            IBigInteger agreed = keyAgreement.CalculateAgreement(kp.Public);

            byte[] agreedBytes = agreed.ToByteArrayUnsigned();

            // TODO Figure out where the magic happens of choosing the right
            // bytes from 'agreedBytes' for each key type - need C# equivalent?
            // (see JCEDHKeyAgreement.engineGenerateSecret)

//			SecretKey key = keyAgreement.generateSecret("DES");
//
//			if (key.getEncoded().length != 8)
//			{
//				Fail("DES length wrong");
//			}
//
//			if (!DESKeySpec.isParityAdjusted(key.getEncoded(), 0))
//			{
//				Fail("DES parity wrong");
//			}
//
//			key = keyAgreement.generateSecret("DESEDE");
//
//			if (key.getEncoded().length != 24)
//			{
//				Fail("DESEDE length wrong");
//			}
//
//			if (!DESedeKeySpec.isParityAdjusted(key.getEncoded(), 0))
//			{
//				Fail("DESEDE parity wrong");
//			}
//
//			key = keyAgreement.generateSecret("Blowfish");
//
//			if (key.getEncoded().length != 16)
//			{
//				Fail("Blowfish length wrong");
//			}
        }
Exemple #31
0
        public ServerAuthority(DHParameters parameters)
        {
            this.parameters = parameters;

            IAsymmetricCipherKeyPairGenerator keyGen = GeneratorUtilities.GetKeyPairGenerator("DH");
            KeyGenerationParameters           kgp    = new DHKeyGenerationParameters(new SecureRandom(), parameters);

            keyGen.Init(kgp);
            kp        = keyGen.GenerateKeyPair();
            agreement = AgreementUtilities.GetBasicAgreement("DH");
            agreement.Init(kp.Private);
        }
Exemple #32
0
        public static AsymmetricCipherKeyPair GenerateBouncyKeyPair()
        {
            // Construct a new public/private key pair (RSA 2048 bits)
            IAsymmetricCipherKeyPairGenerator KeyGen    = GeneratorUtilities.GetKeyPairGenerator("RSA");
            RsaKeyGenerationParameters        KeyParams = new RsaKeyGenerationParameters(BigInteger.ValueOf(0x10001), new SecureRandom(), 2048, 25);

            KeyGen.Init(KeyParams);

            AsymmetricCipherKeyPair KeyPair = KeyGen.GenerateKeyPair();

            return(KeyPair);
        }
Exemple #33
0
        private void createECGostRequest()
        {
            string algorithm = "GOST3411withECGOST3410";
            IAsymmetricCipherKeyPairGenerator ecGostKpg = GeneratorUtilities.GetKeyPairGenerator("ECGOST3410");

            ecGostKpg.Init(
                new ECKeyGenerationParameters(
                    CryptoProObjectIdentifiers.GostR3410x2001CryptoProA,
                    new SecureRandom()));

            //
            // set up the keys
            //
            AsymmetricCipherKeyPair pair    = ecGostKpg.GenerateKeyPair();
            AsymmetricKeyParameter  privKey = pair.Private;
            AsymmetricKeyParameter  pubKey  = pair.Public;

            Pkcs10CertificationRequest req = new Pkcs10CertificationRequest(
                algorithm, new X509Name("CN=XXX"), pubKey, null, privKey);

            if (!req.Verify())
            {
                Fail("Failed Verify check EC.");
            }

            req = new Pkcs10CertificationRequest(req.GetEncoded());
            if (!req.Verify())
            {
                Fail("Failed Verify check EC encoded.");
            }

            if (!req.SignatureAlgorithm.ObjectID.Equals(CryptoProObjectIdentifiers.GostR3411x94WithGostR3410x2001))
            {
                Fail("ECGOST oid incorrect.");
            }

            if (req.SignatureAlgorithm.Parameters != null)
            {
                Fail("ECGOST parameters incorrect.");
            }

            ISigner sig = SignerUtilities.GetSigner(algorithm);

            sig.Init(false, pubKey);

            byte[] b = req.GetCertificationRequestInfo().GetEncoded();
            sig.BlockUpdate(b, 0, b.Length);

            if (!sig.VerifySignature(req.Signature.GetBytes()))
            {
                Fail("signature not mapped correctly.");
            }
        }
Exemple #34
0
        private void Button1_Click_1(object sender, EventArgs e)
        {
            //string signature = textBox1.Text;
            //textBox4.Text = @"C:\Users\MARK\Desktop\PGP\PGPKEY\priv.asc";
            //textBox5.Text = @"C:\Users\MARK\Desktop\PGP\PGPKEY\pub.asc";

            ////RSA密鑰產生器
            //IAsymmetricCipherKeyPairGenerator kpg = GeneratorUtilities.GetKeyPairGenerator("RSA");
            ////Key 構造使用參數
            //kpg.Init(new RsaKeyGenerationParameters(
            //    BigInteger.ValueOf(0x10001), new SecureRandom(),
            //    1024, // key 的長度
            //    25));
            //AsymmetricCipherKeyPair kp = kpg.GenerateKeyPair();
            //char[] password = signature.ToCharArray(); //私鑰的密碼
            //Stream out1, out2;
            //out1 = File.Create(textBox4.Text); //私鑰放置位置
            //out2 = File.Create(textBox5.Text); //公鑰放置位置
            //ExportKeyPair(out1, out2, kp.Public, kp.Private, "MarkWu", password, true);

            string signature   = textBox1.Text;
            string keyWord     = textBox2.Text;
            string storagePath = textBox3.Text;
            string priv_Path   = storagePath + @"\" + keyWord + "_priv.gpg";
            string pub_Path    = storagePath + @"\" + keyWord + "_pub.gpg";


            //RSA密鑰產生器
            IAsymmetricCipherKeyPairGenerator kpg = GeneratorUtilities.GetKeyPairGenerator("RSA");

            //Key 構造使用參數
            kpg.Init(new RsaKeyGenerationParameters(
                         BigInteger.ValueOf(0x10001), new SecureRandom(),
                         1024, // key 的長度
                         25));

            AsymmetricCipherKeyPair kp = kpg.GenerateKeyPair();

            char[] password = signature.ToCharArray(); //私鑰的密碼
            Stream out1, out2;

            out1 = File.Create(priv_Path);                                              //私鑰放置位置
            out2 = File.Create(pub_Path);                                               //公鑰放置位置
            ExportKeyPair(out1, out2, kp.Public, kp.Private, "MarkWu", password, true); //匯出

            out1.Close();                                                               //連線中斷
            out2.Close();
            out1.Dispose();                                                             //解構值
            out2.Dispose();

            textBox4.Text = priv_Path;
            textBox5.Text = pub_Path;
        }
Exemple #35
0
		static OcspTestUtil()
		{
			rand = new SecureRandom();

//			kpg  = KeyPairGenerator.GetInstance("RSA");
//			kpg.initialize(1024, rand);
			kpg = GeneratorUtilities.GetKeyPairGenerator("RSA");
			kpg.Init(new RsaKeyGenerationParameters(
				BigInteger.ValueOf(0x10001), rand, 1024, 25));

			serialNumber = BigInteger.One;

			ecKpg = GeneratorUtilities.GetKeyPairGenerator("ECDSA");
			ecKpg.Init(new KeyGenerationParameters(rand, 192));
		}