Init() public method

public Init ( KeyGenerationParameters parameters ) : void
parameters Org.BouncyCastle.Crypto.KeyGenerationParameters
return void
Beispiel #1
0
        private void button1_Click(object sender, EventArgs e)
        {
            ECKeyGenerationParameters keyGenerationParameters = new ECKeyGenerationParameters(parameters, random);

            ECKeyPairGenerator keygenerator = new ECKeyPairGenerator("ECGOST3410");
            keygenerator.Init(keyGenerationParameters);
            AsymmetricCipherKeyPair pair = keygenerator.GenerateKeyPair();

            ECPrivateKeyParameters validatorPrivate = (ECPrivateKeyParameters)pair.Private;
            ECPublicKeyParameters validatorPublic = (ECPublicKeyParameters)pair.Public;

            /*validatorPrivate = new ECPrivateKeyParameters(
                "ECGOST3410",
                new BigInteger("55441196065363246126355624130324183196576709222340016572108097750006097525544"), // d
                parameters);

            validatorPublic = new ECPublicKeyParameters(
                "ECGOST3410",
                new FpPoint(curve,
                new FpFieldElement(mod_p, new BigInteger("57520216126176808443631405023338071176630104906313632182896741342206604859403")), // x
                new FpFieldElement(mod_p, new BigInteger("17614944419213781543809391949654080031942662045363639260709847859438286763994"))), // y
                parameters);
            */

            tbValPrivate.Text = validatorPrivate.D.ToString(16);
            tbValPublicX.Text = validatorPublic.Q.X.ToBigInteger().ToString(16);
            tbValPublicY.Text = validatorPublic.Q.Y.ToBigInteger().ToString(16);
        }
Beispiel #2
0
		public AsymmetricCipherKeyPair GenerateEphemeralKey(TEllipticCurve curve)
		{
			ECDomainParameters ecParams = EllipticCurveFactory.GetEllipticCurveParameters(curve);					 
			ECKeyPairGenerator keyPairGenerator = new ECKeyPairGenerator();
			SecureRandom random = new SecureRandom();
			keyPairGenerator.Init(new ECKeyGenerationParameters(ecParams, random));
			return keyPairGenerator.GenerateKeyPair();
		}
Beispiel #3
0
		public AsymmetricCipherKeyPair generateKeypair() {
			var eckeygen = new ECKeyGenerationParameters (spec, securerng);
			var keygen = new ECKeyPairGenerator ();
			keygen.Init (eckeygen);

			var kp = keygen.GenerateKeyPair ();
			return kp;
		}
 private static AsymmetricCipherKeyPair GenerateKeyPairEcc()
 {
     var oid = X962NamedCurves.GetOid("prime256v1");
     var generator = new ECKeyPairGenerator();
     var genParam = new ECKeyGenerationParameters(oid, RandomUtil.SecureRandomBc);
     generator.Init(genParam);
     return generator.GenerateKeyPair();
 }
 public ECKeyPair GenerateKeyPair(byte[] applicationSha256, byte[] challengeSha256)
 {
     var conf = new ECKeyGenerationParameters(SecObjectIdentifiers.SecP256r1, new SecureRandom());
     var keyGen = new ECKeyPairGenerator("ECDSA");
     keyGen.Init(conf);
     var pair = keyGen.GenerateKeyPair();
     
     return new ECKeyPair((ECPublicKeyParameters) pair.Public, (ECPrivateKeyParameters) pair.Private);
 }
		public void GenerateEphemeralKey()
		{
			EllipticCurveParameters = EllipticCurveFactory.GetEllipticCurveParameters(Curve);
			ECKeyPairGenerator keyPairGenerator = new ECKeyPairGenerator();
			SecureRandom random = new SecureRandom();
			keyPairGenerator.Init(new ECKeyGenerationParameters(EllipticCurveParameters, random));
			AsymmetricCipherKeyPair keys = keyPairGenerator.GenerateKeyPair();
			PrivateKey = (ECPrivateKeyParameters)keys.Private;
			PublicKey = (ECPublicKeyParameters)keys.Public;
		}
Beispiel #7
0
		/// <summary>
		/// Generates an entirely new keypair.
		/// </summary>
		public ECKey() {
			var generator = new ECKeyPairGenerator();
			var keygenParams = new ECKeyGenerationParameters(_ecParams, _secureRandom);
			generator.Init(keygenParams);
			var keypair = generator.GenerateKeyPair();
			var privParams = (ECPrivateKeyParameters)keypair.Private;
			var pubParams = (ECPublicKeyParameters)keypair.Public;
			_priv = privParams.D;
			// The public key is an encoded point on the elliptic curve. It has no meaning independent of the curve.
			_pub = pubParams.Q.GetEncoded();
		}
