/// <summary>
 /// Creates elliptic curve domain parameters based on the
 /// specified values. </summary>
 /// <param name="curve"> the elliptic curve which this parameter
 /// defines. </param>
 /// <param name="g"> the generator which is also known as the base point. </param>
 /// <param name="n"> the order of the generator {@code g}. </param>
 /// <param name="h"> the cofactor. </param>
 /// <exception cref="NullPointerException"> if {@code curve},
 /// {@code g}, or {@code n} is null. </exception>
 /// <exception cref="IllegalArgumentException"> if {@code n}
 /// or {@code h} is not positive. </exception>
 public ECParameterSpec(EllipticCurve curve, ECPoint g, System.Numerics.BigInteger n, int h)
 {
     if (curve == null)
     {
         throw new NullPointerException("curve is null");
     }
     if (g == null)
     {
         throw new NullPointerException("g is null");
     }
     if (n == null)
     {
         throw new NullPointerException("n is null");
     }
     if (n.signum() != 1)
     {
         throw new IllegalArgumentException("n is not positive");
     }
     if (h <= 0)
     {
         throw new IllegalArgumentException("h is not positive");
     }
     this.Curve_Renamed = curve;
     this.g             = g;
     this.n             = n;
     this.h             = h;
 }
Beispiel #2
0
        public MainPage()
        {
            InitializeComponent();
            menuPage = menu_page;

            Detail.BackgroundColor = (Color)Application.Current.Resources["PageWrapperColor"];
            MasterBehavior         = MasterBehavior.Popover;
            using (var con = DependencyService.Get <IDatabase>().GetConnection(ConnectionType.Login))
            {
                if (con.Table <User>().FirstOrDefault(each => each.LoggedIn) is User loggedUser)
                {
                    EllipticCurve elliptic = new EllipticCurve(false);
                    Task.Run(() => elliptic.KeyExchange(loggedUser.Username)).Wait();
                    if (elliptic.IsSucceeded)
                    {
                        Utility.User         = loggedUser;
                        Utility.SharedSecret = elliptic.SharedSecret;
                        var homePageKey = (int)MenuItemType.Home;
                        if (!MenuPages.ContainsKey(homePageKey))
                        {
                            MenuPages.Add(homePageKey, new NavigationPage(new HomePage()));
                        }
                        Detail           = MenuPages[homePageKey];
                        IsGestureEnabled = true;
                    }
                }
                else
                {
                    IsGestureEnabled = false;
                }
            }
            var staticClassInitiation = Utility.BaseURL;
        }
Beispiel #3
0
        public void InitialiseCurve()
        {
            BigInt p     = new BigInt("bffffffffffffffffffffffffffcffff3", 16);
            Fp     field = new Fp(p);

            curve = new EllipticCurve(field, BigInt.ZERO, BigInt.ONE);
        }
Beispiel #4
0
        public static Point HashToPoint(byte[] toHash, EllipticCurve ec, BigInt cofactor)
        {
            Point P = HashToPoint(toHash, ec);

            P = ec.Multiply(P, cofactor);
            return(P);
        }
Beispiel #5
0
        public void IsOnCurve_PointOnCurve_True()
        {
            EllipticCurve ECC = new EllipticCurve(1, 9, pField: 97, groupOrder: 90);
            Point         P   = new Point(19, 0);

            Assert.IsTrue(ECC.IsPointOnCurve(P));
        }
Beispiel #6
0
        public void AddPoints_SamePointOnCurve_InfResult()
        {
            EllipticCurve ECC = new EllipticCurve(1, 9, pField: 97, groupOrder: 90);
            Point         P   = new Point(19, 0);

            Assert.IsNull(ECC.AddPoints(P, P));
        }
