Inheritance: ECPoint
Exemplo n.º 1
0
        public Cypher GetCypher(string message)
        {
            BigInteger x = GeneralFunctions.H1hash(ID, prim);
            BigInteger y = x.Pow(3).Add(new BigInteger("7", 10)).Pow(2).ModInverse(prim);
            FpFieldElement x_Qid = new FpFieldElement(E.Q, x);
            FpFieldElement y_Qid = new FpFieldElement(E.Q, y);
            FpPoint Qid = new FpPoint(E, x_Qid, y_Qid);

            int r = 0;
            do
            {
                Random rnd = new Random();
                r = rnd.Next(1, int.MaxValue - 1);
            } while (r == 0);

            FpPoint rP = (FpPoint)P.Multiply(new BigInteger(r.ToString(), 10));

            BigInteger gid = GeneralFunctions.Pair(Qid, Ppub, k, prim);
            gid = gid.ModPow(new BigInteger(r.ToString(), 10), prim);

            char[] M = message.ToCharArray();
            char[] cArray = new char[M.Length];
            char[] hash = GeneralFunctions.H2hash(gid, prim).ToCharArray();
            for (int i = 0; i < message.Length; i++)
            {
                cArray[i] = (char)(M[i] ^ hash[i % hash.Length]);
            }

            string c = new String(cArray);

            return new Cypher { U = rP, V = c };
        }
Exemplo n.º 2
0
 public FpCurve(BigInteger q, BigInteger a, BigInteger b)
 {
     this.q        = q;
     this.a        = FromBigInteger(a);
     this.b        = FromBigInteger(b);
     this.infinity = new FpPoint(this, null, null);
 }
Exemplo n.º 3
0
        /**
         * Decode a point on this curve from its ASN.1 encoding. The different
         * encodings are taken account of, including point compression for
         * <code>F<sub>p</sub><code> (X9.62 s 4.2.1 pg 17).
         * @return The decoded point.
         */
        public override ECPoint DecodePoint(
            byte[] encoded)
        {
            ECPoint p = null;

            switch (encoded[0])
            {
            // compressed
            case 0x02:
            case 0x03:
                int    ytilde = encoded[0] & 1;
                byte[] i      = new byte[encoded.Length - 1];

                Array.Copy(encoded, 1, i, 0, i.Length);

                ECFieldElement x     = new FpFieldElement(this.q, new BigInteger(1, i));
                ECFieldElement alpha = x.Multiply(x.Square()).Add(x.Multiply(a).Add(b));
                ECFieldElement beta  = alpha.Sqrt();

                //
                // if we can't find a sqrt we haven't got a point on the
                // curve - run!
                //
                if (beta == null)
                {
                    throw new ArithmeticException("Invalid point compression");
                }

                BigInteger betaValue = beta.ToBigInteger();
                int        bit0      = betaValue.TestBit(0) ? 1 : 0;

                if (bit0 != ytilde)
                {
                    // Use the other root
                    beta = new FpFieldElement(q, q.Subtract(betaValue));
                }

                p = new FpPoint(this, x, beta, true);
                break;

            case 0x04:
                byte[] xEnc = new byte[(encoded.Length - 1) / 2];
                byte[] yEnc = new byte[(encoded.Length - 1) / 2];

                Array.Copy(encoded, 1, xEnc, 0, xEnc.Length);
                Array.Copy(encoded, xEnc.Length + 1, yEnc, 0, yEnc.Length);

                p = new FpPoint(this,
                                new FpFieldElement(this.q, new BigInteger(1, xEnc)),
                                new FpFieldElement(this.q, new BigInteger(1, yEnc)));
                break;

            default:
                throw new FormatException("Invalid point encoding " + encoded[0]);
            }

            return(p);
        }
Exemplo n.º 4
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;
 }
Exemplo n.º 5
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);
				}
			}
Exemplo n.º 6
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);
     base.m_a        = this.FromBigInteger(a);
     base.m_b        = this.FromBigInteger(b);
     base.m_order    = order;
     base.m_cofactor = cofactor;
     base.m_coord    = 4;
 }
Exemplo n.º 7
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);
     base.m_a        = a;
     base.m_b        = b;
     base.m_order    = order;
     base.m_cofactor = cofactor;
     base.m_coord    = 4;
 }