Beispiel #8
0
 public Account()
 {
     var namedCurve = NistNamedCurves.GetByName("P-256");
     var ecdomp = new ECDomainParameters(namedCurve.Curve, namedCurve.G, namedCurve.N);
     var srnd = new SecureRandom();
     var eckeygenparams = new ECKeyGenerationParameters(ecdomp, srnd);
     var g = new ECKeyPairGenerator("ECDSA");
     g.Init(eckeygenparams);
     keyPair = g.GenerateKeyPair();
     address = generateAddress(keyPair.Public);
     this.Label = "(no label)";
 }
        public void InitForEncryption(ISecureRandom random, ECDHPublicKeyParameters publicKey, byte[] fingerPrint, out ECDHPublicKeyParameters ephemeralPublicKey)
        {
            var genParams = publicKey.CreateKeyGenerationParameters(random, publicKey.HashAlgorithm, publicKey.SymmetricKeyAlgorithm);
            var generator = new ECKeyPairGenerator("ECDH");
            generator.Init(genParams);
            var ephemeralKeyPair = generator.GenerateKeyPair();

            _fingerPrint = (byte[])fingerPrint.Clone();
            _privateKey = (ECPrivateKeyParameters)ephemeralKeyPair.Private;
            _publicKey = publicKey;
            _forEncryption = true;
            ephemeralPublicKey = (ECDHPublicKeyParameters)ephemeralKeyPair.Public;
        }
        // Section 7.2.5 ECSP-NR, pg 34
        /**
         * generate a signature for the given message using the key we were
         * initialised with.  Generally, the order of the curve should be at
         * least as long as the hash of the message of interest, and with
         * ECNR it *must* be at least as long.
         *
         * @param digest  the digest to be signed.
         * @exception DataLengthException if the digest is longer than the key allows
         */
        public IBigInteger[] GenerateSignature(
			byte[] message)
        {
            if (!this._forSigning)
            {
                // not properly initilaized... deal with it
                throw new InvalidOperationException("not initialised for signing");
            }

            IBigInteger n = ((ECPrivateKeyParameters)this._key).Parameters.N;
            int nBitLength = n.BitLength;

            IBigInteger e = new BigInteger(1, message);
            int eBitLength = e.BitLength;

            ECPrivateKeyParameters  privKey = (ECPrivateKeyParameters)_key;

            if (eBitLength > nBitLength)
            {
                throw new DataLengthException("input too large for ECNR key.");
            }

            IBigInteger r = null;
            IBigInteger s = null;

            IAsymmetricCipherKeyPair tempPair;
            do // generate r
            {
                // generate another, but very temporary, key pair using
                // the same EC parameters
                ECKeyPairGenerator keyGen = new ECKeyPairGenerator();

                keyGen.Init(new ECKeyGenerationParameters(privKey.Parameters, _random));

                tempPair = keyGen.GenerateKeyPair();

                //    IBigInteger Vx = tempPair.getPublic().getW().getAffineX();
                ECPublicKeyParameters V = (ECPublicKeyParameters) tempPair.Public; // get temp's public key
                IBigInteger Vx = V.Q.X.ToBigInteger(); // get the point's x coordinate

                r = Vx.Add(e).Mod(n);
            }
            while (r.SignValue == 0);

            // generate s
            IBigInteger x = privKey.D;                // private key value
            IBigInteger u = ((ECPrivateKeyParameters)tempPair.Private).D; // temp's private key value
            s = u.Subtract(r.Multiply(x)).Mod(n);

            return new IBigInteger[] { r, s };
        }
        /// <summary>
        /// Initialize new CKeyPair instance with random secret.
        /// </summary>
        public CKeyPair(bool Compressed = true)
        {
            var genParams = new ECKeyGenerationParameters(domain, new SecureRandom());
            var generator = new ECKeyPairGenerator("ECDSA");
            generator.Init(genParams);
            var ecKeyPair = generator.GenerateKeyPair();

            _Private = (ECPrivateKeyParameters)ecKeyPair.Private;
            _Public = (ECPublicKeyParameters)ecKeyPair.Public;

            if (Compressed)
            {
                _Public = Compress(_Public);
            }
        }
        /// <summary>
        /// This generates an elliptic curve key pair. Uses BouncyCastle library for generation.
        /// Hijacked by the BES Random Generator.
        /// </summary>
        /// <param name="keyGen"></param>
        /// <param name="keySize"></param>
        /// <returns></returns>
        public static AsymmetricCipherKeyPair GenerateKeyPair(IBasylKeyGenerator keyGen, string curveName)
        {
            var ecGenerator = new ECKeyPairGenerator("ECDH");

            var ecp = GetCurveFromName(curveName);

            ECDomainParameters ecSpec = new ECDomainParameters(ecp.Curve, ecp.G, ecp.N, ecp.H, ecp.GetSeed());
            ECKeyGenerationParameters ecgp = new ECKeyGenerationParameters(ecSpec, new BasylSecureRandom(keyGen));

            ecGenerator.Init(ecgp);

            AsymmetricCipherKeyPair keys = ecGenerator.GenerateKeyPair();

            return keys;
        }
