private static void Sign(UnsignedTransaction unsignedTransaction, string privateKey, bool isHex, bool addPubKey,
                                 bool forceCompressed = false)
        {
            bool compressed = false;
            var  bytes      = isHex ? privateKey.FromHexString() : GetBytesFromBase58Key(privateKey);

            if (bytes.Length == 33 && bytes[32] == 1)
            {
                compressed = true;
                bytes      = bytes.Take(32).ToArray();
            }

            var privKeyB       = new BigInteger(1, bytes);
            var parms          = SecNamedCurves.GetByName("secp256k1");
            var curve          = new ECDomainParameters(parms.Curve, parms.G, parms.N, parms.H);
            var halfCurveOrder = parms.N.ShiftRight(1);

            var point = curve.G.Multiply(privKeyB);

            if (compressed || forceCompressed)
            {
                point = new FpPoint(curve.Curve, point.X, point.Y, true);
            }

            var publicKey = point.GetEncoded();
            var signer    = new ECDsaSigner();
            var privKey   = new ECPrivateKeyParameters(privKeyB, curve);

            signer.Init(true, privKey);

            foreach (string toSign in unsignedTransaction.ToSign)
            {
                if (addPubKey)
                {
                    unsignedTransaction.PubKeys.Add(publicKey.ToHexString());
                }

                var components = signer.GenerateSignature(toSign.FromHexString());
                var r          = components[0];
                var s          = components[1];

                if (s.CompareTo(halfCurveOrder) > 0)
                {
                    s = curve.N.Subtract(s);
                }

                using (var ms = new MemoryStream())
                    using (var asn = new Asn1OutputStream(ms)) {
                        var seq = new DerSequenceGenerator(asn);
                        seq.AddObject(new DerInteger(r));
                        seq.AddObject(new DerInteger(s));

                        seq.Close();

                        string signedString = ms.ToArray().ToHexString();

                        unsignedTransaction.Signatures.Add(signedString);
                    }
            }
        }
Beispiel #2
0
        public static bool ValidateSignature(Hash data, ECSignature signature, ECKeyPair keyPair)
        {
#if NATIVE_ECDSA
            using (var ecdsa = ECDsa.Create(keyPair))
            {
                return(ecdsa.VerifyHash(data, signature.Signature));
            }
#else
            var derSignature = new DerSequence(
                new DerInteger(new Org.BouncyCastle.Math.BigInteger(1, signature.Signature.Take(32).ToArray())),
                new DerInteger(new Org.BouncyCastle.Math.BigInteger(1, signature.Signature.Skip(32).ToArray())))
                               .GetDerEncoded();

            ISigner            signer                   = SignerUtilities.GetSigner("NONEwithECDSA");
            X9ECParameters     curve                    = Org.BouncyCastle.Asn1.Sec.SecNamedCurves.GetByName(keyPair.CurveType.ToString().ToLower());
            ECDomainParameters domain                   = new ECDomainParameters(curve.Curve, curve.G, curve.N, curve.H);
            Org.BouncyCastle.Math.BigInteger bn         = new Org.BouncyCastle.Math.BigInteger(keyPair.D);
            ECPrivateKeyParameters           parameters = new ECPrivateKeyParameters(bn, domain);
            FpCurve c         = (FpCurve)curve.Curve;
            var     publicKey = new FpPoint(c, new FpFieldElement(c.Q, new Org.BouncyCastle.Math.BigInteger(+1, keyPair.PublicKey.X)),
                                            new FpFieldElement(c.Q, new Org.BouncyCastle.Math.BigInteger(+1, keyPair.PublicKey.Y)));
            ECPublicKeyParameters publicKeyParameters = new ECPublicKeyParameters(publicKey, domain);
            signer.Init(false, publicKeyParameters);
            signer.BlockUpdate(data, 0, data.Length);
            bool ok = signer.VerifySignature(derSignature);
            return(ok);
#endif
        }