Exemplo n.º 8
0
        public FpCurve(BigInteger q, BigInteger a, BigInteger b, BigInteger order, BigInteger cofactor)
            : base(FiniteFields.GetPrimeField(q))
        {
            this.m_q        = q;
            this.m_r        = FpFieldElement.CalculateResidue(q);
            this.m_infinity = new FpPoint(this, null, null);

            this.m_a        = FromBigInteger(a);
            this.m_b        = FromBigInteger(b);
            this.m_order    = order;
            this.m_cofactor = cofactor;
            this.m_coord    = FP_DEFAULT_COORDS;
        }
Exemplo n.º 9
0
        protected FpCurve(BigInteger q, BigInteger r, ECFieldElement a, ECFieldElement b, BigInteger order, BigInteger cofactor)
            : base(FiniteFields.GetPrimeField(q))
        {
            this.m_q        = q;
            this.m_r        = r;
            this.m_infinity = new FpPoint(this, null, null);

            this.m_a        = a;
            this.m_b        = b;
            this.m_order    = order;
            this.m_cofactor = cofactor;
            this.m_coord    = FP_DEFAULT_COORDS;
        }
Exemplo n.º 10
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;
        }
Exemplo n.º 11
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;
        }
Exemplo n.º 12
0
        public Setup()
        {
            n = 3;

            do
            {
                Random r = new Random();
                s = r.Next(1, int.MaxValue - 1);
            } while (s == 0);

            // p i q
            p = new BigInteger("115792089237316195423570985008687907853269984665640564039457584007908834671663", 10);
            //q = p.Pow(n);
            q = p;

            k = new BigInteger("115792089237316195423570985008687907852837564279074904382605163141518161494337", 10);

            // E - krivulja secp256k1 - y ^ 2 = x ^ 3 + 0*x + 7
            BigInteger a = new BigInteger("0", 10);
            BigInteger b = new BigInteger("7", 10);
            E = new FpCurve(q, a, b);

            // P
            BigInteger x1 = new BigInteger("55066263022277343669578718895168534326250603453777594175500187360389116729240", 10);
            BigInteger y1 = new BigInteger("32670510020758816978083085130507043184471273380659243275938904335757337482424", 10);
            FpFieldElement x = (FpFieldElement)E.FromBigInteger(x1); // new FpFieldElement(q, x1);
            FpFieldElement y = (FpFieldElement)E.FromBigInteger(y1); // new FpFieldElement(q, y1);

            P = new FpPoint(E, x, y);

            BigInteger mtp = new BigInteger(s.ToString(), 10);

            Ppub = (FpPoint)P.Multiply(mtp);

            File.WriteAllText("mk", s.ToString() + Environment.NewLine);
        }
Exemplo n.º 13
0
        public static Tuple <byte[], byte[]> GetSecp256k1PublicKey(byte[] privateKey)
        {
            //Secp256k1 curve variables - https://en.bitcoin.it/wiki/Secp256k1
            var privKeyInt = new BigInteger(+1, privateKey);
            var a          = new BigInteger("0");
            var b          = new BigInteger("7");
            var GX         = new BigInteger(+1, HexStringToByteArray("79BE667E F9DCBBAC 55A06295 CE870B07 029BFCDB 2DCE28D9 59F2815B 16F81798"));
            var GY         = new BigInteger(+1, HexStringToByteArray("483ADA77 26A3C465 5DA4FBFC 0E1108A8 FD17B448 A6855419 9C47D08F FB10D4B8"));
            //var n = new BigInteger(+1, HexStringToByteArray("FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFE BAAEDCE6 AF48A03B BFD25E8C D0364141"));
            //var h = new BigInteger("1");
            var p = new BigInteger(+1, HexStringToByteArray("FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFE FFFFFC2F"));
            //var q = h.Multiply(n).Mod(p); //Is this right???
            //- http://en.wikipedia.org/wiki/Elliptic_curve_cryptography

            ECCurve curve = new Org.BouncyCastle.Math.EC.FpCurve(p, a, b);
            ECPoint G     = new Org.BouncyCastle.Math.EC.FpPoint(curve, new FpFieldElement(p, GX), new FpFieldElement(p, GY));

            var Qa = G.Multiply(privKeyInt);

            byte[] PubKeyX = Qa.X.ToBigInteger().ToByteArrayUnsigned();
            byte[] PubKeyY = Qa.Y.ToBigInteger().ToByteArrayUnsigned();

            return(Tuple.Create(PubKeyX, PubKeyY));
        }