Beispiel #13
0
		public static ECKeyPair Generate (X9ECParameters curve, bool compressed = true)
		{
			ECKeyPairGenerator generator = new ECKeyPairGenerator ();
			ECDomainParameters newDomain = new ECDomainParameters(curve.Curve, curve.G, curve.N);
			ECKeyGenerationParameters keygenParams = new ECKeyGenerationParameters (newDomain, secureRandom);
			generator.Init (keygenParams);
			var keyPair = generator.GenerateKeyPair ();
			ECPrivateKeyParameters privParams = (ECPrivateKeyParameters) keyPair.Private;
			ECPublicKeyParameters pubParams = (ECPublicKeyParameters) keyPair.Public;
			ECKeyPair k = new ECKeyPair ();
			k.Domain = newDomain;
			k.Curve = curve;
			k.priv = privParams.D;
			k.pub = pubParams.Q.GetEncoded (compressed);
			return k;
		}
Beispiel #14
0
        public Tuple<ECPrivateKeyParameters, ECPublicKeyParameters> CreateKeyPair()
        {
            var curve = SecNamedCurves.GetByName("secp256k1");
            var domainParameters = new ECDomainParameters(curve.Curve, curve.G, curve.N, curve.H, curve.GetSeed());

            var generator = new ECKeyPairGenerator();
            generator.Init(new ECKeyGenerationParameters(domainParameters, new SecureRandom()));
            var keyPair = new MethodTimer(false).Time("GenerateKeyPair", () => generator.GenerateKeyPair());

            var privateKey = (ECPrivateKeyParameters)keyPair.Private;
            var publicKey = (ECPublicKeyParameters)keyPair.Public;

            //Debug.WriteLine("Private:  {0}".Format2(privateKey.D.ToHexNumberStringUnsigned()));
            //Debug.WriteLine("Public X: {0}".Format2(publicKey.Q.X.ToBigInteger().ToHexNumberStringUnsigned()));
            //Debug.WriteLine("Public Y: {0}".Format2(publicKey.Q.Y.ToBigInteger().ToHexNumberStringUnsigned()));

            return Tuple.Create(privateKey, publicKey);
        }
Beispiel #15
0
        public static string GeneratePrivateKey()
        {
            ECKeyPairGenerator gen = new ECKeyPairGenerator();
            var secureRandom = new SecureRandom(new byte[] { 1, 2, 3, 4, 6 });

            var ps = Org.BouncyCastle.Asn1.Sec.SecNamedCurves.GetByName("secp256k1");
            var ecParams = new ECDomainParameters(ps.Curve, ps.G, ps.N, ps.H);
            var keyGenParam = new ECKeyGenerationParameters(ecParams, secureRandom);
            gen.Init(keyGenParam);

            AsymmetricCipherKeyPair kp = gen.GenerateKeyPair();

            ECPrivateKeyParameters priv = (ECPrivateKeyParameters)kp.Private;

            byte[] hexpriv = priv.D.ToByteArrayUnsigned();
            var privateKey = ByteArrayToString(hexpriv);

            return privateKey;
        }
Beispiel #16
0
        /// <summary>
        /// Create ECDSA and generates new key pair
        /// </summary>
        /// <param name="type">0 or 1 (1 faster)</param>
        /// <param name="forSign">if created for signing, otherwise for verifying</param>
        public ECDSAWrapper(int type, bool forSign)
        {
            try
            {
                this.initCurveandParams(type);

                SecureRandom random = new SecureRandom();
                ECKeyGenerationParameters genParam = new ECKeyGenerationParameters(this.parameters, random);
                ECKeyPairGenerator pGen = new ECKeyPairGenerator();
                pGen.Init(genParam);
                this.pair = pGen.GenerateKeyPair();

                if (forSign)
                    this.ecdsa.Init(true, new ParametersWithRandom(this.pair.Private, random));
                else
                    this.ecdsa.Init(false, this.pair.Public);
            }
            catch (Exception ex)
            {
                throw new Exception("Error while creating ECDSA with new key pair", ex);
            }
        }
