internal Config(ECCurve outer, int coord, ECEndomorphism endomorphism, ECMultiplier multiplier)
 {
     this.outer = outer;
     this.coord = coord;
     this.endomorphism = endomorphism;
     this.multiplier = multiplier;
 }
		public X9ECParameters(
            ECCurve		curve,
            ECPoint		g,
            BigInteger	n)
            : this(curve, g, n, BigInteger.One, null)
        {
        }
예제 #3
0
    public bool VerifySignature(byte[] message, byte[] signature, byte[] pubkey)
    {
      if (pubkey.Length == 33 && (pubkey[0] == 0x02 || pubkey[0] == 0x03))
      {
        try
        {
          pubkey = ECPoint.DecodePoint(pubkey, ECCurve.Secp256r1).EncodePoint(false).Skip(1).ToArray();
        }
        catch
        {
          return false;
        }
      }
      else if (pubkey.Length == 65 && pubkey[0] == 0x04)
      {
        pubkey = pubkey.Skip(1).ToArray();
      }
      else if (pubkey.Length != 64)
      {
        throw new ArgumentException();
      }

      BigInteger x = new BigInteger(1, pubkey.Take(32).ToArray());
      BigInteger y = new BigInteger(1, pubkey.Skip(32).ToArray());

      X9ECParameters ecParams = NistNamedCurves.GetByName("P-256");
      ECDomainParameters domainParameters = new ECDomainParameters(ecParams.Curve, ecParams.G, ecParams.N,
        ecParams.H, ecParams.GetSeed());
      var G = ecParams.G;
      Org.BouncyCastle.Math.EC.ECCurve curve = ecParams.Curve;
      Org.BouncyCastle.Math.EC.ECPoint q = curve.CreatePoint(x, y);

      ECPublicKeyParameters pubkeyParam = new ECPublicKeyParameters(q, domainParameters);

      var verifier = SignerUtilities.GetSigner("SHA-256withECDSA");
      
      verifier.Init(false, pubkeyParam);
      verifier.BlockUpdate(message, 0, message.Length);
      // expected format is SEQUENCE {INTEGER r, INTEGER s}
      var derSignature = new DerSequence(
          // first 32 bytes is "r" number
          new DerInteger(new BigInteger(1, signature.Take(32).ToArray())),
          // last 32 bytes is "s" number
          new DerInteger(new BigInteger(1, signature.Skip(32).ToArray())))
          .GetDerEncoded();

      ///old verify method
      ///
      /*
      const int ECDSA_PUBLIC_P256_MAGIC = 0x31534345;
      pubkey = BitConverter.GetBytes(ECDSA_PUBLIC_P256_MAGIC).Concat(BitConverter.GetBytes(32)).Concat(pubkey).ToArray();
      using (CngKey key = CngKey.Import(pubkey, CngKeyBlobFormat.EccPublicBlob))
      using (ECDsaCng ecdsa = new ECDsaCng(key))
      {
        var result = ecdsa.VerifyData(message, signature, HashAlgorithmName.SHA256);
      }
      */
      ///////////////////
      return verifier.VerifySignature(derSignature);
    }
예제 #4
0
        public static SqlBoolean verifySignature(SqlString keySize, SqlString PublicKey, SqlString message, SqlString signature)
        {
            byte[] messageBytes   = Encoding.ASCII.GetBytes(message.ToString());
            byte[] signatureBytes = Convert.FromBase64String(signature.ToString());

            X9ECParameters     ecParams         = NistNamedCurves.GetByName("P-" + keySize.ToString());
            ECDomainParameters domainParameters = new ECDomainParameters(ecParams.Curve, ecParams.G, ecParams.N, ecParams.H, ecParams.GetSeed());
            var G = ecParams.G;

            Org.BouncyCastle.Math.EC.ECCurve curve = ecParams.Curve;

            byte[]  encoded = Convert.FromBase64String(PublicKey.ToString());
            ECPoint q       = curve.DecodePoint(encoded);

            try
            {
                ECPublicKeyParameters pubkeyParam = new ECPublicKeyParameters(q, domainParameters);
                var verifier = SignerUtilities.GetSigner("ECDSA");
                verifier.Init(false, pubkeyParam);
                verifier.BlockUpdate(messageBytes, 0, messageBytes.Length);
                bool signatureOK = verifier.VerifySignature(signatureBytes);

                return(signatureOK);
            }
            catch
            {
                return(false);
            }
        }
예제 #5
0
 protected ECPoint(ECCurve curve, ECFieldElement x, ECFieldElement y)
 {
     // TODO Should curve == null be allowed?
     this.curve = curve;
     this.x = x;
     this.y = y;
 }
예제 #6
0
		public ECDomainParameters(
            ECCurve     curve,
            ECPoint     g,
            BigInteger  n)
			: this(curve, g, n, BigInteger.One)
        {
        }
예제 #7
0
        protected static ECFieldElement[] GetInitialZCoords(ECCurve curve)
        {
            // Cope with null curve, most commonly used by implicitlyCa
            int coord = null == curve ? ECCurve.COORD_AFFINE : curve.CoordinateSystem;

            switch (coord)
            {
                case ECCurve.COORD_AFFINE:
                case ECCurve.COORD_LAMBDA_AFFINE:
                    return EMPTY_ZS;
                default:
                    break;
            }

            ECFieldElement one = curve.FromBigInteger(BigInteger.One);

            switch (coord)
            {
                case ECCurve.COORD_HOMOGENEOUS:
                case ECCurve.COORD_JACOBIAN:
                case ECCurve.COORD_LAMBDA_PROJECTIVE:
                    return new ECFieldElement[] { one };
                case ECCurve.COORD_JACOBIAN_CHUDNOVSKY:
                    return new ECFieldElement[] { one, one, one };
                case ECCurve.COORD_JACOBIAN_MODIFIED:
                    return new ECFieldElement[] { one, curve.A };
                default:
                    throw new ArgumentException("unknown coordinate system");
            }
        }