Exemplo n.º 14
0
        /// <summary>
        /// Regenerate public key parameters (ECPoint compression)
        /// </summary>
        /// <param name="pubKeyParams">Non-compressed key parameters</param>
        /// <returns>Parameters for compressed key</returns>
        protected ECPublicKeyParameters Compress(ECPublicKeyParameters pubKeyParams)
        {
            if (pubKeyParams.Q.IsCompressed)
            {
                // Already compressed
                return pubKeyParams;
            }

            ECPoint q = new FpPoint(curve.Curve, pubKeyParams.Q.X, pubKeyParams.Q.Y, true);

            return new ECPublicKeyParameters(q, domain);
        }
        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);

            this.m_a = FromBigInteger(a);
            this.m_b = FromBigInteger(b);
            this.m_order = order;
            this.m_cofactor = cofactor;
            this.m_coord = FP_DEFAULT_COORDS;
        }
Exemplo n.º 16
0
 public Decrypt(FpPoint did, BigInteger prim, BigInteger stp)
 {
     d_id = did;
     p = prim;
     k = stp;
 }
Exemplo n.º 17
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;
        }
Exemplo n.º 18
0
        public static ECKey RecoverFromSignature(int recId, ECDSASignature sig, uint256 message, bool compressed)
        {
            if(recId < 0)
                throw new ArgumentException("recId should be positive");
            if(sig.R.SignValue < 0)
                throw new ArgumentException("r should be positive");
            if(sig.S.SignValue < 0)
                throw new ArgumentException("s should be positive");
            if(message == null)
                throw new ArgumentNullException("message");

            var curve = ECKey.CreateCurve();

            // 1.0 For j from 0 to h   (h == recId here and the loop is outside this function)
            //   1.1 Let x = r + jn

            var n = curve.N;
            var i = Org.BouncyCastle.Math.BigInteger.ValueOf((long)recId / 2);
            var x = sig.R.Add(i.Multiply(n));

            //   1.2. Convert the integer x to an octet string X of length mlen using the conversion routine
            //        specified in Section 2.3.7, where mlen = ⌈(log2 p)/8⌉ or mlen = ⌈m/8⌉.
            //   1.3. Convert the octet string (16 set binary digits)||X to an elliptic curve point R using the
            //        conversion routine specified in Section 2.3.4. If this conversion routine outputs “invalid”, then
            //        do another iteration of Step 1.
            //
            // More concisely, what these points mean is to use X as a compressed public key.
            var prime = ((FpCurve)curve.Curve).Q;
            if(x.CompareTo(prime) >= 0)
            {
                return null;
            }

            // Compressed keys require you to know an extra bit of data about the y-coord as there are two possibilities.
            // So it's encoded in the recId.
            ECPoint R = DecompressKey(x, (recId & 1) == 1);
            //   1.4. If nR != point at infinity, then do another iteration of Step 1 (callers responsibility).

            if(!R.Multiply(n).IsInfinity)
                return null;

            //   1.5. Compute e from M using Steps 2 and 3 of ECDSA signature verification.
            var e = new Org.BouncyCastle.Math.BigInteger(1, message.ToBytes());
            //   1.6. For k from 1 to 2 do the following.   (loop is outside this function via iterating recId)
            //   1.6.1. Compute a candidate public key as:
            //               Q = mi(r) * (sR - eG)
            //
            // Where mi(x) is the modular multiplicative inverse. We transform this into the following:
            //               Q = (mi(r) * s ** R) + (mi(r) * -e ** G)
            // Where -e is the modular additive inverse of e, that is z such that z + e = 0 (mod n). In the above equation
            // ** is point multiplication and + is point addition (the EC group operator).
            //
            // We can find the additive inverse by subtracting e from zero then taking the mod. For example the additive
            // inverse of 3 modulo 11 is 8 because 3 + 8 mod 11 = 0, and -3 mod 11 = 8.

            var eInv = Org.BouncyCastle.Math.BigInteger.Zero.Subtract(e).Mod(n);
            var rInv = sig.R.ModInverse(n);
            var srInv = rInv.Multiply(sig.S).Mod(n);
            var eInvrInv = rInv.Multiply(eInv).Mod(n);
            var q = (FpPoint)ECAlgorithms.SumOfTwoMultiplies(curve.G, eInvrInv, R, srInv);
            if(compressed)
            {
                q = new FpPoint(curve.Curve, q.X, q.Y, true);
            }
            return new ECKey(q.GetEncoded(), false);
        }
