Inheritance: KeyGenerationParameters
        public ECDiffieHellmanBc(Int32 keySize)
        {
            Org.BouncyCastle.Asn1.X9.X9ECParameters ecParams;
            switch (keySize) {
            case 256:
                ecParams = Org.BouncyCastle.Asn1.Sec.SecNamedCurves.GetByName("secp256r1");
                break;
            case 384:
                ecParams = Org.BouncyCastle.Asn1.Sec.SecNamedCurves.GetByName("secp384r1");
                break;
            case 521:
                ecParams = Org.BouncyCastle.Asn1.Sec.SecNamedCurves.GetByName("secp521r1");
                break;
            default:
                throw new ArgumentException("ECDiffieHellman key size " + keySize + " not supported");
            }
            _keySize = keySize;
            _domainParameters = new ECDomainParameters(ecParams.Curve, ecParams.G, ecParams.N, ecParams.H, ecParams.GetSeed());

            // Initialize key generation parameters with new SecureRandom
            Org.BouncyCastle.Security.SecureRandom secureRandom = new Org.BouncyCastle.Security.SecureRandom();
            ECKeyGenerationParameters keyGenParams = new ECKeyGenerationParameters(_domainParameters, secureRandom);

            // Generate key pair from domain parameters
            Org.BouncyCastle.Crypto.Generators.ECKeyPairGenerator generator = new Org.BouncyCastle.Crypto.Generators.ECKeyPairGenerator();
            generator.Init(keyGenParams);
            Org.BouncyCastle.Crypto.AsymmetricCipherKeyPair keyPair = generator.GenerateKeyPair();

            // Save the private and public key parameters
            _privateKeyParameters = (ECPrivateKeyParameters) keyPair.Private;
            _publicKeyParameters = (ECPublicKeyParameters) keyPair.Public;

            _kdf = ECDiffieHellmanKeyDerivationFunction.Hash;
            _hashAlgorithm = CngAlgorithm.Sha256;
        }
Beispiel #2
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 #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);
 }
Beispiel #6
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 #7
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)";
 }
        /// <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;
        }
        /// <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);
            }
        }
Beispiel #10
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;
		}
        public static int Main(string[] args)
        {
            var secureRandom = new SecureRandom();
            var ecParams = new ECKeyGenerationParameters(SecObjectIdentifiers.SecP256r1, secureRandom);
            var ecdsa = GeneratorUtilities.GetKeyPairGenerator("ECDSA");
            ecdsa.Init(ecParams);
            var ecdh = GeneratorUtilities.GetKeyPairGenerator("ECDH");
            ecdh.Init(ecParams);

            IAsymmetricCipherKeyPair kpEcdsa = ecdsa.GenerateKeyPair();
            IAsymmetricCipherKeyPair kpEcdh = ecdh.GenerateKeyPair();

            if (args.Length < 2)
            {
                Console.WriteLine("EcKeyRingGenerator [-a] identity passPhrase");
                return 0;
            }

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

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

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

                ExportKeyPair(out1, out2, kpEcdsa, kpEcdh, args[0], args[1].ToCharArray(), false, secureRandom);
            }
            out1.Close();
            out2.Close();
            return 0;
        }
Beispiel #12
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 #13
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 #14
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 #15
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");
            }
        }