예제 #8
0
        public X9ECParameters(
            Asn1Sequence seq)
        {
            if (!(seq[0] is DerInteger)
               || !((DerInteger) seq[0]).Value.Equals(BigInteger.One))
            {
                throw new ArgumentException("bad version in X9ECParameters");
            }

            X9Curve x9c = new X9Curve(
                X9FieldID.GetInstance(seq[1]),
                Asn1Sequence.GetInstance(seq[2]));

            this.curve = x9c.Curve;
            object p = seq[3];

            if (p is X9ECPoint)
            {
                this.g = ((X9ECPoint)p);
            }
            else
            {
                this.g = new X9ECPoint(curve, (Asn1OctetString)p);
            }

            this.n = ((DerInteger)seq[4]).Value;
            this.seed = x9c.GetSeed();

            if (seq.Count == 6)
            {
                this.h = ((DerInteger)seq[5]).Value;
            }
        }
예제 #9
0
 internal ECPoint(ECCurve curve, ECFieldElement x, ECFieldElement y, ECFieldElement[] zs, bool withCompression)
 {
     this.m_curve = curve;
     this.m_x = x;
     this.m_y = y;
     this.m_zs = zs;
     this.m_withCompression = withCompression;
 }
예제 #10
0
        public ECDomainParameters(
            ECCurve     curve,
            ECPoint     g,
            BigInteger  n,
            BigInteger  h)
			: this(curve, g, n, h, null)
		{
        }
예제 #11
0
 public X9ECParameters(
     ECCurve     curve,
     X9ECPoint   g,
     BigInteger  n,
     BigInteger  h)
     : this(curve, g, n, h, null)
 {
 }
예제 #12
0
 public X9ECParameters(
     ECCurve		curve,
     ECPoint		g,
     BigInteger	n,
     BigInteger	h,
     byte[]		seed)
     : this(curve, new X9ECPoint(g), n, h, seed)
 {
 }
예제 #13
0
		public X9Curve(
            X9FieldID		fieldID,
            Asn1Sequence	seq)
        {
			if (fieldID == null)
				throw new ArgumentNullException("fieldID");
			if (seq == null)
				throw new ArgumentNullException("seq");

			this.fieldIdentifier = fieldID.Identifier;

			if (fieldIdentifier.Equals(X9ObjectIdentifiers.PrimeField))
            {
                BigInteger q = ((DerInteger) fieldID.Parameters).Value;
                X9FieldElement x9A = new X9FieldElement(q, (Asn1OctetString) seq[0]);
                X9FieldElement x9B = new X9FieldElement(q, (Asn1OctetString) seq[1]);
                curve = new FpCurve(q, x9A.Value.ToBigInteger(), x9B.Value.ToBigInteger());
            }
            else
            {
				if (fieldIdentifier.Equals(X9ObjectIdentifiers.CharacteristicTwoField)) 
				{
					// Characteristic two field
					DerSequence parameters = (DerSequence)fieldID.Parameters;
					int m = ((DerInteger)parameters[0]).Value.IntValue;
					DerObjectIdentifier representation
						= (DerObjectIdentifier)parameters[1];

					int k1 = 0;
					int k2 = 0;
					int k3 = 0;
					if (representation.Equals(X9ObjectIdentifiers.TPBasis)) 
					{
						// Trinomial basis representation
						k1 = ((DerInteger)parameters[2]).Value.IntValue;
					}
					else 
					{
						// Pentanomial basis representation
						DerSequence pentanomial = (DerSequence) parameters[2];
						k1 = ((DerInteger) pentanomial[0]).Value.IntValue;
						k2 = ((DerInteger) pentanomial[1]).Value.IntValue;
						k3 = ((DerInteger) pentanomial[2]).Value.IntValue;
					}
					X9FieldElement x9A = new X9FieldElement(m, k1, k2, k3, (Asn1OctetString)seq[0]);
					X9FieldElement x9B = new X9FieldElement(m, k1, k2, k3, (Asn1OctetString)seq[1]);
					// TODO Is it possible to get the order (n) and cofactor(h) too?
					curve = new F2mCurve(m, k1, k2, k3, x9A.Value.ToBigInteger(), x9B.Value.ToBigInteger());
				}
			}

			if (seq.Count == 3)
            {
                seed = ((DerBitString) seq[2]).GetBytes();
            }
        }
예제 #14
0
        protected internal ECPoint(ECCurve curve, ECFieldElement x, ECFieldElement y, bool withCompression)
        {
            if (curve == null)
                throw new ArgumentNullException("curve");

            _curve = curve;
            _x = x;
            _y = y;
            _withCompression = withCompression;
        }
예제 #15
0
		public X9ECParameters (
			ECCurve		curve,
			ECPoint		g,
			BigInteger	n,
			BigInteger	h,
			byte[]		seed)
		{
			this.curve = curve;
			this.g = g;
			this.n = n;
			this.h = h;
			this.seed = seed;
		}
        public ECDomainParameters(ECCurve curve, ECPoint g, IBigInteger n, IBigInteger h, byte[] seed)
        {
            if (curve == null)
                throw new ArgumentNullException("curve");
            if (g == null)
                throw new ArgumentNullException("g");
            if (n == null)
                throw new ArgumentNullException("n");
            if (h == null)
                throw new ArgumentNullException("h");

            _curve = curve;
            _g = g;
            _n = n;
            _h = h;
            _seed = Arrays.Clone(seed);
        }