Exemplo n.º 19
0
            protected override X9ECParameters CreateParameters()
            {
                // p = 2^224 - 2^96 + 1
                BigInteger secp224r1P = new BigInteger(
                    "26959946667150639794667015087019630673557916260026308143510066298881");

                // a = -3, b = b4050a850c04b3abf54132565044b0b7d7bfd8ba270b39432355ffb4
                ECCurve secp224r1Curve = new FpCurve(secp224r1P,
                    new BigInteger("26959946667150639794667015087019630673557916260026308143510066298878"),
                    new BigInteger("b4050a850c04b3abf54132565044b0b7d7bfd8ba270b39432355ffb4", 16));

                // x = b70e0cbd6bb4bf7f321390b94a03c1d356c21122343280d6115c1d21
                ECFieldElement secp224r1x = new FpFieldElement(
                    secp224r1P,
                    new BigInteger("b70e0cbd6bb4bf7f321390b94a03c1d356c21122343280d6115c1d21", 16));

                // y = bd376388b5f723fb4c22dfe6cd4375a05a07476444d5819985007e34
                ECFieldElement secp224r1y = new FpFieldElement(
                    secp224r1P,
                    new BigInteger("bd376388b5f723fb4c22dfe6cd4375a05a07476444d5819985007e34", 16));

                ECPoint secp224r1BasePoint = new FpPoint(
                    secp224r1Curve, secp224r1x, secp224r1y, false);

                BigInteger secp224r1n = new BigInteger("26959946667150639794667015087019625940457807714424391721682722368061");

                BigInteger secp224r1h = new BigInteger("1");

                //static readonly byte[] secp224r1Seed = (Hex.decode("bd71344799d5c7fcdc45b59fa3b9ab8f6a948bc5"));
                byte[] secp224r1Seed = null;

                return new X9ECParameters(
                    secp224r1Curve,
                    secp224r1BasePoint,
                    secp224r1n,
                    secp224r1h,
                    secp224r1Seed);
            }
Exemplo n.º 20
0
 public FpCurve(BigInteger q, BigInteger a, BigInteger b)
 {
     this.q = q;
     this.a = FromBigInteger(a);
     this.b = FromBigInteger(b);
     this.infinity = new FpPoint(this, null, null);
 }
Exemplo n.º 21
0
        // Miller "function"
        private static BigInteger MLF(FpPoint P, FpPoint R, FpPoint Q)
        {
            if (!P.Equals(R))
            {
                if (P.X.Equals(R.X))
                {
                    return Q.X.Subtract(P.X).ToBigInteger();
                }
                else {
                    BigInteger l = R.Y.Subtract(P.Y).Divide((R.X.Subtract(P.X))).ToBigInteger();

                    return Q.Y.Subtract(P.Y).ToBigInteger().Subtract(l.Multiply((Q.X.Subtract(P.X).ToBigInteger())));
                }
            }
            else
            {
                // z*y^2=d*x^3+a*x+b -> derivacija po x -> 3*x^2+a
                BigInteger brojnik = new BigInteger("3", 10).Multiply(P.X.ToBigInteger().Pow(2));
                // z*y^2=d*x^3+a*x+b -> derivacija po y -> 2*y
                BigInteger nazivnik = new BigInteger("2", 10).Multiply(P.Y.ToBigInteger());

                if (nazivnik.ToString(10) == "0")
                {
                    return (Q.X.ToBigInteger().Subtract(P.X.ToBigInteger()));
                }
                else
                {
                    double koef = (double)(brojnik.IntValue / nazivnik.IntValue);

                    double rez = Q.Y.Subtract(P.Y).ToBigInteger().IntValue - koef * (Q.X.Subtract(P.X).ToBigInteger().IntValue);

                    return new BigInteger(rez.ToString(), 10);
                }
            }
        }