Beispiel #3
0
        private static void test()
        {
            Console.Out.WriteLine("Start!");

            // namjesti postavke prvo
            Setup setup = new Setup();

            // tajni ključ
            FpPoint d_id = setup.Exctract("*****@*****.**");

            Encrypt e = new Encrypt("*****@*****.**", setup.GetP(), setup.GetPpub(), setup.p, setup.E, setup.k);

            string poruka = "moram porati posluku";
            Cypher c      = e.GetCypher(poruka);

            Console.Out.WriteLine("poruka: \"" + poruka + "\"");
            Console.Out.WriteLine("sifrat: \"" + c.V + "\"");
            Console.Out.WriteLine("tocka: \"(" + c.U.X.ToBigInteger().ToString(16) + " ,\n\t" + c.U.Y.ToBigInteger().ToString(16) + "\"");

            Decrypt d   = new Decrypt(d_id, setup.p, setup.k);
            string  msg = d.GetMessage(c);

            Console.Out.WriteLine("decoded: \"" + msg + "\"");

            Console.ReadKey();
        }
    public static bool VerifySign(string _dataToSign, string _signPack, string _pubKeyX, string _pubKeyY)
    {
        SM2 sm2 = SM2.Instance;

        sm2.cipher_sm = new SM2.Cipher();

        string signPack1 = _signPack.Substring(0, 64);
        string signPack2 = _signPack.Substring(64, 64);

        BigInteger ecc_gx = new BigInteger(_pubKeyX, 16);
        BigInteger ecc_gy = new BigInteger(_pubKeyY, 16);

        ECFieldElement ecc_gx_fieldElement = sm2.ecc_curve.FromBigInteger(ecc_gx);                                 //选定椭圆曲线上基点 G 的 x 坐标
        ECFieldElement ecc_gy_fieldElement = sm2.ecc_curve.FromBigInteger(ecc_gy);                                 //选定椭圆曲线上基点 G 的 y 坐标
        ECPoint        ecc_point_g         = new FpPoint(sm2.ecc_curve, ecc_gx_fieldElement, ecc_gy_fieldElement); //生成基点 G

        SM2.SM2Result result = new SM2.SM2Result();

        BigInteger gp_br = new BigInteger(signPack1, 16);
        BigInteger gp_bs = new BigInteger(signPack2, 16);

        result.r = gp_br;
        result.s = gp_bs;

        sm2.Sm2Verify(HexStringToBytes(_dataToSign), ecc_point_g, gp_br, gp_bs, result);

        return(result.R.Equals(result.r));
    }
Beispiel #5
0
        /**
         * Test encoding with and without point compression.
         *
         * @param p
         *            The point to be encoded and decoded.
         */
        private void implTestEncoding(ECPoint p)
        {
            // Not Point Compression
            ECPoint unCompP;

            // Point compression
            ECPoint compP;

            if (p is FpPoint)
            {
                unCompP = new FpPoint(p.Curve, p.X, p.Y, false);
                compP   = new FpPoint(p.Curve, p.X, p.Y, true);
            }
            else
            {
                unCompP = new F2mPoint(p.Curve, p.X, p.Y, false);
                compP   = new F2mPoint(p.Curve, p.X, p.Y, true);
            }

            byte[]  unCompBarr = unCompP.GetEncoded();
            ECPoint decUnComp  = p.Curve.DecodePoint(unCompBarr);

            Assert.AreEqual(p, decUnComp, "Error decoding uncompressed point");

            byte[]  compBarr = compP.GetEncoded();
            ECPoint decComp  = p.Curve.DecodePoint(compBarr);

            Assert.AreEqual(p, decComp, "Error decoding compressed point");
        }
Beispiel #6
0
        public static ECPublicKeyParameters PublicKeyFromBytes(byte[] key)
        {
            /*
             * Convert public key into a public key object
             * The public key comprises two co-ordinates X followed by Y, both 32 bytes
             */

            byte[] public_key_x = new byte[32];
            byte[] public_key_y = new byte[32];

            Array.Copy(key, 0, public_key_x, 0, public_key_x.Length);
            Array.Copy(key, 32, public_key_y, 0, public_key_y.Length);

            BigInteger bi_x = new BigInteger(1, public_key_x);
            BigInteger bi_y = new BigInteger(1, public_key_y);

            // the key needs to relate to a specific curve
            X9ECParameters ecP    = X962NamedCurves.GetByName("prime256v1");
            var            ecSpec = new ECDomainParameters(ecP.Curve, ecP.G, ecP.N, ecP.H, ecP.GetSeed());

            FpCurve c = (FpCurve)ecP.Curve;

            var fe_x = new FpFieldElement(c.Q, bi_x);
            var fe_y = new FpFieldElement(c.Q, bi_y);

            // point q represents the x,y co-ordinate of the public key
            ECPoint q = new FpPoint(c, fe_x, fe_y);

            return(new ECPublicKeyParameters("ECDSA", q, ecSpec));
        }
        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);
            /*****************************************************************************/
        }