예제 #17
0
        public X9ECParameters(
            Asn1Sequence seq)
        {
            if (!(seq[0] is DerInteger)
               || !((DerInteger) seq[0]).Value.Equals(BigInteger.One))
            {
                throw new ArgumentException("bad version in X9ECParameters");
            }

            X9Curve x9c = null;
            if (seq[2] is X9Curve)
            {
                x9c = (X9Curve) seq[2];
            }
            else
            {
                x9c = new X9Curve(
                    new X9FieldID(
                        (Asn1Sequence) seq[1]),
                        (Asn1Sequence) seq[2]);
            }

            this.curve = x9c.Curve;

            if (seq[3] is X9ECPoint)
            {
                this.g = ((X9ECPoint) seq[3]).Point;
            }
            else
            {
                this.g = new X9ECPoint(curve, (Asn1OctetString) seq[3]).Point;
            }

            this.n = ((DerInteger) seq[4]).Value;
            this.seed = x9c.GetSeed();

            if (seq.Count == 6)
            {
                this.h = ((DerInteger) seq[5]).Value;
            }
            else
            {
                this.h = BigInteger.One;
            }
        }
예제 #18
0
		public ECDomainParameters(
            ECCurve     curve,
            ECPoint     g,
            BigInteger  n,
            BigInteger  h,
            byte[]      seed)
        {
			if (curve == null)
				throw new ArgumentNullException("curve");
			if (g == null)
				throw new ArgumentNullException("g");
			if (n == null)
				throw new ArgumentNullException("n");
			if (h == null)
				throw new ArgumentNullException("h");

			this.curve = curve;
            this.g = g;
            this.n = n;
            this.h = h;
            this.seed = Arrays.Clone(seed);
        }
예제 #19
0
        public X9ECParameters(
            ECCurve		curve,
            ECPoint		g,
            BigInteger	n,
            BigInteger	h,
            byte[]		seed)
        {
            this.curve = curve;
            this.g = g.Normalize();
            this.n = n;
            this.h = h;
            this.seed = seed;

            if (ECAlgorithms.IsFpCurve(curve))
            {
                this.fieldID = new X9FieldID(curve.Field.Characteristic);
            }
            else if (ECAlgorithms.IsF2mCurve(curve))
            {
                IPolynomialExtensionField field = (IPolynomialExtensionField)curve.Field;
                int[] exponents = field.MinimalPolynomial.GetExponentsPresent();
                if (exponents.Length == 3)
                {
                    this.fieldID = new X9FieldID(exponents[2], exponents[1]);
                }
                else if (exponents.Length == 5)
                {
                    this.fieldID = new X9FieldID(exponents[4], exponents[1], exponents[2], exponents[3]);
                }
                else
                {
                    throw new ArgumentException("Only trinomial and pentomial curves are supported");
                }
            }
            else
            {
                throw new ArgumentException("'curve' is of an unsupported type");
            }
        }
예제 #20
0
        /// <summary>
        /// Hashes a seed t into a point T on the curve. Returns null if t is unsuitable.
        /// </summary>
        /// <param name="curve">The elliptic curve in Weierstrass form</param>
        /// <param name="t">The seed</param>
        /// <returns>A random point T uniquely determined by seed t, otherwise null</returns>
        public static ECPoint?HashToWeierstrassCurve(ECCurve curve, byte[] t)
        {
            ECFieldElement x, ax, x3, y, y2;

            BigInteger P      = curve.Field.Characteristic;
            SHA256?    sha256 = SHA256.Create();
            BigInteger hash   = new BigInteger(sha256.ComputeHash(t));

            // Check that the hash is within valid range
            if (hash.CompareTo(BigInteger.One) < 0 || hash.CompareTo(P) >= 0)
            {
                return(null);
            }

            // A valid point (x,y) must satisfy: y^2 = x^3 + Ax + B mod P
            // Convert hash from BigInt to FieldElement x modulo P
            x  = curve.FromBigInteger(hash);        // x
            ax = x.Multiply(curve.A);               // Ax
            x3 = x.Square().Multiply(x);            // x^3 = x^2 * x
            y2 = x3.Add(ax).Add(curve.B);           // y^2 = x^3 + Ax + B
            y  = y2.Sqrt();                         // y = sqrt(x^3 + Ax + B)

            // y == null if square root mod P does not exist
            if (y == null)
            {
                return(null);
            }

            ECPoint T = curve.CreatePoint(x.ToBigInteger(), y.ToBigInteger());

            // Use the built-in point validator, which also checks for membership
            // in weak subgroups
            if (!T.IsValid())
            {
                return(null);
            }

            return(T);
        }
예제 #21
0
		public X9Curve(
            ECCurve	curve,
            byte[]	seed)
        {
			if (curve == null)
				throw new ArgumentNullException("curve");

			this.curve = curve;
            this.seed = Arrays.Clone(seed);

			if (curve is FpCurve)
			{
				this.fieldIdentifier = X9ObjectIdentifiers.PrimeField;
			}
			else if (curve is F2mCurve)
			{
				this.fieldIdentifier = X9ObjectIdentifiers.CharacteristicTwoField;
			}
			else
			{
				throw new ArgumentException("This type of ECCurve is not implemented");
			}
		}
		public X9ECParameters(
            ECCurve		curve,
            ECPoint		g,
            BigInteger	n,
            BigInteger	h,
            byte[]		seed)
        {
            this.curve = curve;
            this.g = g;
            this.n = n;
            this.h = h;
            this.seed = seed;

			if (curve is FpCurve)
			{
				this.fieldID = new X9FieldID(((FpCurve) curve).Q);
			}
			else if (curve is F2mCurve)
			{
				F2mCurve curveF2m = (F2mCurve) curve;
				this.fieldID = new X9FieldID(curveF2m.M, curveF2m.K1,
					curveF2m.K2, curveF2m.K3);
			}
        }