Exemplo n.º 22
0
        public static AsymmetricKeyParameter CreateKey(
			SubjectPublicKeyInfo keyInfo)
        {
            AlgorithmIdentifier algID = keyInfo.AlgorithmID;

            if (algID.ObjectID.Equals(PkcsObjectIdentifiers.RsaEncryption)
                || algID.ObjectID.Equals(X509ObjectIdentifiers.IdEARsa))
            {
                RsaPublicKeyStructure pubKey = RsaPublicKeyStructure.GetInstance(keyInfo.GetPublicKey());

                return new RsaKeyParameters(false, pubKey.Modulus, pubKey.PublicExponent);
            }
            else if (algID.ObjectID.Equals(PkcsObjectIdentifiers.DhKeyAgreement)
                || algID.ObjectID.Equals(X9ObjectIdentifiers.DHPublicNumber))
            {
                DHParameter para = new DHParameter((Asn1Sequence)keyInfo.AlgorithmID.Parameters);
                DerInteger derY = (DerInteger)keyInfo.GetPublicKey();

                return new DHPublicKeyParameters(derY.Value, new DHParameters(para.P, para.G));
            }
            else if (algID.ObjectID.Equals(OiwObjectIdentifiers.ElGamalAlgorithm))
            {
                ElGamalParameter para = new ElGamalParameter((Asn1Sequence)keyInfo.AlgorithmID.Parameters);
                DerInteger derY = (DerInteger)keyInfo.GetPublicKey();

                return new ElGamalPublicKeyParameters(derY.Value, new ElGamalParameters(para.P, para.G));
            }
            else if (algID.ObjectID.Equals(X9ObjectIdentifiers.IdDsa)
                || algID.ObjectID.Equals(OiwObjectIdentifiers.DsaWithSha1))
            {
                DsaParameter para = DsaParameter.GetInstance(keyInfo.AlgorithmID.Parameters);
                DerInteger derY = (DerInteger)keyInfo.GetPublicKey();

                return new DsaPublicKeyParameters(derY.Value, new DsaParameters(para.P, para.Q, para.G));
            }
            else if (algID.ObjectID.Equals(X9ObjectIdentifiers.IdECPublicKey))
            {
                X962Parameters para = new X962Parameters((Asn1Object)keyInfo.AlgorithmID.Parameters);
                ECDomainParameters dParams = null;

                if (para.IsNamedCurve)
                {
                    DerObjectIdentifier oid = (DerObjectIdentifier)para.Parameters;
                    X9ECParameters ecP = X962NamedCurves.GetByOid(oid);

                    if (ecP == null)
                    {
                        ecP = SecNamedCurves.GetByOid(oid);

                        if (ecP == null)
                        {
                            ecP = NistNamedCurves.GetByOid(oid);
                        }
                    }

                    dParams = new ECDomainParameters(
                        ecP.Curve,
                        ecP.G,
                        ecP.N,
                        ecP.H,
                        ecP.GetSeed());
                }
                else
                {
                    X9ECParameters ecP = new X9ECParameters((Asn1Sequence)para.Parameters.ToAsn1Object());

                    dParams = new ECDomainParameters(
                        ecP.Curve,
                        ecP.G,
                        ecP.N,
                        ecP.H,
                        ecP.GetSeed());
                }

                DerBitString bits = keyInfo.PublicKeyData;
                byte[] data = bits.GetBytes();
                Asn1OctetString key = new DerOctetString(data);

                X9ECPoint derQ = new X9ECPoint(dParams.Curve, key);

                return new ECPublicKeyParameters(derQ.Point, dParams);
            }
            else if (algID.ObjectID.Equals(CryptoProObjectIdentifiers.GostR3410x2001))
            {
                Gost3410PublicKeyAlgParameters gostParams = new Gost3410PublicKeyAlgParameters(
                    (Asn1Sequence) algID.Parameters);

                Asn1OctetString key;
                try
                {
                    key = (Asn1OctetString) keyInfo.GetPublicKey();
                }
                catch (IOException)
                {
                    throw new ArgumentException("invalid info structure in GOST3410 public key");
                }

                byte[] keyEnc = key.GetOctets();
                byte[] x = new byte[32];
                byte[] y = new byte[32];

                for (int i = 0; i != y.Length; i++)
                {
                    x[i] = keyEnc[32 - 1 - i];
                }

                for (int i = 0; i != x.Length; i++)
                {
                    y[i] = keyEnc[64 - 1 - i];
                }

                ECDomainParameters ecP = ECGost3410NamedCurves.GetByOid(gostParams.PublicKeyParamSet);

                if (ecP == null)
                    return null;

                ECCurve curve = ecP.Curve;
                ECPoint q;

                if (curve is FpCurve)
                {
                    FpCurve curveFp = (FpCurve) curve;
                    q = new FpPoint(
                        curveFp,
                        new FpFieldElement(curveFp.Q, new BigInteger(1, x)),
                        new FpFieldElement(curveFp.Q, new BigInteger(1, y)));
                }
                else
                {
                    F2mCurve curveF2m = (F2mCurve) curve;
                    q = new F2mPoint(
                        curveF2m,
                        new F2mFieldElement(curveF2m.M, curveF2m.K1, curveF2m.K2, curveF2m.K3, new BigInteger(1, x)),
                        new F2mFieldElement(curveF2m.M, curveF2m.K1, curveF2m.K2, curveF2m.K3, new BigInteger(1, y)),
                        false);
                }

                return new ECPublicKeyParameters(q, gostParams.PublicKeyParamSet);
            }
            else if (algID.ObjectID.Equals(CryptoProObjectIdentifiers.GostR3410x94))
            {
                Gost3410PublicKeyAlgParameters algParams = new Gost3410PublicKeyAlgParameters(
                    (Asn1Sequence) algID.Parameters);

                DerOctetString derY;
                try
                {
                    derY = (DerOctetString) keyInfo.GetPublicKey();
                }
                catch (IOException)
                {
                    throw new ArgumentException("invalid info structure in GOST3410 public key");
                }

                byte[] keyEnc = derY.GetOctets();
                byte[] keyBytes = new byte[keyEnc.Length];

                for (int i = 0; i != keyEnc.Length; i++)
                {
                    keyBytes[i] = keyEnc[keyEnc.Length - 1 - i]; // was little endian
                }

                BigInteger y = new BigInteger(1, keyBytes);

                return new Gost3410PublicKeyParameters(y, algParams.PublicKeyParamSet);
            }
            else
            {
                throw new SecurityUtilityException("algorithm identifier in key not recognised: " + algID.ObjectID);
            }
        }