Beispiel #7
0
        /// <summary>
        /// 使用私钥对消息进行签名
        /// </summary>
        /// <param name="privateKey"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        unsafe public static Signature Sign(ReadOnlySpan <byte> privateKey, ReadOnlySpan <byte> message)
        {
            if (privateKey.Length != 32)
            {
                throw new InvalidPrivateKeyException("私钥长度必须是32字节");
            }
            if (message.Length != 32)
            {
                throw new InvalidMessageException("消息长度必须是32字节");
            }

            var         dA             = new U256N(privateKey);
            var         msg            = new U256N(message);
            Span <byte> tempPrivateKey = stackalloc byte[32];

            CreatePrivateKey(tempPrivateKey);
            var   k = new U256N(tempPrivateKey);
            var   p = (Point)EllipticCurve.MulG(k);
            U256N R = p.X.Value;
            U256N S = (msg + dA * R) / k;

            if (p.Y.Value.v0 % 2 != 0)
            {
                S = -S;
            }
            return(new Signature(R, S));
        }
        public void VerifyCert(StringBuilder sb, BackgroundWorker bw, Certificate cert)
        {
            BigInteger[]  args  = null;
            ECPoint       point = ECPoint.POINT_INFINITY;
            ECPoint       P     = ECPoint.POINT_INFINITY;
            EllipticCurve curve = null;

            while ((args = cert.Read()) != null)
            {
                if (bw.CancellationPending)
                {
                    return;
                }
                curve = new EllipticCurve(args[0], args[1], args[2], args[3]);
                sb.AppendFormat("N = {0}\n", args[2].ToString());
                sb.AppendFormat("a = {0}", args[0].ToString());
                sb.AppendLine();
                sb.AppendFormat("b = {0}", args[1].ToString());
                sb.AppendLine();
                sb.AppendFormat("m = {0}", args[3].ToString());
                sb.AppendLine();
                sb.AppendFormat("q = {0}", args[4].ToString());
                sb.AppendLine();
                point = new ECPoint(args[5], args[6]);
                sb.AppendFormat("P = ({0}, {1})", point.GetAffineX().ToString(), point.GetAffineY().ToString());
                sb.AppendLine();
                P = ECMath.Multiply(curve, args[3] / args[4], point);
                sb.AppendFormat("Q = ({0}, {1})", P.GetAffineX().ToString(), P.GetAffineY().ToString());
                sb.AppendLine();
                P = ECMath.Multiply(curve, args[4], P);
                sb.Append("R = (0, 1)\n");
                sb.AppendLine();
            }
        }
Beispiel #9
0
        public EllipticDiffieHellman(EllipticCurve curve, Point generator, BigInteger order, byte[] priv = null)
        {
            this.curve     = curve;
            this.generator = generator;

            // Generate private key
            if (priv == null)
            {
                byte[] max = order.ToByteArray();
                do
                {
                    byte[] p1 = new byte[5 /*rand.Next(max.Length) + 1*/];

                    rand.NextBytes(p1);

                    if (p1.Length == max.Length)
                    {
                        p1[p1.Length - 1] %= max[max.Length - 1];
                    }
                    else
                    {
                        p1[p1.Length - 1] &= 127;
                    }

                    this.priv = new BigInteger(p1);
                } while (this.priv < 2);
            }
            else
            {
                this.priv = new BigInteger(priv);
            }

            // Generate public key
            pub = curve.Multiply(generator, this.priv);
        }
        public void GelfodMethod_MainTest()
        {
            EllipticCurve ECC = new EllipticCurve(1, 9, pField: 97, groupOrder: 90);

            Console.WriteLine($"{ECC}, N = {ECC.N}, p = {ECC.p}");
            Point Q = new Point(34, 16);

            Console.WriteLine($"Q = {Q}");
            Point P = new Point(69, 40);

            Console.WriteLine($"P = {P}");

            Dictionary <int, int> divisors = new Dictionary <int, int>
            {
                { 2, 1 },
                { 3, 2 },
                { 5, 1 }
            };

            int expected = 34;

            int actual = GelfondMethod.GetLog(ECC, Q, P, divisors);

            Console.WriteLine($"l = {actual}(mod {ECC.N})");

            Assert.AreEqual(expected, actual);
        }
Beispiel #11
0
 public SessionService(ApplicationContext context, IServerKeyManager keyManager, IMapper mapper, EllipticCurve ellipticCurve)
 {
     this.context       = context;
     this.keyManager    = keyManager;
     this.mapper        = mapper;
     this.ellipticCurve = ellipticCurve;
 }
Beispiel #12
0
        public Wallet()
        {
            this.Balance = Constants.STARTING_BALANCE;

            this.KeyPair   = EllipticCurve.GenerateKeys();
            this.PublicKey = this.KeyPair.PublicKey();
        }
Beispiel #13
0
 /// <summary>
 /// Abstract base class for Elliptic Curve / AES-256 hybrid ciphers.s
 /// </summary>
 /// <param name="PublicKey">Remote public key.</param>
 /// <param name="ReferenceCurve">Reference curve</param>
 /// <param name="DefaultSymmetricCipher">Default symmetric cipher.</param>
 public EllipticCurveEndpoint(byte[] PublicKey, EllipticCurve ReferenceCurve, IE2eSymmetricCipher DefaultSymmetricCipher)
     : base(DefaultSymmetricCipher)
 {
     this.publicKey       = PublicKey;
     this.curve           = ReferenceCurve;
     this.hasPrivateKey   = false;
     this.publicKeyBase64 = Convert.ToBase64String(this.publicKey);
 }