Beispiel #17
0
        public override void PerformTest()
        {
            StaticTest();

            FpCurve curve = new FpCurve(
                new BigInteger("6277101735386680763835789423207666416083908700390324961279"), // q
                new BigInteger("fffffffffffffffffffffffffffffffefffffffffffffffc", 16), // a
                new BigInteger("64210519e59c80e70fa7e9ab72243049feb8deecc146b9b1", 16)); // b

            ECDomainParameters parameters = new ECDomainParameters(
                curve,
                curve.DecodePoint(Hex.Decode("03188da80eb03090f67cbf20eb43a18800f4ff0afd82ff1012")), // G
                new BigInteger("6277101735386680763835789423176059013767194773182842284081")); // n

            ECKeyPairGenerator eGen = new ECKeyPairGenerator();
            KeyGenerationParameters gParam = new ECKeyGenerationParameters(parameters, new SecureRandom());

            eGen.Init(gParam);

            AsymmetricCipherKeyPair p1 = eGen.GenerateKeyPair();
            AsymmetricCipherKeyPair p2 = eGen.GenerateKeyPair();

            DoTest(p1, p2);
        }
Beispiel #18
0
        public static void FullSignatureTest(byte[] hash)
        {
            X9ECParameters ecParams = Org.BouncyCastle.Asn1.Sec.SecNamedCurves.GetByName("secp256k1");
            ECDomainParameters domainParameters = new ECDomainParameters(ecParams.Curve,
                ecParams.G, ecParams.N, ecParams.H,
                ecParams.GetSeed());
            ECKeyGenerationParameters keyGenParams =
                new ECKeyGenerationParameters(domainParameters, new SecureRandom());

            AsymmetricCipherKeyPair keyPair;
            ECKeyPairGenerator generator = new ECKeyPairGenerator();
            generator.Init(keyGenParams);
            keyPair = generator.GenerateKeyPair();

            ECPrivateKeyParameters privateKey = (ECPrivateKeyParameters) keyPair.Private;
            ECPublicKeyParameters publicKey = (ECPublicKeyParameters) keyPair.Public;

            Console.WriteLine("Generated private key: " + ToHex(privateKey.D.ToByteArrayUnsigned()));
            Console.WriteLine("Generated public key: " + ToHex(publicKey.Q.GetEncoded()));

            ECDsaSigner signer = new ECDsaSigner();
            signer.Init(true, privateKey);
            BigInteger[] sig = signer.GenerateSignature(hash);

            int recid = -1;
            for (int rec=0; rec<4; rec++) {
                try
                {
                    ECPoint Q = ECDSA_SIG_recover_key_GFp(sig, hash, rec, true);
                    if (ToHex(publicKey.Q.GetEncoded()).Equals(ToHex(Q.GetEncoded())))
                    {
                        recid = rec;
                        break;
                    }
                }
                catch (Exception)
                {
                    continue;
                }
            }
            if (recid < 0) throw new Exception("Did not find proper recid");

            byte[] fullSigBytes = new byte[65];
            fullSigBytes[0] = (byte) (27+recid);
            Buffer.BlockCopy(sig[0].ToByteArrayUnsigned(), 0, fullSigBytes, 1, 32);
            Buffer.BlockCopy(sig[1].ToByteArrayUnsigned(), 0, fullSigBytes, 33, 32);

            Console.WriteLine("Generated full signature: " + Convert.ToBase64String(fullSigBytes));

            byte[] sigBytes = new byte[64];
            Buffer.BlockCopy(sig[0].ToByteArrayUnsigned(), 0, sigBytes, 0, 32);
            Buffer.BlockCopy(sig[1].ToByteArrayUnsigned(), 0, sigBytes, 32, 32);

            ECPoint genQ = ECDSA_SIG_recover_key_GFp(sig, hash, recid, false);
            Console.WriteLine("Generated signature verifies: " + VerifySignature(genQ.GetEncoded(), hash, sigBytes));
        }