예제 #23
0
        public static bool IsF2mCurve(ECCurve c)
        {
            IFiniteField field = c.Field;

            return(field.Dimension > 1 && field.Characteristic.Equals(BigInteger.Two) && field is IPolynomialExtensionField);
        }
예제 #24
0
 internal DefaultLookupTable(ECCurve outer, byte[] table, int size)
 {
     this.m_outer = outer;
     this.m_table = table;
     this.m_size  = size;
 }
예제 #25
0
 public static bool IsFpCurve(ECCurve c)
 {
     return(c.Field.Dimension == 1);
 }
예제 #26
0
 /**
  * Create a point that encodes with or without point compresion.
  *
  * @param curve the curve to use
  * @param x affine x co-ordinate
  * @param y affine y co-ordinate
  * @param withCompression if true encode with point compression
  */
 public FpPoint(ECCurve curve, ECFieldElement x, ECFieldElement y, bool withCompression)
     : base(curve, x, y, withCompression)
 {
     if ((x == null) != (y == null))
         throw new ArgumentException("Exactly one of the field elements is null");
 }
예제 #27
0
 public F2MPoint(
     ECCurve curve)
     : this(curve, null, null)
 {
 }
예제 #28
0
 public F2mPoint(
     ECCurve curve)
     : this(curve, null, null)
 {
 }
		public static int GetByteLength(
			ECCurve c)
		{
			return (c.FieldSize + 7) / 8;
		}
예제 #30
0
        public override ECPoint TwicePlus(ECPoint b)
        {
            if (base.IsInfinity)
            {
                return(b);
            }
            if (b.IsInfinity)
            {
                return(this.Twice());
            }
            ECCurve        curve     = this.Curve;
            ECFieldElement rawXCoord = base.RawXCoord;

            if (rawXCoord.IsZero)
            {
                return(b);
            }
            int coordinateSystem = curve.CoordinateSystem;
            int num = coordinateSystem;

            if (num != 6)
            {
                return(this.Twice().Add(b));
            }
            ECFieldElement rawXCoord2     = b.RawXCoord;
            ECFieldElement eCFieldElement = b.RawZCoords[0];

            if (rawXCoord2.IsZero || !eCFieldElement.IsOne)
            {
                return(this.Twice().Add(b));
            }
            ECFieldElement rawYCoord       = base.RawYCoord;
            ECFieldElement eCFieldElement2 = base.RawZCoords[0];
            ECFieldElement rawYCoord2      = b.RawYCoord;
            ECFieldElement x  = rawXCoord.Square();
            ECFieldElement b2 = rawYCoord.Square();
            ECFieldElement eCFieldElement3 = eCFieldElement2.Square();
            ECFieldElement b3 = rawYCoord.Multiply(eCFieldElement2);
            ECFieldElement b4 = curve.A.Multiply(eCFieldElement3).Add(b2).Add(b3);
            ECFieldElement eCFieldElement4 = rawYCoord2.AddOne();
            ECFieldElement eCFieldElement5 = curve.A.Add(eCFieldElement4).Multiply(eCFieldElement3).Add(b2).MultiplyPlusProduct(b4, x, eCFieldElement3);
            ECFieldElement eCFieldElement6 = rawXCoord2.Multiply(eCFieldElement3);
            ECFieldElement eCFieldElement7 = eCFieldElement6.Add(b4).Square();

            if (eCFieldElement7.IsZero)
            {
                if (eCFieldElement5.IsZero)
                {
                    return(b.Twice());
                }
                return(curve.Infinity);
            }
            else
            {
                if (eCFieldElement5.IsZero)
                {
                    return(new F2mPoint(curve, eCFieldElement5, curve.B.Sqrt(), base.IsCompressed));
                }
                ECFieldElement x2 = eCFieldElement5.Square().Multiply(eCFieldElement6);
                ECFieldElement eCFieldElement8 = eCFieldElement5.Multiply(eCFieldElement7).Multiply(eCFieldElement3);
                ECFieldElement y = eCFieldElement5.Add(eCFieldElement7).Square().MultiplyPlusProduct(b4, eCFieldElement4, eCFieldElement8);
                return(new F2mPoint(curve, x2, y, new ECFieldElement[]
                {
                    eCFieldElement8
                }, base.IsCompressed));
            }
        }
예제 #31
0
 protected internal ECPointBase(ECCurve curve, ECFieldElement x, ECFieldElement y, bool withCompression)
     : base(curve, x, y, withCompression)
 {
 }
예제 #32
0
 protected ECPoint(ECCurve curve, ECFieldElement	x, ECFieldElement y, bool withCompression)
     : this(curve, x, y, GetInitialZCoords(curve), withCompression)
 {
 }
예제 #33
0
 public static bool IsFpCurve(ECCurve c)
 {
     return(IsFpField(c.Field));
 }