Beispiel #16
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 #17
0
        public static SshKey CreateKey(SshVersion version,
      PublicKeyAlgorithm algorithm, string comment = "")
        {
            if (version == SshVersion.SSH1 &&
            algorithm != PublicKeyAlgorithm.SSH_RSA) {
            throw new Exception("unsupported version/algorithm combination");
              }

              switch (algorithm) {
            case PublicKeyAlgorithm.SSH_RSA:
              KeyGenerationParameters keyGenParam =
            new KeyGenerationParameters(secureRandom, 512);

              RsaKeyPairGenerator rsaKeyPairGen = new RsaKeyPairGenerator();
              rsaKeyPairGen.Init(keyGenParam);
              AsymmetricCipherKeyPair keyPair = rsaKeyPairGen.GenerateKeyPair();
              var rsaKey = new SshKey(version, keyPair);
              rsaKey.Comment = comment;
              return rsaKey;

            case PublicKeyAlgorithm.SSH_DSS:
              DsaParametersGenerator dsaParamGen = new DsaParametersGenerator();
              dsaParamGen.Init(512, 10, secureRandom);
              DsaParameters dsaParam = dsaParamGen.GenerateParameters();
              DsaKeyGenerationParameters dsaKeyGenParam =
            new DsaKeyGenerationParameters(secureRandom, dsaParam);
              DsaKeyPairGenerator dsaKeyPairGen = new DsaKeyPairGenerator();
              dsaKeyPairGen.Init(dsaKeyGenParam);
              keyPair = dsaKeyPairGen.GenerateKeyPair();
              var dsaKey = new SshKey(SshVersion.SSH2, keyPair);
              dsaKey.Comment = comment;
              return dsaKey;

            case PublicKeyAlgorithm.ECDSA_SHA2_NISTP256:
              X9ECParameters ecdsa256X9Params =
            SecNamedCurves.GetByName("secp256r1");
              ECDomainParameters ecdsa256DomainParams =
            new ECDomainParameters(ecdsa256X9Params.Curve, ecdsa256X9Params.G,
              ecdsa256X9Params.N, ecdsa256X9Params.H);
              ECKeyGenerationParameters ecdsa256GenParams =
            new ECKeyGenerationParameters(ecdsa256DomainParams, secureRandom);
              ECKeyPairGenerator ecdsa256Gen = new ECKeyPairGenerator();
              ecdsa256Gen.Init(ecdsa256GenParams);
              keyPair = ecdsa256Gen.GenerateKeyPair();
              var ecdsa256Key = new SshKey(SshVersion.SSH2, keyPair);
              ecdsa256Key.Comment = comment;
              return ecdsa256Key;

            case PublicKeyAlgorithm.ECDSA_SHA2_NISTP384:
              X9ECParameters ecdsa384X9Params =
            SecNamedCurves.GetByName("secp384r1");
              ECDomainParameters ecdsa384DomainParams =
            new ECDomainParameters(ecdsa384X9Params.Curve, ecdsa384X9Params.G,
              ecdsa384X9Params.N, ecdsa384X9Params.H);
              ECKeyGenerationParameters ecdsa384GenParams =
            new ECKeyGenerationParameters(ecdsa384DomainParams, secureRandom);
              ECKeyPairGenerator ecdsa384Gen = new ECKeyPairGenerator();
              ecdsa384Gen.Init(ecdsa384GenParams);
              keyPair = ecdsa384Gen.GenerateKeyPair();
              var ecdsa384Key = new SshKey(SshVersion.SSH2, keyPair);
              ecdsa384Key.Comment = comment;
              return ecdsa384Key;

            case PublicKeyAlgorithm.ECDSA_SHA2_NISTP521:
              X9ECParameters ecdsa521X9Params =
            SecNamedCurves.GetByName("secp521r1");
              ECDomainParameters ecdsa521DomainParams =
            new ECDomainParameters(ecdsa521X9Params.Curve, ecdsa521X9Params.G,
              ecdsa521X9Params.N, ecdsa521X9Params.H);
              ECKeyGenerationParameters ecdsa521GenParams =
            new ECKeyGenerationParameters(ecdsa521DomainParams, secureRandom);
              ECKeyPairGenerator ecdsa521Gen = new ECKeyPairGenerator();
              ecdsa521Gen.Init(ecdsa521GenParams);
              keyPair = ecdsa521Gen.GenerateKeyPair();
              var ecdsa521Key = new SshKey(SshVersion.SSH2, keyPair);
              ecdsa521Key.Comment = comment;
              return ecdsa521Key;

            case PublicKeyAlgorithm.ED25519:
              var privateKeySeed = secureRandom.GenerateSeed(Ed25519.PrivateKeySeedSizeInBytes);
              var publicKeyBytes = new byte[Ed25519.PublicKeySizeInBytes];
              var privateKeyBytes = new byte[Ed25519.ExpandedPrivateKeySizeInBytes];
              Ed25519.KeyPairFromSeed(out publicKeyBytes, out privateKeyBytes, privateKeySeed);
              var publicKey = new Ed25519PublicKeyParameter(publicKeyBytes);
              var privateKey = new Ed25519PrivateKeyParameter(privateKeyBytes);
              var ed25519Key = new SshKey(SshVersion.SSH2, publicKey, privateKey, comment);
              return ed25519Key;

            default:
              throw new Exception("unsupported algorithm");
              }
        }
        public void 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");
            }
        }