Beispiel #19
0
 public static ECKey GenerateKey()
 {
     //mixing bouncy implementation
     var gen = new ECKeyPairGenerator();
     var keyGenParam = new KeyGenerationParameters(SecureRandom, 256);
     gen.Init(keyGenParam);
     var keyPair =  gen.GenerateKeyPair();
     var privateBytes = ((ECPrivateKeyParameters)keyPair.Private).D.ToByteArray();
     return new ECKey(privateBytes, true);
 }
		public void Backdoor()
		{
			var random = new SecureRandom();
			var curve = CustomNamedCurves.GetByName("secp521r1");
			var gen = new ECKeyPairGenerator("ECDSA");
			var G = curve.G;
			var N = curve.N;
			var paramz = new ECDomainParameters(curve.Curve, G, N);
			gen.Init(new ECKeyGenerationParameters(paramz, random));

			var kCalc = new RandomDsaKCalculator(); // kCalc generates random values [1, N-1]
			kCalc.Init(N, random);

			var attackersKeyPair = gen.GenerateKeyPair();

			var v = ((ECPrivateKeyParameters)attackersKeyPair.Private).D; //attacker's private
			var V = G.Multiply(v); //attackers public

			var usersKeyPair = gen.GenerateKeyPair(); //user's keypair
			var D = ((ECPrivateKeyParameters)usersKeyPair.Private).D; //user's private
			var Q = ((ECPublicKeyParameters)usersKeyPair.Public).Q;//user's public


			const string message1 = "First message to sign";
			var m1 = new BigInteger(1, Hash(Encoding.UTF8.GetBytes(message1))); // hash of m1

			//Generate signature 1
			var k1 = kCalc.NextK(); // k1 is true random
			var signaturePoint1 = G.Multiply(k1).Normalize();

			//(r1, s1) - signature 1
			var r1 = signaturePoint1.AffineXCoord.ToBigInteger().Mod(N);
			var s1 = k1.ModInverse(N).Multiply(m1.Add(D.Multiply(r1)));


			//verify signature 1
			var w = s1.ModInverse(N);
			var u1 = m1.Multiply(w).Mod(N);
			var u2 = r1.Multiply(w).Mod(N);
			var verifyPoint1 = ECAlgorithms.SumOfTwoMultiplies(G, u1, Q, u2).Normalize();

			var valid1 = verifyPoint1.AffineXCoord.ToBigInteger().Mod(N).Equals(r1);


			//Generate signature 2
			const string message2 = "Second message to sign";
			var m2 = new BigInteger(1, Hash(Encoding.UTF8.GetBytes(message2))); // hash of m2

			//here we generate a,b,h,e < N using seed = hash(m2)
			kCalc.Init(N, new SecureRandom(new SeededGenerator(Hash(Encoding.UTF8.GetBytes(message2)))));

			var a = kCalc.NextK();
			var b = kCalc.NextK();
			var h = kCalc.NextK();
			var e = kCalc.NextK();

			//u,j - true random
			var u = (random.Next() % 2) == 1 ? BigInteger.One : BigInteger.Zero;
			var j = (random.Next() % 2) == 1 ? BigInteger.One : BigInteger.Zero;

			//compute hidden field element
			var Z = G.Multiply(k1).Multiply(a)
				.Add(V.Multiply(k1).Multiply(b))
				.Add(G.Multiply(h).Multiply(j))
				.Add(V.Multiply(e).Multiply(u))
				.Normalize();

			var zX = Z.AffineXCoord.ToBigInteger().ToByteArray();

			var hash = Hash(zX);
			var k2 = new BigInteger(1, hash);
			var signaturePoint2 = G.Multiply(k2).Normalize();

			//(r2, s2) = signature 2
			var r2 = signaturePoint2.AffineXCoord.ToBigInteger().Mod(N);
			var s2 = k2.ModInverse(N).Multiply(m2.Add(D.Multiply(r2)));

			//verify signature 2

			w = s2.ModInverse(N);
			u1 = m2.Multiply(w).Mod(N);
			u2 = r2.Multiply(w).Mod(N);
			var verifyPoint2 = ECAlgorithms.SumOfTwoMultiplies(G, u1, Q, u2).Normalize();

			var valid2 = verifyPoint2.AffineXCoord.ToBigInteger().Mod(N).Equals(r2);

			if (valid1 && valid2)
			{
				//compute user's private key
				var d = ExtractUsersPrivateKey(G, N, message1, message2, r1, s1, r2, s2, v, V, Q);
				Console.WriteLine("Ecdsa private key restored: {0}", d.Equals(D));
			}
			else
			{
				Console.WriteLine("Something's wrong");
			}
		}
 public static AsymmetricCipherKeyPair GenerateECKeyPair(SecureRandom random, ECDomainParameters ecParams)
 {
     ECKeyPairGenerator keyPairGenerator = new ECKeyPairGenerator();
     keyPairGenerator.Init(new ECKeyGenerationParameters(ecParams, random));
     return keyPairGenerator.GenerateKeyPair();
 }
 protected virtual AsymmetricCipherKeyPair GenerateECKeyPair(ECDomainParameters ecParams)
 {
     ECKeyPairGenerator keyPairGenerator = new ECKeyPairGenerator();
     ECKeyGenerationParameters keyGenerationParameters = new ECKeyGenerationParameters(ecParams,
         context.SecureRandom);
     keyPairGenerator.Init(keyGenerationParameters);
     return keyPairGenerator.GenerateKeyPair();
 }