Beispiel #8
0
 public Encrypt(string id, FpPoint tocka, FpPoint Ppublic, BigInteger prost, FpCurve curve, BigInteger stp)
 {
     ID   = id;
     P    = tocka;
     Ppub = Ppublic;
     prim = prost;
     E    = curve;
     k    = stp;
 }
Beispiel #9
0
        private static void decode(Cypher cypher, string id, Setup setup)
        {
            // tajni ključ
            FpPoint d_id = setup.Exctract(id, true);

            Decrypt d   = new Decrypt(d_id, setup.p, setup.k);
            string  msg = d.GetMessage(cypher);

            Console.Out.WriteLine("decoded: \"" + msg + "\"");
        }
Beispiel #10
0
        private static void CheckIsOnCurve(FpCurve curve, FpPoint point)
        {
            ECFieldElement lhs = point.Y.Square();
            ECFieldElement rhs = point.X.Multiply(point.X.Square().Add(curve.A)).Add(curve.B);

            if (!lhs.Equals(rhs))
            {
                throw new CryptographicException("point not on curve");
            }
        }
        public ECPublicKeyParameters ParsePublicKey(String X, String Y)
        {
            var c = (FpCurve)ECSpec.Curve;
            var q = new FpPoint(ECP.Curve,
                                c.FromBigInteger(new BigInteger(X, 16)),
                                c.FromBigInteger(new BigInteger(Y, 16)));

            return(q.IsValid()
                       ? new ECPublicKeyParameters("ECDH", q, SecObjectIdentifiers.SecP192r1)
                       : null);
        }
Beispiel #12
0
 /**
  * Creates the points on the curve with literature values.
  */
 internal static void createPoints()
 {
     for (int i = 0; i < pointSource.Length / 2; i++)
     {
         FpFieldElement x = new FpFieldElement(q, new BigInteger(
                                                   pointSource[2 * i].ToString()));
         FpFieldElement y = new FpFieldElement(q, new BigInteger(
                                                   pointSource[2 * i + 1].ToString()));
         p[i] = new FpPoint(curve, x, y);
     }
 }
Beispiel #13
0
        private void button3_Click(object sender, EventArgs e)
        {
            FpPoint    G = (FpPoint)parameters.G;
            BigInteger k = (new BigInteger(random.Next(1, parameters.N.BitCount - 1), random)).Add(BigInteger.One);

            tbk.Text = k.ToString(16);
            FpPoint C = (FpPoint)G.Multiply(k);

            tbCX.Text = C.X.ToBigInteger().ToString(16);
            tbCY.Text = C.Y.ToBigInteger().ToString(16);
        }
Beispiel #14
0
 public FpCurve(BigInteger q, BigInteger a, BigInteger b, BigInteger order, BigInteger cofactor)
     : base(q)
 {
     m_q        = q;
     m_r        = FpFieldElement.CalculateResidue(q);
     m_infinity = new FpPoint(this, null, null);
     m_a        = FromBigInteger(a);
     m_b        = FromBigInteger(b);
     m_order    = order;
     m_cofactor = cofactor;
     m_coord    = 4;
 }
Beispiel #15
0
        public static ECPublicKeyParameters ConvertPublicToParameters(string publicKey)
        {
            Org.BouncyCastle.Asn1.X9.X9ECParameters ecP = Org.BouncyCastle.Asn1.Sec.SecNamedCurves.GetByName("secp256k1");
            ECDomainParameters ecSpec = new ECDomainParameters(ecP.Curve, ecP.G, ecP.N, ecP.H, ecP.GetSeed());
            var            pubBytes   = ValidateAndGetHexPublicKey(publicKey).Skip(1).ToArray();
            var            c          = (FpCurve)ecP.Curve;
            ECFieldElement x          = c.FromBigInteger(new BigInteger(1, pubBytes.Take(32).ToArray()));
            ECFieldElement y          = c.FromBigInteger(new BigInteger(1, pubBytes.Skip(32).ToArray()));
            ECPoint        dd         = new FpPoint(c, x, y);

            return(new ECPublicKeyParameters(dd, ecSpec));
        }