Exemplo n.º 23
0
        private static void Main(string[] args)
        {
            string id = "*****@*****.**";
            string poruka = "moram porati posluku";
            Cypher sifrat;

            if (args.Length < 2)
            {
                test();
                Console.WriteLine("\n");
                upute();
                return;
            }

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

            if (args[0] == "-f")
            {
                string put = args[1];
                if (!File.Exists(put))
                {
                    poruka = File.ReadAllText(put);
                    if (args.Length != 3)
                    {
                        upute();
                        return;
                    }

                    id = args[args.Length - 1];

                    encode(poruka, id, setup);
                }
                else
                {
                    Console.WriteLine("File does not exists!\n");
                    upute();
                    return;
                }
            }

            string sif;
            string xs;
            string ys;

            if (args[1] == "-d")
            {
                if (args[1] == "-f" && args.Length == 6)
                {
                    string put = args[2];
                    sif = File.ReadAllText(put);

                    id = args[args.Length - 1];
                    xs = args[3];
                    ys = args[4];
                }
                else if (args.Length > 6 || args.Length != 5)
                {
                    upute();
                    return;
                }
                else
                {
                    sif = args[1];
                    xs = args[2];
                    ys = args[3];
                    id = args[args.Length - 1];
                }

                BigInteger x1 = new BigInteger(xs, 10);
                BigInteger y1 = new BigInteger(ys, 10);

                FpFieldElement x = (FpFieldElement)setup.E.FromBigInteger(x1);
                FpFieldElement y = (FpFieldElement)setup.E.FromBigInteger(y1);

                FpPoint point = new FpPoint(setup.E, x, y);

                sifrat = new Cypher { U = point, V = sif };

                decode(sifrat, id, setup);
            }
            else
            {
                poruka = "";
                for (int i = 1; i < args.Length - 2; i++)
                {
                    poruka += args[i] + " ";
                }
                poruka += args[args.Length - 2];

                id = args[args.Length - 1];

                encode(poruka, id, setup);
            }

            Console.ReadKey();
        }