Beispiel #14
0
 /// <summary>
 /// Abstract base class for Elliptic Curve / AES-256 hybrid ciphers.s
 /// </summary>
 /// <param name="Curve">Curve instance</param>
 /// <param name="DefaultSymmetricCipher">Default symmetric cipher.</param>
 public EllipticCurveEndpoint(EllipticCurve Curve, IE2eSymmetricCipher DefaultSymmetricCipher)
     : base(DefaultSymmetricCipher)
 {
     this.curve           = Curve;
     this.publicKey       = Curve.PublicKey;
     this.hasPrivateKey   = true;
     this.publicKeyBase64 = Convert.ToBase64String(this.publicKey);
 }
Beispiel #15
0
        public static BigInteger computeZ(byte[] bytes, EllipticCurve theCurve)
        {
            BitArray hashBitArray = new BitArray(bytes);

            hashBitArray.RightShift(hashBitArray.Length - DummyProject.Common.BitOperations.getBits(theCurve.p).Length);
            hashBitArray.CopyTo(bytes, 0);
            return(new BigInteger(bytes));
        }
Beispiel #16
0
 private static void PrintPoints(EllipticCurve curve)
 {
     Console.WriteLine($"Curve: {curve}");
     Console.WriteLine($"Curve's order: {curve.N}{Environment.NewLine}");
     Console.WriteLine("Points of curve:");
     foreach (var point in curve.GenerateAllPoints())
     {
         Console.WriteLine(point);
     }
 }
Beispiel #17
0
        public void MultiplyPoint_PointOnCurve_CorrectResult()
        {
            EllipticCurve ECC      = new EllipticCurve(1, 9, pField: 97, groupOrder: 90);
            Point         P        = new Point(34, 16);
            Point         expected = new Point(19, 0);

            Point actual = ECC.MultiplyPoint(45, P);

            Assert.AreEqual(expected, actual);
        }
Beispiel #18
0
        //step 3
        private static BigInteger computeK(EllipticCurve theCurve)
        {
            BigInteger k = PrivateKeyGenerator.generatePrivateKey();

            while (k >= theCurve.p)
            {
                k = PrivateKeyGenerator.generatePrivateKey();
            }
            return(k);
        }
Beispiel #19
0
        public void AddPoints_SamePointOnCurve_CorrectResult()
        {
            EllipticCurve ECC = new EllipticCurve(1, 9, pField: 97, groupOrder: 90);
            Point         P   = new Point(22, 3);

            Point expected = new Point(10, 90);

            Point actual = ECC.AddPoints(P, P);

            Assert.AreEqual(expected, actual);
        }
Beispiel #20
0
        public void NegativePoint_PointOnCurve_CorrectResult()
        {
            EllipticCurve ECC = new EllipticCurve(1, 9, pField: 97, groupOrder: 90);
            Point         P   = new Point(10, 7);

            Point expected = new Point(10, 90);

            Point actual = ECC.GetNegativePoint(P);

            Assert.AreEqual(expected, actual);
        }
Beispiel #21
0
        public BFUserPrivateKey(SerializedPrivateKey key)
        {
            this.key = new Point(new BigInt(key.KeyX), new BigInt(key.KeyY));
            Fp            field = new Fp(new BigInt(key.CurveField));
            EllipticCurve curve = new EllipticCurve(field, new BigInt(key.CurveA), new BigInt(key.CurveB));
            Pairing       e     = new TatePairing(curve, new BigInt(key.PairingGroupOrder), new BigInt(key.PairingCofactor));
            Point         p     = new Point(new BigInt(key.PX), new BigInt(key.PY));
            Point         pPub  = new Point(new BigInt(key.PPubX), new BigInt(key.PPubY));

            this.param = new BFMasterPublicKey(e, p, pPub);
        }
Beispiel #22
0
        public void GetLog_PointOnCurve_CorrectResult()
        {
            EllipticCurve ECC = new EllipticCurve(1, 9, pField: 97, groupOrder: 90);
            Point         P   = new Point(72, 48);
            Point         Q   = new Point(72, 49);

            int expected = 2; //89

            int actual = ECC.GetLog(P, Q);

            Assert.AreEqual(expected, actual);
        }
Beispiel #23
0
        public void GetLog_InfPoint_ReturnsCorrectResult()
        {
            EllipticCurve ECC = new EllipticCurve(1, 9, pField: 97, groupOrder: 90);
            Point         P   = null;
            Point         Q   = new Point(19, 0);

            int expected = 2;

            int actual = ECC.GetLog(P, Q);

            Assert.AreEqual(expected, actual);
        }