Beispiel #23
0
 public static EncryptionResult EncryptMessage(byte[] userKey, byte[] userSecret, byte[] data, ushort padding = 0, bool randomisePadding = false)
 {
     var Random = new SecureRandom();
     var Salt = new byte[16];
     Random.NextBytes(Salt);
     var Curve = ECNamedCurveTable.GetByName("prime256v1");
     var Spec = new ECDomainParameters(Curve.Curve, Curve.G, Curve.N, Curve.H, Curve.GetSeed());
     var Generator = new ECKeyPairGenerator();
     Generator.Init(new ECKeyGenerationParameters(Spec, new SecureRandom()));
     var KeyPair = Generator.GenerateKeyPair();
     var AgreementGenerator = new ECDHBasicAgreement();
     AgreementGenerator.Init(KeyPair.Private);
     var IKM =
         AgreementGenerator.CalculateAgreement(new ECPublicKeyParameters(Spec.Curve.DecodePoint(userKey), Spec));
     var PRK = GenerateHKDF(userSecret, IKM.ToByteArrayUnsigned(),
         Encoding.UTF8.GetBytes("Content-Encoding: auth\0"), 32);
     var PublicKey = ((ECPublicKeyParameters)KeyPair.Public).Q.GetEncoded(false);
     var CEK = GenerateHKDF(Salt, PRK, CreateInfoChunk("aesgcm", userKey, PublicKey), 16);
     var Nonce = GenerateHKDF(Salt, PRK, CreateInfoChunk("nonce", userKey, PublicKey), 12);
     if (randomisePadding && (padding > 0)) padding = Convert.ToUInt16(Math.Abs(Random.NextInt()) % (padding + 1));
     var Input = new byte[padding + 2 + data.Length];
     Buffer.BlockCopy(ConvertInt(padding), 0, Input, 0, 2);
     Buffer.BlockCopy(data, 0, Input, padding + 2, data.Length);
     var Cipher = CipherUtilities.GetCipher("AES/GCM/NoPadding");
     Cipher.Init(true, new AeadParameters(new KeyParameter(CEK), 128, Nonce));
     var Message = new byte[Cipher.GetOutputSize(Input.Length)];
     Cipher.DoFinal(Input, 0, Input.Length, Message, 0);
     return new EncryptionResult { Salt = Salt, Payload = Message, PublicKey = PublicKey };
 }
Beispiel #24
0
        public void TestECBasicAgreementTest()
        {
            SecureRandom random = new SecureRandom();

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

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

            ECKeyPairGenerator pGen = new ECKeyPairGenerator();
            ECKeyGenerationParameters genParam = new ECKeyGenerationParameters(parameters, random);

            pGen.Init(genParam);

            AsymmetricCipherKeyPair p1 = pGen.GenerateKeyPair();
            AsymmetricCipherKeyPair p2 = pGen.GenerateKeyPair();

            //
            // two way
            //
            IBasicAgreement e1 = new ECDHBasicAgreement();
            IBasicAgreement e2 = new ECDHBasicAgreement();

            e1.Init(p1.Private);
            e2.Init(p2.Private);

            BigInteger   k1 = e1.CalculateAgreement(p2.Public);
            BigInteger   k2 = e2.CalculateAgreement(p1.Public);

            if (!k1.Equals(k2))
            {
                Fail("calculated agreement test failed");
            }

            //
            // two way
            //
            e1 = new ECDHCBasicAgreement();
            e2 = new ECDHCBasicAgreement();

            e1.Init(p1.Private);
            e2.Init(p2.Private);

            k1 = e1.CalculateAgreement(p2.Public);
            k2 = e2.CalculateAgreement(p1.Public);

            if (!k1.Equals(k2))
            {
                Fail("calculated agreement test failed");
            }
        }
Beispiel #25
0
        public void TestECMqvRandom()
        {
            SecureRandom random = new SecureRandom();

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

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

            ECKeyPairGenerator pGen = new ECKeyPairGenerator();

            pGen.Init(new ECKeyGenerationParameters(parameters, random));

            // Pre-established key pairs
            AsymmetricCipherKeyPair U1 = pGen.GenerateKeyPair();
            AsymmetricCipherKeyPair V1 = pGen.GenerateKeyPair();

            // Ephemeral key pairs
            AsymmetricCipherKeyPair U2 = pGen.GenerateKeyPair();
            AsymmetricCipherKeyPair V2 = pGen.GenerateKeyPair();

            BigInteger x = calculateAgreement(U1, U2, V1, V2);

            if (x == null)
            {
                Fail("MQV Test Vector (random) agreement failed");
            }
        }