Beispiel #16
0
 protected FpCurve(BigInteger q, BigInteger r, ECFieldElement a, ECFieldElement b, BigInteger order, BigInteger cofactor)
     : base(q)
 {
     m_q        = q;
     m_r        = r;
     m_infinity = new FpPoint(this, null, null);
     m_a        = a;
     m_b        = b;
     m_order    = order;
     m_cofactor = cofactor;
     m_coord    = 4;
 }
Beispiel #17
0
        public FpCurve(BigInteger q, BigInteger a, BigInteger b, BigInteger order, BigInteger cofactor)
            : base(q)
        {
            this.m_q        = q;
            this.m_r        = FpFieldElement.CalculateResidue(q);
            this.m_infinity = new FpPoint(this, null, null, false);

            this.m_a        = FromBigInteger(a);
            this.m_b        = FromBigInteger(b);
            this.m_order    = order;
            this.m_cofactor = cofactor;
            this.m_coord    = FP_DEFAULT_COORDS;
        }
Beispiel #18
0
        internal static BigInteger Pair(FpPoint Q, FpPoint P, BigInteger m, BigInteger p)
        {
            // TODO: napravi jebeno uparivanje!!!! - nešto zeza

            BigInteger pq = Miller(P, Q, m, p);
            BigInteger qp = Miller(Q, P, m, p);

            int parity = m.Mod(new BigInteger("2", 10)).IntValue;

            BigInteger rez = new BigInteger(Math.Pow(-1, parity).ToString(), 10).Multiply(pq.Divide(qp)).Mod(p);

            return(rez);
        }
Beispiel #19
0
        protected FpCurve(BigInteger q, BigInteger r, ECFieldElement a, ECFieldElement b, BigInteger order, BigInteger cofactor)
            : base(q)
        {
            this.m_q        = q;
            this.m_r        = r;
            this.m_infinity = new FpPoint(this, null, null, false);

            this.m_a        = a;
            this.m_b        = b;
            this.m_order    = order;
            this.m_cofactor = cofactor;
            this.m_coord    = FP_DEFAULT_COORDS;
        }
Beispiel #20
0
        public static string GenerateSecp256k1PublicKey(string privateKey, bool useCompression)
        {
            var        Ecc          = SecNamedCurves.GetByName("secp256k1");
            var        DomainParams = new ECDomainParameters(Ecc.Curve, Ecc.G, Ecc.N, Ecc.H);
            var        bytes        = Hex.Hex2Bytes(privateKey);
            BigInteger d            = new BigInteger(bytes);
            ECPoint    q            = DomainParams.G.Multiply(d);

            q = q.Normalize();
            var     publicParams = new ECPublicKeyParameters(q, DomainParams);
            FpPoint fp           = new FpPoint(Ecc.Curve, q.AffineXCoord, q.AffineYCoord);

            return(Hex.Bytes2Hex(fp.GetEncoded(useCompression)));
        }