예제 #34
0
        public override ECPoint Add(ECPoint b)
        {
            if (base.IsInfinity)
            {
                return(b);
            }
            if (b.IsInfinity)
            {
                return(this);
            }
            ECCurve        curve            = this.Curve;
            int            coordinateSystem = curve.CoordinateSystem;
            ECFieldElement rawXCoord        = base.RawXCoord;
            ECFieldElement rawXCoord2       = b.RawXCoord;
            int            num = coordinateSystem;

            switch (num)
            {
            case 0:
            {
                ECFieldElement rawYCoord       = base.RawYCoord;
                ECFieldElement rawYCoord2      = b.RawYCoord;
                ECFieldElement eCFieldElement  = rawXCoord.Add(rawXCoord2);
                ECFieldElement eCFieldElement2 = rawYCoord.Add(rawYCoord2);
                if (!eCFieldElement.IsZero)
                {
                    ECFieldElement eCFieldElement3 = eCFieldElement2.Divide(eCFieldElement);
                    ECFieldElement eCFieldElement4 = eCFieldElement3.Square().Add(eCFieldElement3).Add(eCFieldElement).Add(curve.A);
                    ECFieldElement y = eCFieldElement3.Multiply(rawXCoord.Add(eCFieldElement4)).Add(eCFieldElement4).Add(rawYCoord);
                    return(new F2mPoint(curve, eCFieldElement4, y, base.IsCompressed));
                }
                if (eCFieldElement2.IsZero)
                {
                    return(this.Twice());
                }
                return(curve.Infinity);
            }

            case 1:
            {
                ECFieldElement rawYCoord3      = base.RawYCoord;
                ECFieldElement eCFieldElement5 = base.RawZCoords[0];
                ECFieldElement rawYCoord4      = b.RawYCoord;
                ECFieldElement eCFieldElement6 = b.RawZCoords[0];
                bool           isOne           = eCFieldElement5.IsOne;
                ECFieldElement eCFieldElement7 = rawYCoord4;
                ECFieldElement eCFieldElement8 = rawXCoord2;
                if (!isOne)
                {
                    eCFieldElement7 = eCFieldElement7.Multiply(eCFieldElement5);
                    eCFieldElement8 = eCFieldElement8.Multiply(eCFieldElement5);
                }
                bool           isOne2           = eCFieldElement6.IsOne;
                ECFieldElement eCFieldElement9  = rawYCoord3;
                ECFieldElement eCFieldElement10 = rawXCoord;
                if (!isOne2)
                {
                    eCFieldElement9  = eCFieldElement9.Multiply(eCFieldElement6);
                    eCFieldElement10 = eCFieldElement10.Multiply(eCFieldElement6);
                }
                ECFieldElement eCFieldElement11 = eCFieldElement7.Add(eCFieldElement9);
                ECFieldElement eCFieldElement12 = eCFieldElement8.Add(eCFieldElement10);
                if (!eCFieldElement12.IsZero)
                {
                    ECFieldElement eCFieldElement13 = eCFieldElement12.Square();
                    ECFieldElement eCFieldElement14 = eCFieldElement13.Multiply(eCFieldElement12);
                    ECFieldElement b2 = isOne ? eCFieldElement6 : (isOne2 ? eCFieldElement5 : eCFieldElement5.Multiply(eCFieldElement6));
                    ECFieldElement eCFieldElement15 = eCFieldElement11.Add(eCFieldElement12);
                    ECFieldElement eCFieldElement16 = eCFieldElement15.MultiplyPlusProduct(eCFieldElement11, eCFieldElement13, curve.A).Multiply(b2).Add(eCFieldElement14);
                    ECFieldElement x  = eCFieldElement12.Multiply(eCFieldElement16);
                    ECFieldElement b3 = isOne2 ? eCFieldElement13 : eCFieldElement13.Multiply(eCFieldElement6);
                    ECFieldElement y2 = eCFieldElement11.MultiplyPlusProduct(rawXCoord, eCFieldElement12, rawYCoord3).MultiplyPlusProduct(b3, eCFieldElement15, eCFieldElement16);
                    ECFieldElement eCFieldElement17 = eCFieldElement14.Multiply(b2);
                    return(new F2mPoint(curve, x, y2, new ECFieldElement[]
                        {
                            eCFieldElement17
                        }, base.IsCompressed));
                }
                if (eCFieldElement11.IsZero)
                {
                    return(this.Twice());
                }
                return(curve.Infinity);
            }

            default:
                if (num != 6)
                {
                    throw new InvalidOperationException("unsupported coordinate system");
                }
                if (rawXCoord.IsZero)
                {
                    if (rawXCoord2.IsZero)
                    {
                        return(curve.Infinity);
                    }
                    return(b.Add(this));
                }
                else
                {
                    ECFieldElement rawYCoord5       = base.RawYCoord;
                    ECFieldElement eCFieldElement18 = base.RawZCoords[0];
                    ECFieldElement rawYCoord6       = b.RawYCoord;
                    ECFieldElement eCFieldElement19 = b.RawZCoords[0];
                    bool           isOne3           = eCFieldElement18.IsOne;
                    ECFieldElement eCFieldElement20 = rawXCoord2;
                    ECFieldElement eCFieldElement21 = rawYCoord6;
                    if (!isOne3)
                    {
                        eCFieldElement20 = eCFieldElement20.Multiply(eCFieldElement18);
                        eCFieldElement21 = eCFieldElement21.Multiply(eCFieldElement18);
                    }
                    bool           isOne4           = eCFieldElement19.IsOne;
                    ECFieldElement eCFieldElement22 = rawXCoord;
                    ECFieldElement eCFieldElement23 = rawYCoord5;
                    if (!isOne4)
                    {
                        eCFieldElement22 = eCFieldElement22.Multiply(eCFieldElement19);
                        eCFieldElement23 = eCFieldElement23.Multiply(eCFieldElement19);
                    }
                    ECFieldElement eCFieldElement24 = eCFieldElement23.Add(eCFieldElement21);
                    ECFieldElement eCFieldElement25 = eCFieldElement22.Add(eCFieldElement20);
                    if (!eCFieldElement25.IsZero)
                    {
                        ECFieldElement eCFieldElement27;
                        ECFieldElement y3;
                        ECFieldElement eCFieldElement29;
                        if (rawXCoord2.IsZero)
                        {
                            ECPoint eCPoint = this.Normalize();
                            rawXCoord = eCPoint.RawXCoord;
                            ECFieldElement yCoord           = eCPoint.YCoord;
                            ECFieldElement b4               = rawYCoord6;
                            ECFieldElement eCFieldElement26 = yCoord.Add(b4).Divide(rawXCoord);
                            eCFieldElement27 = eCFieldElement26.Square().Add(eCFieldElement26).Add(rawXCoord).Add(curve.A);
                            if (eCFieldElement27.IsZero)
                            {
                                return(new F2mPoint(curve, eCFieldElement27, curve.B.Sqrt(), base.IsCompressed));
                            }
                            ECFieldElement eCFieldElement28 = eCFieldElement26.Multiply(rawXCoord.Add(eCFieldElement27)).Add(eCFieldElement27).Add(yCoord);
                            y3 = eCFieldElement28.Divide(eCFieldElement27).Add(eCFieldElement27);
                            eCFieldElement29 = curve.FromBigInteger(BigInteger.One);
                        }
                        else
                        {
                            eCFieldElement25 = eCFieldElement25.Square();
                            ECFieldElement eCFieldElement30 = eCFieldElement24.Multiply(eCFieldElement22);
                            ECFieldElement eCFieldElement31 = eCFieldElement24.Multiply(eCFieldElement20);
                            eCFieldElement27 = eCFieldElement30.Multiply(eCFieldElement31);
                            if (eCFieldElement27.IsZero)
                            {
                                return(new F2mPoint(curve, eCFieldElement27, curve.B.Sqrt(), base.IsCompressed));
                            }
                            ECFieldElement eCFieldElement32 = eCFieldElement24.Multiply(eCFieldElement25);
                            if (!isOne4)
                            {
                                eCFieldElement32 = eCFieldElement32.Multiply(eCFieldElement19);
                            }
                            y3 = eCFieldElement31.Add(eCFieldElement25).SquarePlusProduct(eCFieldElement32, rawYCoord5.Add(eCFieldElement18));
                            eCFieldElement29 = eCFieldElement32;
                            if (!isOne3)
                            {
                                eCFieldElement29 = eCFieldElement29.Multiply(eCFieldElement18);
                            }
                        }
                        return(new F2mPoint(curve, eCFieldElement27, y3, new ECFieldElement[]
                        {
                            eCFieldElement29
                        }, base.IsCompressed));
                    }
                    if (eCFieldElement24.IsZero)
                    {
                        return(this.Twice());
                    }
                    return(curve.Infinity);
                }
                break;
            }
        }