Exemplo n.º 24
0
            protected override X9ECParameters CreateParameters()
            {
                // p = 2^256 - 2^224 + 2^192 + 2^96 - 1
                BigInteger secp256r1P = new BigInteger(
                    "115792089210356248762697446949407573530086143415290314195533631308867097853951");

                // a = -3, b = 5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b
                ECCurve secp256r1Curve = new FpCurve(secp256r1P,
                    new BigInteger("115792089210356248762697446949407573530086143415290314195533631308867097853948"),
                    new BigInteger("5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b", 16));

                // x = 6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296
                ECFieldElement secp256r1x = new FpFieldElement(
                    secp256r1P,
                    new BigInteger("6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296", 16));

                // y = 4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5
                ECFieldElement secp256r1y = new FpFieldElement(
                    secp256r1P,
                    new BigInteger("4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5", 16));

                ECPoint secp256r1BasePoint = new FpPoint(
                    secp256r1Curve, secp256r1x, secp256r1y, false);

                BigInteger secp256r1n = new BigInteger("115792089210356248762697446949407573529996955224135760342422259061068512044369");

                BigInteger secp256r1h = new BigInteger("1");

                //static readonly byte[] secp256r1Seed = (Hex.decode("c49d360886e704936a6678e1139d26b7819f7e90"));
                byte[] secp256r1Seed = null;

                return new X9ECParameters(
                    secp256r1Curve,
                    secp256r1BasePoint,
                    secp256r1n,
                    secp256r1h,
                    secp256r1Seed);
            }
Exemplo n.º 25
0
        /// <summary>
        /// Regenerate public key parameters (ECPoint decompression)
        /// </summary>
        /// <param name="pubKeyParams">Compressed key parameters</param>
        /// <returns>Parameters for non-compressed key</returns>
        protected ECPublicKeyParameters Decompress(ECPublicKeyParameters pubKeyParams)
        {
            if (!pubKeyParams.Q.IsCompressed)
            {
                // Isn't compressed
                return pubKeyParams;
            }

            var q = new FpPoint(curve.Curve, pubKeyParams.Q.X, pubKeyParams.Q.Y, false);

            return new ECPublicKeyParameters(q, domain);
        }
Exemplo n.º 26
0
            protected override X9ECParameters CreateParameters()
            {
                // p = 2^384 - 2^128 - 2^96 + 2^32 - 1
                BigInteger secp384r1P = new BigInteger(
                    "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFF0000000000000000FFFFFFFF", 16);

                // a, b
                ECCurve secp384r1Curve = new FpCurve(secp384r1P,
                    new BigInteger("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFF0000000000000000FFFFFFFC", 16),
                    new BigInteger("B3312FA7E23EE7E4988E056BE3F82D19181D9C6EFE8141120314088F5013875AC656398D8A2ED19D2A85C8EDD3EC2AEF", 16));

                // x
                ECFieldElement secp384r1x = new FpFieldElement(
                    secp384r1P,
                    new BigInteger("AA87CA22BE8B05378EB1C71EF320AD746E1D3B628BA79B9859F741E082542A385502F25DBF55296C3A545E3872760AB7", 16));

                // y
                ECFieldElement secp384r1y = new FpFieldElement(
                    secp384r1P,
                    new BigInteger("3617DE4A96262C6F5D9E98BF9292DC29F8F41DBD289A147CE9DA3113B5F0B8C00A60B1CE1D7E819D7A431D7C90EA0E5F", 16));

                ECPoint secp384r1BasePoint = new FpPoint(
                    secp384r1Curve, secp384r1x, secp384r1y, false);

                BigInteger secp384r1n = new BigInteger("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFC7634D81F4372DDF581A0DB248B0A77AECEC196ACCC52973", 16);

                BigInteger secp384r1h = BigInteger.One;

                //static readonly byte[] secp384r1Seed = (Hex.decode("A335926AA319A27A1D00896A6773A4827ACDAC73"));
                byte[] secp384r1Seed = null;

                return new X9ECParameters(
                    secp384r1Curve,
                    secp384r1BasePoint,
                    secp384r1n,
                    secp384r1h,
                    secp384r1Seed);
            }
        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);

            this.m_a = a;
            this.m_b = b;
            this.m_order = order;
            this.m_cofactor = cofactor;
            this.m_coord = FP_DEFAULT_COORDS;
        }