Beispiel #21
0
        private ExtendedKey GenerateKey(uint index)
        {
            Thrower.Condition <AddressException>((index & HardendIndex) != 0 && !this.Master.HasPrivateKey, "A public key can't derivate an hardened child");

            byte[] extended;
            byte[] pub = this.Master.PublicKey.Bytes;
            if ((index & HardendIndex) == 0)
            {
                var sequenceBytes = BitHelper.GetBytes(index, false);
                extended = pub.ToArray().Concat(sequenceBytes).ToArray();
            }
            else
            {
                var priv          = this.Master.PrivateKey.Bytes;
                var sequenceBytes = BitHelper.GetBytes(index, false);
                extended = (new byte[] { 0 }).Concat(priv.ToArray()).Concat(sequenceBytes).ToArray();
            }

            var leftRight = CryptoUtil.ComputeHmac512(this.ChainCode, extended);
            var leftKey   = leftRight.Take(32).ToArray();
            var rightKey  = leftRight.Skip(32).ToArray();

            BigInteger bigIntegerLeft = new BigInteger(1, leftKey);

            Thrower.Condition <AddressException>(bigIntegerLeft.CompareTo(EcKey.EcParams.N) >= 0, "This is rather unlikely, but it did just happen");

            if (this.Master.HasPrivateKey)
            {
                BigInteger key = bigIntegerLeft.Add(new BigInteger(1, this.Master.PrivateKey.Bytes)).Mod(EcKey.EcParams.N);
                Thrower.Condition <AddressException>(key.Equals(BigInteger.Zero), "This is rather unlikely, but it did just happen");

                ////  fix the private key in case it needs padding
                var keyBytes = new EcKey(key).GetPrivKeyBytes();

                return(new ExtendedKey(new BitcoinPrivateKey(keyBytes), rightKey, (byte)(this.Depth + 1), this.GenerateFingerPrint(), index));
            }
            else
            {
                var qdecoded = EcKey.EcParams.Curve.DecodePoint(this.Master.PublicKey.Bytes);
                var key      = new ECPublicKeyParameters("EC", qdecoded, EcKey.EcParams);

                var qkey = EcKey.EcParams.G.Multiply(bigIntegerLeft).Add(key.Q);
                Thrower.Condition <AddressException>(qkey.IsInfinity, "This is rather unlikely, but it did just happen");

                var point = new FpPoint(EcKey.EcParams.Curve, qkey.Normalize().XCoord, qkey.Normalize().YCoord, true);

                return(new ExtendedKey(new BitcoinPublicKey(point.GetEncoded()), rightKey, (byte)(this.Depth + 1), this.GenerateFingerPrint(), index));
            }
        }
Beispiel #22
0
        private void button5_Click(object sender, EventArgs e)
        {
            FpPoint    G       = (FpPoint)parameters.G;
            FpPoint    Q       = new FpPoint(curve, new FpFieldElement(mod_p, TextBoxToBigInteger16(tbValPublicX)), new FpFieldElement(mod_p, TextBoxToBigInteger16(tbValPublicY)));
            FpPoint    C       = new FpPoint(curve, new FpFieldElement(mod_p, TextBoxToBigInteger16(tbCX)), new FpFieldElement(mod_p, TextBoxToBigInteger16(tbCY)));
            BigInteger mu      = TextBoxToBigInteger16(tbVoterMu);
            BigInteger epsilon = TextBoxToBigInteger16(tbVoterEpsilon);
            BigInteger delta   = TextBoxToBigInteger16(tbVoterDelta);
            BigInteger tau     = TextBoxToBigInteger16(tbVoterTau);
            BigInteger q       = parameters.N;

            FpPoint Cs = (FpPoint)G.Multiply(epsilon).Add(Q.Multiply(mu)).Add(C.Multiply(delta.ModInverse(q)));

            tbCsX.Text = Cs.X.ToBigInteger().ToString(16);
            tbCsY.Text = Cs.Y.ToBigInteger().ToString(16);
        }
Beispiel #23
0
        public void TestPointCreationConsistency()
        {
            try
            {
                FpPoint bad = new FpPoint(Fp.curve, new FpFieldElement(
                                              Fp.q, new BigInteger("12")), null);
                Assert.Fail();
            }
            catch (ArgumentException)
            {
                // Expected
            }

            try
            {
                FpPoint bad = new FpPoint(Fp.curve, null,
                                          new FpFieldElement(Fp.q, new BigInteger("12")));
                Assert.Fail();
            }
            catch (ArgumentException)
            {
                // Expected
            }

            try
            {
                F2mPoint bad = new F2mPoint(F2m.curve, new F2mFieldElement(
                                                F2m.m, F2m.k1, new BigInteger("1011")), null);
                Assert.Fail();
            }
            catch (ArgumentException)
            {
                // Expected
            }

            try
            {
                F2mPoint bad = new F2mPoint(F2m.curve, null,
                                            new F2mFieldElement(F2m.m, F2m.k1,
                                                                new BigInteger("1011")));
                Assert.Fail();
            }
            catch (ArgumentException)
            {
                // Expected
            }
        }
        public ECPublicKeyParameters ParsePublicKey(String PublicKey,
                                                    PublicKeyFormats PublicKeyFormat = PublicKeyFormats.DER)
        {
            switch (PublicKeyFormat)
            {
            case PublicKeyFormats.DER:
                return(new ECPublicKeyParameters("ECDSA", ECP.Curve.DecodePoint(PublicKey.HexStringToByteArray()), ECSpec));

            case PublicKeyFormats.plain:
                var c   = (FpCurve)ECSpec.Curve;
                var x   = c.FromBigInteger(new BigInteger(PublicKey.Substring(0, 48), 16));
                var y   = c.FromBigInteger(new BigInteger(PublicKey.Substring(48), 16));
                var q   = new FpPoint(ECP.Curve, x, y);
                var isv = q.IsValid();
                return(new ECPublicKeyParameters("ECDH", q, SecObjectIdentifiers.SecP192r1));
            }

            return(null);
        }