Beispiel #19
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));
        }
        /** 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());
            }
        }
 protected virtual AsymmetricCipherKeyPair GenerateECKeyPair(ECDomainParameters ecParams)
 {
     ECKeyPairGenerator keyPairGenerator = new ECKeyPairGenerator();
     ECKeyGenerationParameters keyGenerationParameters = new ECKeyGenerationParameters(ecParams,
         context.SecureRandom);
     keyPairGenerator.Init(keyGenerationParameters);
     return keyPairGenerator.GenerateKeyPair();
 }
Beispiel #22
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());
        }
        private void GenerateKeys(string curveName)
        {
            this.logger?.Debug($"ECDHE: Creating ephemeral ecc domain parameters and keys for curve {curveName}...");
            X9ECParameters ecParams = SecNamedCurves.GetByName(curveName);
            this.domainParameters = new ECDomainParameters(
                ecParams.Curve,
                ecParams.G,
                ecParams.N,
                ecParams.H,
                ecParams.GetSeed());
            var keyGenParams = new ECKeyGenerationParameters(this.domainParameters, new SecureRandom());

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

            this.privateKey = (ECPrivateKeyParameters)keyPair.Private;
            this.publicKey = (ECPublicKeyParameters)keyPair.Public;
        }
        /**
         * Test Sign and Verify with B parameters
         * see: http://www.ietf.org/internet-drafts/draft-popov-cryptopro-cpalgs-01.txt
         * gostR3410-2001-CryptoPro-B-ParamSet  P.47-48
         */
        private void ecGOST3410_BParam()
        {
            SecureRandom random = new SecureRandom();

            BigInteger mod_p = new BigInteger("57896044618658097711785492504343953926634992332820282019728792003956564823193"); //p

            FpCurve curve = new FpCurve(
                mod_p, // p
                new BigInteger("57896044618658097711785492504343953926634992332820282019728792003956564823190"), // a
                new BigInteger("28091019353058090096996979000309560759124368558014865957655842872397301267595")); // b

            ECDomainParameters parameters = new ECDomainParameters(
                curve,
                new FpPoint(curve,
                new FpFieldElement(mod_p,new BigInteger("1")), // x
                new FpFieldElement(mod_p,new BigInteger("28792665814854611296992347458380284135028636778229113005756334730996303888124"))), // y
                new BigInteger("57896044618658097711785492504343953927102133160255826820068844496087732066703")); // q

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

            pGen.Init(genParam);

            AsymmetricCipherKeyPair pair = pGen.GenerateKeyPair();

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

            ECGost3410Signer ecgost3410 = new ECGost3410Signer();

            ecgost3410.Init(true, param);

            BigInteger[] sig = ecgost3410.GenerateSignature(hashmessage);

            ecgost3410.Init(false, pair.Public);

            if (!ecgost3410.VerifySignature(hashmessage, sig[0], sig[1]))
            {
                Fail("signature fails");
            }
        }
        /**
         * Test Sign and Verify with C parameters
         * see: http://www.ietf.org/internet-drafts/draft-popov-cryptopro-cpalgs-01.txt
         * gostR3410-2001-CryptoPro-C-ParamSet  P.48
         */
        private void ecGOST3410_CParam()
        {
            SecureRandom random = new SecureRandom();

            BigInteger mod_p = new BigInteger("70390085352083305199547718019018437841079516630045180471284346843705633502619"); //p

            FpCurve curve = new FpCurve(
                mod_p, // p
                new BigInteger("70390085352083305199547718019018437841079516630045180471284346843705633502616"), // a
                new BigInteger("32858")); // b

            ECDomainParameters parameters = new ECDomainParameters(
                curve,
                new FpPoint(curve,
                new FpFieldElement(mod_p,new BigInteger("0")), // x
                new FpFieldElement(mod_p,new BigInteger("29818893917731240733471273240314769927240550812383695689146495261604565990247"))), // y
                new BigInteger("70390085352083305199547718019018437840920882647164081035322601458352298396601")); // q

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

            pGen.Init(genParam);

            AsymmetricCipherKeyPair pair = pGen.GenerateKeyPair();

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

            ECGost3410Signer ecgost3410 = new ECGost3410Signer();

            ecgost3410.Init(true, param);

            BigInteger[] sig = ecgost3410.GenerateSignature(hashmessage);

            ecgost3410.Init(false, pair.Public);

            if (!ecgost3410.VerifySignature(hashmessage, sig[0], sig[1]))
            {
                Fail("signature fails");
            }
        }
        /**
         * Test Sign and Verify with test parameters
         * see: http://www.ietf.org/internet-drafts/draft-popov-cryptopro-cpalgs-01.txt
         * gostR3410-2001-TestParamSet  P.46
         */
        private void ecGOST3410_TestParam()
        {
            SecureRandom    random = new SecureRandom();

            BigInteger mod_p = new BigInteger("57896044618658097711785492504343953926634992332820282019728792003956564821041"); //p

            FpCurve curve = new FpCurve(
                mod_p, // p
                new BigInteger("7"), // a
                new BigInteger("43308876546767276905765904595650931995942111794451039583252968842033849580414")); // b

            ECDomainParameters parameters = new ECDomainParameters(
                                   curve,
                                   new FpPoint(curve,
                                   new FpFieldElement(mod_p,new BigInteger("2")), // x
                                   new FpFieldElement(mod_p,new BigInteger("4018974056539037503335449422937059775635739389905545080690979365213431566280"))), // y
                                   new BigInteger("57896044618658097711785492504343953927082934583725450622380973592137631069619")); // q

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

            pGen.Init(genParam);

            AsymmetricCipherKeyPair  pair = pGen.GenerateKeyPair();

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

            ECGost3410Signer ecgost3410 = new ECGost3410Signer();

            ecgost3410.Init(true, param);

            //get hash message using the digest GOST3411.
            byte[] message = Encoding.ASCII.GetBytes("Message for sign");
            Gost3411Digest gost3411 = new Gost3411Digest();
            gost3411.BlockUpdate(message, 0, message.Length);
            byte[] hashmessage = new byte[gost3411.GetDigestSize()];
            gost3411.DoFinal(hashmessage, 0);

            BigInteger[] sig = ecgost3410.GenerateSignature(hashmessage);

            ecgost3410.Init(false, pair.Public);

            if (!ecgost3410.VerifySignature(hashmessage, sig[0], sig[1]))
            {
                Fail("signature fails");
            }
        }
        /**
         * Test Sign and Verify with A parameters
         * see: http://www.ietf.org/internet-drafts/draft-popov-cryptopro-cpalgs-01.txt
         * gostR3410-2001-CryptoPro-A-ParamSet  P.47
         */
        public void ecGOST3410_AParam()
        {
            SecureRandom    random = new SecureRandom();

            BigInteger mod_p = new BigInteger("115792089237316195423570985008687907853269984665640564039457584007913129639319"); //p

            FpCurve curve = new FpCurve(
                mod_p, // p
                new BigInteger("115792089237316195423570985008687907853269984665640564039457584007913129639316"), // a
                new BigInteger("166")); // b

            ECDomainParameters parameters = new ECDomainParameters(
                curve,
                new FpPoint(curve,
                new FpFieldElement(mod_p, new BigInteger("1")), // x
                new FpFieldElement(mod_p, new BigInteger("64033881142927202683649881450433473985931760268884941288852745803908878638612"))), // y
                new BigInteger("115792089237316195423570985008687907853073762908499243225378155805079068850323")); // q

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

            pGen.Init(genParam);

            AsymmetricCipherKeyPair  pair = pGen.GenerateKeyPair();

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

            ECGost3410Signer ecgost3410 = new ECGost3410Signer();

            ecgost3410.Init(true, param);

            BigInteger[] sig = ecgost3410.GenerateSignature(hashmessage);

            ecgost3410.Init(false, pair.Public);

            if (!ecgost3410.VerifySignature(hashmessage, sig[0], sig[1]))
            {
                Fail("signature fails");
            }
        }