예제 #35
0
 protected internal ECPointBase(ECCurve curve, ECFieldElement x, ECFieldElement y, ECFieldElement[] zs, bool withCompression)
     : base(curve, x, y, zs, withCompression)
 {
 }
예제 #36
0
 protected AbstractFpPoint(ECCurve curve, ECFieldElement x, ECFieldElement y, bool withCompression) : base(curve, x, y, withCompression)
 {
 }
예제 #37
0
 /**
  * @param curve base curve
  * @param x x point
  * @param y y point
  */
 public F2MPoint(ECCurve curve, ECFieldElement x, ECFieldElement y)
     : this(curve, x, y, false)
 {
 }
예제 #38
0
        /**
         * @param curve base curve
         * @param x x point
         * @param y y point
         * @param withCompression true if encode with point compression.
         */
        public F2mPoint(
            ECCurve			curve,
            ECFieldElement	x,
            ECFieldElement	y,
            bool			withCompression)
            : base(curve, x, y, withCompression)
        {
            if ((x == null) != (y == null))
            {
                throw new ArgumentException("Exactly one of the field elements is null");
            }

            if (x != null)
            {
                // Check if x and y are elements of the same field
                F2mFieldElement.CheckFieldElements(x, y);

                // Check if x and a are elements of the same field
                if (curve != null)
                {
                    F2mFieldElement.CheckFieldElements(x, curve.A);
                }
            }
        }
예제 #39
0
        internal static ECPoint ImplSumOfMultiplies(ECPoint[] ps, BigInteger[] ks)
        {
            int count = ps.Length;

            int[]             widths = new int[count];
            WNafPreCompInfo[] infos  = new WNafPreCompInfo[count];
            byte[][]          wnafs  = new byte[count][];

            int len = 0;

            for (int i = 0; i < count; ++i)
            {
                widths[i] = System.Math.Max(2, System.Math.Min(16, WNafUtilities.GetWindowSize(ks[i].BitLength)));
                infos[i]  = WNafUtilities.Precompute(ps[i], widths[i], true);
                wnafs[i]  = WNafUtilities.GenerateWindowNaf(widths[i], ks[i]);
                len       = System.Math.Max(len, wnafs[i].Length);
            }

            ECCurve curve    = ps[0].Curve;
            ECPoint infinity = curve.Infinity;

            ECPoint R      = infinity;
            int     zeroes = 0;

            for (int i = len - 1; i >= 0; --i)
            {
                ECPoint r = infinity;

                for (int j = 0; j < count; ++j)
                {
                    byte[] wnaf = wnafs[j];
                    int    wi   = i < wnaf.Length ? (int)(sbyte)wnaf[i] : 0;
                    if (wi != 0)
                    {
                        int             n     = System.Math.Abs(wi);
                        WNafPreCompInfo info  = infos[j];
                        ECPoint[]       table = wi < 0 ? info.PreCompNeg : info.PreComp;
                        r = r.Add(table[n >> 1]);
                    }
                }

                if (r == infinity)
                {
                    ++zeroes;
                    continue;
                }

                if (zeroes > 0)
                {
                    R      = R.TimesPow2(zeroes);
                    zeroes = 0;
                }

                R = R.TwicePlus(r);
            }

            if (zeroes > 0)
            {
                R = R.TimesPow2(zeroes);
            }

            return(R);
        }
예제 #40
0
 internal F2mPoint(ECCurve curve, ECFieldElement x, ECFieldElement y, ECFieldElement[] zs, bool withCompression) : base(curve, x, y, zs, withCompression)
 {
 }