Beispiel #25
0
        public PubKey Derivate(byte[] cc, uint nChild, out byte[] ccChild)
        {
            byte[] lr = null;
            var    l  = new byte[32];
            var    r  = new byte[32];

            if (nChild >> 31 == 0)
            {
                var pubKey = ToBytes();
                lr = Hashes.BIP32Hash(cc, nChild, pubKey[0], pubKey.Skip(1).ToArray());
            }
            else
            {
                throw new InvalidOperationException("A public key can't derivate an hardened child");
            }

            Array.Copy(lr, l, 32);
            Array.Copy(lr, 32, r, 0, 32);
            ccChild = r;


            var N          = ECKey.CURVE.N;
            var parse256LL = new BigInteger(1, l);

            if (parse256LL.CompareTo(N) >= 0)
            {
                throw new InvalidOperationException(
                          "You won a prize ! this should happen very rarely. Take a screenshot, and roll the dice again.");
            }

            var q = ECKey.CURVE.G.Multiply(parse256LL).Add(this.ECKey.GetPublicKeyParameters().Q);

            if (q.IsInfinity)
            {
                throw new InvalidOperationException(
                          "You won the big prize ! this would happen only 1 in 2^127. Take a screenshot, and roll the dice again.");
            }

            q = q.Normalize();
            var p = new FpPoint(ECKey.CURVE.Curve, q.XCoord, q.YCoord, true);

            return(new PubKey(p.GetEncoded()));
        }
Beispiel #26
0
        /// <summary>
        /// Initializes the algorithm from public key.
        /// </summary>
        /// <remarks>
        /// byte[] X
        /// byte[] Y
        /// </remarks>
        public void FromPublicKey(byte[] publicKey)
        {
            if (publicKey == null)
            {
                throw new ArgumentNullException("publicKey");
            }

            if (publicKey.Length == 0)
            {
                throw new InvalidOperationException("Invalid EC key.");
            }

            if (publicKey[0] != 4)
            {
                throw new InvalidOperationException("EC point compression not supported.");
            }

            if ((publicKey.Length & 1) != 1)
            {
                throw new InvalidOperationException("Unsupported EC key.");
            }

            int keySize = publicKey.Length / 2;

            if ((BitLength + 7) / 8 != keySize)
            {
                throw new InvalidOperationException("Unexpected EC key bit length.");
            }

            byte[] X = new byte[keySize];
            byte[] Y = new byte[keySize];
            Array.Copy(publicKey, 1, X, 0, keySize);
            Array.Copy(publicKey, 1 + keySize, Y, 0, keySize);

            var            curve = _info.Parameters.Curve;
            ECFieldElement x     = curve.FromBigInteger(new BigInteger(1, X));
            ECFieldElement y     = curve.FromBigInteger(new BigInteger(1, Y));
            ECPoint        q2    = new FpPoint(curve, x, y);

            PublicKey  = new ECPublicKeyParameters(_info.AlgorithmName, q2, _info.Parameters);
            PrivateKey = null;
        }