Beispiel #28
0
        public static X509Certificate2 GenerateSelfSignedCertEcdsa()
        {
            var randomGenerator = new CryptoApiRandomGenerator();
            var random = new SecureRandom(randomGenerator);
            var certificateGenerator = new X509V3CertificateGenerator();
            var serialNumber =
            BigIntegers.CreateRandomInRange(
                BigInteger.One, BigInteger.ValueOf(Int64.MaxValue), random);
            certificateGenerator.SetSerialNumber(serialNumber);
            const string signatureAlgorithm = "SHA256withECDSA";
            certificateGenerator.SetSignatureAlgorithm(signatureAlgorithm);
            var subjectDN = new X509Name("CN=simpletorrent");
            var issuerDN = subjectDN;
            certificateGenerator.SetIssuerDN(issuerDN);
            certificateGenerator.SetSubjectDN(subjectDN);
            var notBefore = DateTime.UtcNow.Date.AddHours(-24);
            var notAfter = notBefore.AddYears(1000);
            certificateGenerator.SetNotBefore(notBefore);
            certificateGenerator.SetNotAfter(notAfter);
            ECKeyGenerationParameters genParam
                = new ECKeyGenerationParameters(X962NamedCurves.GetOid("prime256v1"), random);

            var keyPairGenerator = new ECKeyPairGenerator();
            keyPairGenerator.Init(genParam);
            var subjectKeyPair = keyPairGenerator.GenerateKeyPair();

            certificateGenerator.SetPublicKey(subjectKeyPair.Public);

            var issuerKeyPair = subjectKeyPair;
            var certificate = certificateGenerator.Generate(issuerKeyPair.Private, random);

            var store = new Pkcs12Store();
            string friendlyName = certificate.SubjectDN.ToString();
            var certificateEntry = new X509CertificateEntry(certificate);
            store.SetCertificateEntry(friendlyName, certificateEntry);

            store.SetKeyEntry(friendlyName, new AsymmetricKeyEntry(subjectKeyPair.Private), new[] { certificateEntry });

            string password = "******";

            var stream = new MemoryStream();
            store.Save(stream, password.ToCharArray(), random);

            //mono bug #1660 fix -> convert to definite-length encoding
            byte[] pfx = Pkcs12Utilities.ConvertToDefiniteLength(stream.ToArray(), password.ToCharArray());

            var convertedCertificate =
                new X509Certificate2(
                    pfx, password,
                    X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable);

            return convertedCertificate;
        }
        public void GenerateEccKeyTest()
        {
            const string identity = "GenerateEccKeyTest Identity";

            var secureRandom = new SecureRandom();
            var keyParamSet = SecObjectIdentifiers.SecP256r1;
            var ecParams = new ECKeyGenerationParameters(keyParamSet, secureRandom);

            var now = DateTime.UtcNow;
            var masterKey = GenerateKeyPair(PublicKeyAlgorithmTag.Ecdsa, ecParams, now);
            var subKey = GenerateKeyPair(PublicKeyAlgorithmTag.Ecdh, ecParams, now);

            var keyRingGenerator = new PgpKeyRingGenerator(
                PgpSignature.PositiveCertification,
                masterKey,
                identity,
                SymmetricKeyAlgorithmTag.Aes256,
                HashAlgorithmTag.Sha256,
                "".ToCharArray(),
                true,
                GenerateSignatureSubpackets(identity),
                null,
                secureRandom);
            keyRingGenerator.AddSubKey(subKey);

            var secretKeyRing = keyRingGenerator.GenerateSecretKeyRing();
            CheckEccKey(secretKeyRing);
        }