Beispiel #24
0
        public void GetLog_SamePointsOnCurve_ReturnsOne()
        {
            EllipticCurve ECC = new EllipticCurve(1, 9, pField: 97, groupOrder: 90);
            Point         P   = new Point(72, 49);
            Point         Q   = new Point(72, 49);

            int expected = 1;

            int actual = ECC.GetLog(P, Q);

            Assert.AreEqual(expected, actual);
        }
        public void TestMultBook()
        {
            EllipticCurve curve = new EllipticCurve(a: -1, b: 3231, modulus: 661643);

            Point q = (87, 2);

            q = curve.Multiply(BigInteger.Pow(2, 9), q);
            bool success = q.Equals((Point)(196083, 134895));

            q       = curve.Multiply(BigInteger.Pow(3, 6), q);
            success = success && q.Equals((Point)(470021, 282574));
            Assert.IsTrue(success);
        }
Beispiel #26
0
        public static Point HashToPoint(byte[] toHash, EllipticCurve ec)
        {
            BigInt b = HashToField(toHash, ec.Field);

            Point P = ec.GetPoint(b);

            while (P == null)
            {
                b = b.Add(BigInt.ONE);
                P = ec.GetPoint(b);
            }
            return(P);
        }
Beispiel #27
0
    void Output(BigInteger privateKey)
    {
        BigInteger publicKeyX;
        BigInteger publicKeyY;

        BouncyCastle.ECPrivateKeyToPublicKey(privateKey, out publicKeyX, out publicKeyY);

        byte[] publicKey = EllipticCurve.PublicKeyToBytes(publicKeyX, publicKeyY);
        byte[] address   = ETHAddress.PublicKeyToETHAddress(publicKey);

        m_paragraphAddress.Inlines.Add("Private key (confidential): 0x" + Encode.BytesToHex(Encode.BigIntegerToBytes(privateKey, 32)) + "\n");
        m_paragraphAddress.Inlines.Add("Public key: 0x" + Encode.BytesToHex(publicKey) + "\n");
        m_paragraphAddress.Inlines.Add("ETH address: 0x" + Encode.BytesToHex(address) + "\n");
        m_paragraphAddress.Inlines.Add("ETC address: 0x" + Encode.BytesToHex(address) + "\n");
    }
Beispiel #28
0
        /// <summary>
        /// 使用公钥验证消息的签名是否正确
        /// </summary>
        /// <param name="publicKey"></param>
        /// <param name="message"></param>
        /// <param name="signature"></param>
        /// <returns></returns>
        public static bool Verify(PublicKey publicKey, ReadOnlySpan <byte> message, Signature signature)
        {
            if (message.Length != 32)
            {
                throw new InvalidMessageException("消息长度必须是32字节");
            }

            var msg   = new U256N(message);
            var S_inv = ~(U256N)signature.S;
            var u1    = S_inv * msg;
            var u2    = S_inv * signature.R;
            var P     = EllipticCurve.MulG(u1) + new JacobianPoint(publicKey.X, publicKey.Y) * u2;

            return(P.X == signature.R * (P.Z ^ 2));
        }
Beispiel #29
0
 /// <summary>
 /// Compares this elliptic curve for equality with the
 /// specified object. </summary>
 /// <param name="obj"> the object to be compared. </param>
 /// <returns> true if {@code obj} is an instance of
 /// EllipticCurve and the field, A, and B match, false otherwise. </returns>
 public override bool Equals(Object obj)
 {
     if (this == obj)
     {
         return(true);
     }
     if (obj is EllipticCurve)
     {
         EllipticCurve curve = (EllipticCurve)obj;
         if ((Field_Renamed.Equals(curve.Field_Renamed)) && (a.Equals(curve.a)) && (b.Equals(curve.b)))
         {
             return(true);
         }
     }
     return(false);
 }
Beispiel #30
0
        public static bool Validate(Transaction transaction)
        {
            var outputTotal = transaction.OutputMap.Values.Sum();

            if (transaction.Input.Amount != outputTotal)
            {
                Logger.Info($"Invalid transaction from {transaction.Input.Address}");
                return(false);
            }
            if (!EllipticCurve.VerifySignature(publicKey: transaction.Input.Address, data: transaction.OutputMap.SerializeObject(), signature: transaction.Input.Signature))
            {
                Logger.Info($"Invalid signature from {transaction.Input.Address}");
                return(false);
            }
            return(true);
        }