예제 #41
0
        internal static ECPoint ImplShamirsTrickWNaf(ECPoint P, BigInteger k, ECPoint Q, BigInteger l)
        {
            int widthP = System.Math.Max(2, System.Math.Min(16, WNafUtilities.GetWindowSize(k.BitLength)));
            int widthQ = System.Math.Max(2, System.Math.Min(16, WNafUtilities.GetWindowSize(l.BitLength)));

            WNafPreCompInfo infoP = WNafUtilities.Precompute(P, widthP, true);
            WNafPreCompInfo infoQ = WNafUtilities.Precompute(Q, widthQ, true);

            ECPoint[] preCompP    = infoP.PreComp;
            ECPoint[] preCompQ    = infoQ.PreComp;
            ECPoint[] preCompNegP = infoP.PreCompNeg;
            ECPoint[] preCompNegQ = infoQ.PreCompNeg;

            byte[] wnafP = WNafUtilities.GenerateWindowNaf(widthP, k);
            byte[] wnafQ = WNafUtilities.GenerateWindowNaf(widthQ, l);

            int len = System.Math.Max(wnafP.Length, wnafQ.Length);

            ECCurve curve    = P.Curve;
            ECPoint infinity = curve.Infinity;

            ECPoint R      = infinity;
            int     zeroes = 0;

            for (int i = len - 1; i >= 0; --i)
            {
                int wiP = i < wnafP.Length ? (int)(sbyte)wnafP[i] : 0;
                int wiQ = i < wnafQ.Length ? (int)(sbyte)wnafQ[i] : 0;

                if ((wiP | wiQ) == 0)
                {
                    ++zeroes;
                    continue;
                }

                ECPoint r = infinity;
                if (wiP != 0)
                {
                    int       nP     = System.Math.Abs(wiP);
                    ECPoint[] tableP = wiP < 0 ? preCompNegP : preCompP;
                    r = r.Add(tableP[nP >> 1]);
                }
                if (wiQ != 0)
                {
                    int       nQ     = System.Math.Abs(wiQ);
                    ECPoint[] tableQ = wiQ < 0 ? preCompNegQ : preCompQ;
                    r = r.Add(tableQ[nQ >> 1]);
                }

                if (zeroes > 0)
                {
                    R      = R.TimesPow2(zeroes);
                    zeroes = 0;
                }

                R = R.TwicePlus(r);
            }

            if (zeroes > 0)
            {
                R = R.TimesPow2(zeroes);
            }

            return(R);
        }
예제 #42
0
 /**
  * Create a point which encodes with point compression.
  *
  * @param curve the curve to use
  * @param x affine x co-ordinate
  * @param y affine y co-ordinate
  */
 public FpPoint(ECCurve curve, ECFieldElement x, ECFieldElement y)
     : this(curve, x, y, false)
 {
 }
예제 #43
0
        private static ECPoint ImplShamirsTrickFixedPoint(ECPoint p, BigInteger k, ECPoint q, BigInteger l)
        {
            ECCurve c        = p.Curve;
            int     combSize = FixedPointUtilities.GetCombSize(c);

            if (k.BitLength > combSize || l.BitLength > combSize)
            {
                /*
                 * TODO The comb works best when the scalars are less than the (possibly unknown) order.
                 * Still, if we want to handle larger scalars, we could allow customization of the comb
                 * size, or alternatively we could deal with the 'extra' bits either by running the comb
                 * multiple times as necessary, or by using an alternative multiplier as prelude.
                 */
                throw new InvalidOperationException("fixed-point comb doesn't support scalars larger than the curve order");
            }

            FixedPointPreCompInfo infoP = FixedPointUtilities.Precompute(p);
            FixedPointPreCompInfo infoQ = FixedPointUtilities.Precompute(q);

            ECLookupTable lookupTableP = infoP.LookupTable;
            ECLookupTable lookupTableQ = infoQ.LookupTable;

            int widthP = infoP.Width;
            int widthQ = infoQ.Width;

            // TODO This shouldn't normally happen, but a better "solution" is desirable anyway
            if (widthP != widthQ)
            {
                FixedPointCombMultiplier m = new FixedPointCombMultiplier();
                ECPoint r1 = m.Multiply(p, k);
                ECPoint r2 = m.Multiply(q, l);
                return(r1.Add(r2));
            }

            int width = widthP;

            int d = (combSize + width - 1) / width;

            ECPoint R = c.Infinity;

            int fullComb = d * width;

            uint[] K = Nat.FromBigInteger(fullComb, k);
            uint[] L = Nat.FromBigInteger(fullComb, l);

            int top = fullComb - 1;

            for (int i = 0; i < d; ++i)
            {
                uint secretIndexK = 0, secretIndexL = 0;

                for (int j = top - i; j >= 0; j -= d)
                {
                    uint secretBitK = K[j >> 5] >> (j & 0x1F);
                    secretIndexK  ^= secretBitK >> 1;
                    secretIndexK <<= 1;
                    secretIndexK  ^= secretBitK;

                    uint secretBitL = L[j >> 5] >> (j & 0x1F);
                    secretIndexL  ^= secretBitL >> 1;
                    secretIndexL <<= 1;
                    secretIndexL  ^= secretBitL;
                }

                ECPoint addP = lookupTableP.LookupVar((int)secretIndexK);
                ECPoint addQ = lookupTableQ.LookupVar((int)secretIndexL);

                ECPoint T = addP.Add(addQ);

                R = R.TwicePlus(T);
            }

            return(R.Add(infoP.Offset).Add(infoQ.Offset));
        }
예제 #44
0
 internal FpPoint(ECCurve curve, ECFieldElement x, ECFieldElement y, ECFieldElement[] zs, bool withCompression)
     : base(curve, x, y, zs, withCompression)
 {
 }
예제 #45
0
		protected bool Equals(
			ECCurve other)
		{
			return a.Equals(other.a) && b.Equals(other.b);
		}