Beispiel #26
0
        public void TestECDsaKeyGenTest()
        {
            SecureRandom random = new SecureRandom();

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

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

            ECKeyPairGenerator pGen = new ECKeyPairGenerator();
            ECKeyGenerationParameters genParam = new ECKeyGenerationParameters(
                parameters,
                random);

            pGen.Init(genParam);

            AsymmetricCipherKeyPair pair = pGen.GenerateKeyPair();

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

            ECDsaSigner ecdsa = new ECDsaSigner();

            ecdsa.Init(true, param);

            byte[] message = new BigInteger("968236873715988614170569073515315707566766479517").ToByteArray();
            BigInteger[] sig = ecdsa.GenerateSignature(message);

            ecdsa.Init(false, pair.Public);

            if (!ecdsa.VerifySignature(message, sig[0], sig[1]))
            {
                Fail("signature fails");
            }
        }
        public void TestECDsaP256Sha256WithGeneratedKey()
        {
            var secureRandom = new SecureRandom();
            X9ECParameters p = NistNamedCurves.GetByName("P-256");
            var parameters = new ECDomainParameters(p.Curve, p.G, p.N, p.H);
            var ecParams = new ECKeyGenerationParameters(parameters, secureRandom);
            var ecGen = new ECKeyPairGenerator("ECDSA");
            ecGen.Init(ecParams);
            var pairKey = ecGen.GenerateKeyPair();
            var priKey = pairKey.Private as ECPrivateKeyParameters;

            byte[] m = Hex.Decode("1BD4ED430B0F384B4E8D458EFF1A8A553286D7AC21CB2F6806172EF5F94A06AD");

            var dsa = new ECDsaSigner();

            dsa.Init(true, new ParametersWithRandom(priKey, secureRandom));

            IBigInteger[] sig = dsa.GenerateSignature(m);

            // Verify the signature
            var pubKey = pairKey.Public as ECPublicKeyParameters;

            dsa.Init(false, pubKey);
            if (!dsa.VerifySignature(m, sig[0], sig[1]))
            {
                Fail("signature fails");
            }
        }
        /** Generates an entirely new keypair. */
        public CMicroCashKeyPair(bool bGenerate)
        {
            if(bGenerate)
            {
                ECKeyPairGenerator gen = new ECKeyPairGenerator();
                var secureRandom = new SecureRandom();
                var ps = Org.BouncyCastle.Asn1.Sec.SecNamedCurves.GetByName("secp256k1");
                var ecParams = new ECDomainParameters(ps.Curve, ps.G, ps.N, ps.H);
                var keyGenParam = new ECKeyGenerationParameters(ecParams, secureRandom);
                gen.Init(keyGenParam);

                AsymmetricCipherKeyPair kp = gen.GenerateKeyPair();

                ECPrivateKeyParameters priv = (ECPrivateKeyParameters)kp.Private;
                ECPublicKeyParameters pub = (ECPublicKeyParameters)kp.Public;

                byte[] hexpriv = priv.D.ToByteArrayUnsigned();
                //byte[] hexPub = pub
                Org.BouncyCastle.Math.BigInteger Db = new Org.BouncyCastle.Math.BigInteger(1,hexpriv);
                ECPoint dd = ps.G.Multiply(Db);

                byte[] pubaddr = new byte[65];
                byte[] Y = dd.Y.ToBigInteger().ToByteArray();
                Array.Copy(Y, 0, pubaddr, 64 - Y.Length + 1, Y.Length);
                byte[] X = dd.X.ToBigInteger().ToByteArray();
                Array.Copy(X, 0, pubaddr, 32 - X.Length + 1, X.Length);
                pubaddr[0] = 4;

                m_Priv = new BigInteger(hexpriv);
                m_Pub = pubaddr;
                m_Address = ConvertPubKeyToAddress(m_Pub);
                m_PubKeyString = bytesToHexString(m_Pub);
                m_PrivKeyString = bytesToHexString(m_Priv.ToByteArray());
            }
        }
        public void TestMethod1()
        {
            // this snippet can be easily used in any normal c# project as well by simply removing the .Dump() methods
            // and saving the output into a variable / file of your choice.
            // you'll need to add BouncyCastle.Crypto nuget to use this.
            // tested on 1.8.0-beta4

            AsymmetricCipherKeyPair pair;
            Pkcs10CertificationRequest csr;

            var ecMode = false;
            var values = new Dictionary<DerObjectIdentifier, string> {
    {X509Name.CN, ""}, //domain name
    {X509Name.OU, "Domain Control Validated"},
    {X509Name.O, ""}, //Organisation's Legal name
    {X509Name.L, "London"},
    {X509Name.ST, "England"},
    {X509Name.C, "GB"},
};

            var subjectAlternateNames = new GeneralName[] { };

            var extensions = new Dictionary<DerObjectIdentifier, X509Extension>()
{
    {X509Extensions.BasicConstraints, new X509Extension(true, new DerOctetString(new BasicConstraints(false)))},
    {X509Extensions.KeyUsage, new X509Extension(true, new DerOctetString(new KeyUsage(KeyUsage.DigitalSignature | KeyUsage.KeyEncipherment | KeyUsage.DataEncipherment | KeyUsage.NonRepudiation)))},
    {X509Extensions.ExtendedKeyUsage, new X509Extension(false, new DerOctetString(new ExtendedKeyUsage(KeyPurposeID.IdKPServerAuth)))},
};

            if (values[X509Name.CN].StartsWith("www.")) values[X509Name.CN] = values[X509Name.CN].Substring(4);

            if (!values[X509Name.CN].StartsWith("*.") && subjectAlternateNames.Length == 0)
                subjectAlternateNames = new GeneralName[] { new GeneralName(GeneralName.DnsName, $"www.{values[X509Name.CN]}") };

            if (subjectAlternateNames.Length > 0) extensions.Add(X509Extensions.SubjectAlternativeName, new X509Extension(false, new DerOctetString(new GeneralNames(subjectAlternateNames))));

            var subject = new X509Name(values.Keys.Reverse().ToList(), values);

            if (ecMode)
            {
                var gen = new ECKeyPairGenerator();
                var ecp = Org.BouncyCastle.Asn1.Sec.SecNamedCurves.GetByName("secp384r1");
                gen.Init(new ECKeyGenerationParameters(new ECDomainParameters(ecp.Curve, ecp.G, ecp.N, ecp.H, ecp.GetSeed()), new SecureRandom()));

                pair = gen.GenerateKeyPair();

                extensions.Add(X509Extensions.SubjectKeyIdentifier, new X509Extension(false, new DerOctetString(new SubjectKeyIdentifierStructure(pair.Public))));
                csr = new Pkcs10CertificationRequest("SHA256withECDSA", subject, pair.Public, new DerSet(new AttributePkcs(PkcsObjectIdentifiers.Pkcs9AtExtensionRequest, new DerSet(new X509Extensions(extensions)))), pair.Private);

            }
            else
            {
                var gen = new RsaKeyPairGenerator();
                gen.Init(new KeyGenerationParameters(new SecureRandom(), 2048));

                pair = gen.GenerateKeyPair();
                extensions.Add(X509Extensions.SubjectKeyIdentifier, new X509Extension(false, new DerOctetString(new SubjectKeyIdentifierStructure(pair.Public))));
                csr = new Pkcs10CertificationRequest("SHA256withRSA", subject, pair.Public, new DerSet(new AttributePkcs(PkcsObjectIdentifiers.Pkcs9AtExtensionRequest, new DerSet(new X509Extensions(extensions)))), pair.Private);
            }

            //Convert BouncyCastle csr to .PEM file.
            var csrPem = new StringBuilder();
            var csrPemWriter = new PemWriter(new StringWriter(csrPem));
            csrPemWriter.WriteObject(csr);
            csrPemWriter.Writer.Flush();

            Console.WriteLine(csrPem.ToString());

            var privateKeyPem = new StringBuilder();
            var privateKeyPemWriter = new PemWriter(new StringWriter(privateKeyPem));
            privateKeyPemWriter.WriteObject(pair.Private);
            csrPemWriter.Writer.Flush();

            //privateKeyPem.ToString().Dump("Private Key");
        }
Beispiel #30
0
        public static Ecdsa Generate()
        {
            X9ECParameters ecParams = Org.BouncyCastle.Asn1.Sec.SecNamedCurves.GetByName("secp256k1");
            ECDomainParameters domainParameters = new ECDomainParameters(ecParams.Curve,
                ecParams.G, ecParams.N, ecParams.H,
                ecParams.GetSeed());
            ECKeyGenerationParameters keyGenParams =
                new ECKeyGenerationParameters(domainParameters, new SecureRandom());

            AsymmetricCipherKeyPair keyPair;
            ECKeyPairGenerator generator = new ECKeyPairGenerator();
            generator.Init(keyGenParams);
            keyPair = generator.GenerateKeyPair();

            ECPrivateKeyParameters privateKey = (ECPrivateKeyParameters) keyPair.Private;
            ECPublicKeyParameters publicKey = (ECPublicKeyParameters) keyPair.Public;

            return new Ecdsa(publicKey.Q.GetEncoded(), privateKey.D.ToByteArrayUnsigned());
        }