Beispiel #27
0
        private void button3_Click(object sender, EventArgs e)  //генерация K - G etc.
        {
            FpPoint    G = (FpPoint)parameters.G;
            BigInteger k = (new BigInteger(random.Next(1, parameters.N.BitCount - 1), random)).Add(BigInteger.One);

            tbk.Text = k.ToString(16);
            FpPoint C = (FpPoint)G.Multiply(k);

            tbCX.Text = C.X.ToBigInteger().ToString(16);
            tbCY.Text = C.Y.ToBigInteger().ToString(16);

            BigInteger mu      = (new BigInteger(random.Next(1, parameters.N.BitCount - 1), random)).Add(BigInteger.One);
            BigInteger epsilon = (new BigInteger(random.Next(1, parameters.N.BitCount - 1), random)).Add(BigInteger.One);
            BigInteger delta   = (new BigInteger(random.Next(1, parameters.N.BitCount - 1), random)).Add(BigInteger.One);
            BigInteger tau     = (new BigInteger(random.Next(1, parameters.N.BitCount - 1), random)).Add(BigInteger.One);

            tbVoterMu.Text      = mu.ToString(16);
            tbVoterEpsilon.Text = epsilon.ToString(16);
            tbVoterDelta.Text   = delta.ToString(16);
            tbVoterTau.Text     = tau.ToString(16);
        }
Beispiel #28
0
        public FpPoint Exctract(string ID, bool decrypt = false)
        {
            if (decrypt)
            {
                string sStr = File.ReadAllText("mk");
                s = int.Parse(sStr);
            }

            //  y^2 = x^3 + 117050x^2 + x
            BigInteger x = GeneralFunctions.H1hash(ID, p);
            BigInteger y = x.Pow(3).Add(x.Pow(2).Multiply(new BigInteger("117050", 10))).Add(x).Pow(2).ModInverse(p);

            FpFieldElement x_Qid = new FpFieldElement(q, x);
            FpFieldElement y_Qid = new FpFieldElement(q, y);
            FpPoint        Qid   = new FpPoint(E, x_Qid, y_Qid);

            FpPoint d_id = (FpPoint)Qid.Multiply(new BigInteger(s.ToString(), 10));

            // privatni ključ
            return(d_id);
        }
        public static BigInteger CalculateSharedKey(BigInteger BIx, BigInteger BIy, ECPrivateKeyParameters privateKey)
        {
            IBasicAgreement aKeyAgree = AgreementUtilities.GetBasicAgreement("ECDH");

            aKeyAgree.Init(privateKey);

            X9ECParameters     ecP    = NistNamedCurves.GetByName("P-521");
            ECDomainParameters ecSpec = new ECDomainParameters(ecP.Curve, ecP.G, ecP.N, ecP.H, ecP.GetSeed());

            FpCurve c = (FpCurve)ecSpec.Curve;

            ECFieldElement x = new FpFieldElement(c.Q, BIx);
            ECFieldElement y = new FpFieldElement(c.Q, BIy);
            ECPoint        q = new FpPoint(ecP.Curve, x, y);

            ECPublicKeyParameters publicKey = new ECPublicKeyParameters("ECDH", q, SecObjectIdentifiers.SecP521r1);

            BigInteger k1 = aKeyAgree.CalculateAgreement(publicKey);

            return(k1);
        }
Beispiel #30
0
        /// <summary>
        /// millerov agoritam
        /// </summary>
        /// <param name="a">točka</param>
        /// <param name="b">točka</param>
        /// <param name="m">red grupe</param>
        /// <param name="p">red polja, prim</param>
        /// <returns></returns>
        private static BigInteger Miller(FpPoint P, FpPoint Q, BigInteger m, BigInteger prim)
        {
            // Millerov algoritam

            string mBin = m.ToString(2);

            BigInteger t1 = new BigInteger("1", 10);
            BigInteger t2 = new BigInteger("1", 10);
            FpPoint    V  = P;

            for (int i = 0; i < m.BitLength; i++)
            {
                V  = (FpPoint)V.Twice();
                t1 = t1.ModPow(new BigInteger("2", 10), prim).Multiply(MLF(V, V, Q));
                if (mBin[i] == '1')
                {
                    t1 = t1.Multiply(MLF(V, P, Q));
                    V  = (FpPoint)V.Add(P);
                }
            }
            return(t1);
        }