예제 #46
0
 private static ECCurve ConfigureCurveGlv(ECCurve c, GlvTypeBParameters p)
 {
     return c.Configure().SetEndomorphism(new GlvTypeBEndomorphism(c, p)).Create();
 }
예제 #47
0
 private static ECCurve ConfigureCurve(ECCurve curve)
 {
     return curve;
 }
예제 #48
0
        public override ECPoint Twice()
        {
            if (base.IsInfinity)
            {
                return(this);
            }
            ECCurve        curve     = this.Curve;
            ECFieldElement rawXCoord = base.RawXCoord;

            if (rawXCoord.IsZero)
            {
                return(curve.Infinity);
            }
            int coordinateSystem = curve.CoordinateSystem;
            int num = coordinateSystem;

            switch (num)
            {
            case 0:
            {
                ECFieldElement rawYCoord      = base.RawYCoord;
                ECFieldElement eCFieldElement = rawYCoord.Divide(rawXCoord).Add(rawXCoord);
                ECFieldElement x = eCFieldElement.Square().Add(eCFieldElement).Add(curve.A);
                ECFieldElement y = rawXCoord.SquarePlusProduct(x, eCFieldElement.AddOne());
                return(new F2mPoint(curve, x, y, base.IsCompressed));
            }

            case 1:
            {
                ECFieldElement rawYCoord2      = base.RawYCoord;
                ECFieldElement eCFieldElement2 = base.RawZCoords[0];
                bool           isOne           = eCFieldElement2.IsOne;
                ECFieldElement eCFieldElement3 = isOne ? rawXCoord : rawXCoord.Multiply(eCFieldElement2);
                ECFieldElement b = isOne ? rawYCoord2 : rawYCoord2.Multiply(eCFieldElement2);
                ECFieldElement eCFieldElement4 = rawXCoord.Square();
                ECFieldElement eCFieldElement5 = eCFieldElement4.Add(b);
                ECFieldElement eCFieldElement6 = eCFieldElement3;
                ECFieldElement eCFieldElement7 = eCFieldElement6.Square();
                ECFieldElement eCFieldElement8 = eCFieldElement5.Add(eCFieldElement6);
                ECFieldElement eCFieldElement9 = eCFieldElement8.MultiplyPlusProduct(eCFieldElement5, eCFieldElement7, curve.A);
                ECFieldElement x2 = eCFieldElement6.Multiply(eCFieldElement9);
                ECFieldElement y2 = eCFieldElement4.Square().MultiplyPlusProduct(eCFieldElement6, eCFieldElement9, eCFieldElement8);
                ECFieldElement eCFieldElement10 = eCFieldElement6.Multiply(eCFieldElement7);
                return(new F2mPoint(curve, x2, y2, new ECFieldElement[]
                    {
                        eCFieldElement10
                    }, base.IsCompressed));
            }

            default:
            {
                if (num != 6)
                {
                    throw new InvalidOperationException("unsupported coordinate system");
                }
                ECFieldElement rawYCoord3       = base.RawYCoord;
                ECFieldElement eCFieldElement11 = base.RawZCoords[0];
                bool           isOne2           = eCFieldElement11.IsOne;
                ECFieldElement eCFieldElement12 = isOne2 ? rawYCoord3 : rawYCoord3.Multiply(eCFieldElement11);
                ECFieldElement eCFieldElement13 = isOne2 ? eCFieldElement11 : eCFieldElement11.Square();
                ECFieldElement a = curve.A;
                ECFieldElement eCFieldElement14 = isOne2 ? a : a.Multiply(eCFieldElement13);
                ECFieldElement eCFieldElement15 = rawYCoord3.Square().Add(eCFieldElement12).Add(eCFieldElement14);
                if (eCFieldElement15.IsZero)
                {
                    return(new F2mPoint(curve, eCFieldElement15, curve.B.Sqrt(), base.IsCompressed));
                }
                ECFieldElement eCFieldElement16 = eCFieldElement15.Square();
                ECFieldElement eCFieldElement17 = isOne2 ? eCFieldElement15 : eCFieldElement15.Multiply(eCFieldElement13);
                ECFieldElement b2 = curve.B;
                ECFieldElement eCFieldElement19;
                if (b2.BitLength < curve.FieldSize >> 1)
                {
                    ECFieldElement eCFieldElement18 = rawYCoord3.Add(rawXCoord).Square();
                    ECFieldElement b3;
                    if (b2.IsOne)
                    {
                        b3 = eCFieldElement14.Add(eCFieldElement13).Square();
                    }
                    else
                    {
                        b3 = eCFieldElement14.SquarePlusProduct(b2, eCFieldElement13.Square());
                    }
                    eCFieldElement19 = eCFieldElement18.Add(eCFieldElement15).Add(eCFieldElement13).Multiply(eCFieldElement18).Add(b3).Add(eCFieldElement16);
                    if (a.IsZero)
                    {
                        eCFieldElement19 = eCFieldElement19.Add(eCFieldElement17);
                    }
                    else if (!a.IsOne)
                    {
                        eCFieldElement19 = eCFieldElement19.Add(a.AddOne().Multiply(eCFieldElement17));
                    }
                }
                else
                {
                    ECFieldElement eCFieldElement20 = isOne2 ? rawXCoord : rawXCoord.Multiply(eCFieldElement11);
                    eCFieldElement19 = eCFieldElement20.SquarePlusProduct(eCFieldElement15, eCFieldElement12).Add(eCFieldElement16).Add(eCFieldElement17);
                }
                return(new F2mPoint(curve, eCFieldElement16, eCFieldElement19, new ECFieldElement[]
                    {
                        eCFieldElement17
                    }, base.IsCompressed));
            }
            }
        }
예제 #49
-1
 public X9ECPoint(ECCurve c, Asn1OctetString s)
     : this(c, s.GetOctets())
 {
 }