Exemplo n.º 28
0
        /**
         * Decode a point on this curve from its ASN.1 encoding. The different
         * encodings are taken account of, including point compression for
         * <code>F<sub>p</sub></code> (X9.62 s 4.2.1 pg 17).
         * @return The decoded point.
         */
        public override ECPoint DecodePoint(
			byte[] encoded)
        {
            ECPoint p = null;

            switch (encoded[0])
            {
                // compressed
                case 0x02:
                case 0x03:
                    int ytilde = encoded[0] & 1;
                    byte[] i = new byte[encoded.Length - 1];

                    Array.Copy(encoded, 1, i, 0, i.Length);

                    ECFieldElement x = new FpFieldElement(this.q, new BigInteger(1, i));
                    ECFieldElement alpha = x.Multiply(x.Square()).Add(x.Multiply(a).Add(b));
                    ECFieldElement beta = alpha.Sqrt();

                    //
                    // if we can't find a sqrt we haven't got a point on the
                    // curve - run!
                    //
                    if (beta == null)
                        throw new ArithmeticException("Invalid point compression");

                    BigInteger betaValue = beta.ToBigInteger();
                    int bit0 = betaValue.TestBit(0) ? 1 : 0;

                    if (bit0 != ytilde)
                    {
                        // Use the other root
                        beta = new FpFieldElement(q, q.Subtract(betaValue));
                    }

                    p = new FpPoint(this, x, beta, true);
                    break;
                case 0x04:
                    byte[] xEnc = new byte[(encoded.Length - 1) / 2];
                    byte[] yEnc = new byte[(encoded.Length - 1) / 2];

                    Array.Copy(encoded, 1, xEnc, 0, xEnc.Length);
                    Array.Copy(encoded, xEnc.Length + 1, yEnc, 0, yEnc.Length);

                    p = new FpPoint(this,
                        new FpFieldElement(this.q, new BigInteger(1, xEnc)),
                        new FpFieldElement(this.q, new BigInteger(1, yEnc)));
                    break;
                default:
                    throw new FormatException("Invalid point encoding " + encoded[0]);
            }

            return p;
        }
Exemplo n.º 29
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
			}
		}
Exemplo n.º 30
0
            protected override X9ECParameters CreateParameters()
            {
                // p = 2^521 - 1
                BigInteger secp521r1P = new BigInteger(
                    "6864797660130609714981900799081393217269435300143305409394463459185543183397656052122559640661454554977296311391480858037121987999716643812574028291115057151");

                // a = -3, b = 051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00
                ECCurve secp521r1Curve = new FpCurve(secp521r1P,
                    new BigInteger("6864797660130609714981900799081393217269435300143305409394463459185543183397656052122559640661454554977296311391480858037121987999716643812574028291115057148"),
                    new BigInteger("051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00", 16));

                // x = c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66
                ECFieldElement secp521r1x = new FpFieldElement(
                    secp521r1P,
                    new BigInteger("c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66", 16));

                // y = 11839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650
                ECFieldElement secp521r1y = new FpFieldElement(
                    secp521r1P,
                    new BigInteger("11839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650", 16));

                ECPoint secp521r1BasePoint = new FpPoint(
                    secp521r1Curve, secp521r1x, secp521r1y, false);

                BigInteger secp521r1n = new BigInteger("6864797660130609714981900799081393217269435300143305409394463459185543183397655394245057746333217197532963996371363321113864768612440380340372808892707005449");

                BigInteger secp521r1h = new BigInteger("1");

                //static readonly byte[] secp521r1Seed = (Hex.decode("d09e8800291cb85396cc6717393284aaa0da64ba"));
                byte[] secp521r1Seed = null;

                return new X9ECParameters(
                    secp521r1Curve,
                    secp521r1BasePoint,
                    secp521r1n,
                    secp521r1h,
                    secp521r1Seed);
            }
Exemplo n.º 31
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);
        }
Exemplo n.º 32
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");
		}