public GlvMultiplier(ECCurve curve, GlvEndomorphism glvEndomorphism)
        {
            if (curve == null || curve.Order == null)
                throw new ArgumentException("Need curve with known group order", "curve");

            this.curve = curve;
            this.glvEndomorphism = glvEndomorphism;
        }
        protected virtual ECCurve ConfigureCurve(ECCurve c, int coord)
        {
            if (c.CoordinateSystem == coord)
                return c;

            if (!c.SupportsCoordinateSystem(coord))
                throw new ArgumentException("Coordinate system " + coord + " not supported by this curve", "coord");

            return c.Configure().SetCoordinateSystem(coord).Create();
        }
Example #3
0
        public bool IsCurveTypeEqual(ECCurve.ECCurveType actual)
        {
            if (CurveType == actual)
                return true;

            // Montgomery and Weierstrass are interchangable depending on the platform 
            if (CurveType == ECCurve.ECCurveType.PrimeMontgomery && actual == ECCurve.ECCurveType.PrimeShortWeierstrass ||
                CurveType == ECCurve.ECCurveType.PrimeShortWeierstrass && actual == ECCurve.ECCurveType.PrimeMontgomery)
            {
                return true;
            }

            return false;
        }
Example #4
0
        public override ECPoint Add(ECPoint b)
        {
            if (this.IsInfinity)
            {
                return(b);
            }
            if (b.IsInfinity)
            {
                return(this);
            }
            if (this == b)
            {
                return(Twice());
            }

            ECCurve curve = this.Curve;

            SecP384R1FieldElement X1 = (SecP384R1FieldElement)this.RawXCoord, Y1 = (SecP384R1FieldElement)this.RawYCoord;
            SecP384R1FieldElement X2 = (SecP384R1FieldElement)b.RawXCoord, Y2 = (SecP384R1FieldElement)b.RawYCoord;

            SecP384R1FieldElement Z1 = (SecP384R1FieldElement)this.RawZCoords[0];
            SecP384R1FieldElement Z2 = (SecP384R1FieldElement)b.RawZCoords[0];

            uint c;

            uint[] tt1 = Nat.Create(24);
            uint[] tt2 = Nat.Create(24);
            uint[] t3  = Nat.Create(12);
            uint[] t4  = Nat.Create(12);

            bool Z1IsOne = Z1.IsOne;

            uint[] U2, S2;
            if (Z1IsOne)
            {
                U2 = X2.x;
                S2 = Y2.x;
            }
            else
            {
                S2 = t3;
                SecP384R1Field.Square(Z1.x, S2);

                U2 = tt2;
                SecP384R1Field.Multiply(S2, X2.x, U2);

                SecP384R1Field.Multiply(S2, Z1.x, S2);
                SecP384R1Field.Multiply(S2, Y2.x, S2);
            }

            bool Z2IsOne = Z2.IsOne;

            uint[] U1, S1;
            if (Z2IsOne)
            {
                U1 = X1.x;
                S1 = Y1.x;
            }
            else
            {
                S1 = t4;
                SecP384R1Field.Square(Z2.x, S1);

                U1 = tt1;
                SecP384R1Field.Multiply(S1, X1.x, U1);

                SecP384R1Field.Multiply(S1, Z2.x, S1);
                SecP384R1Field.Multiply(S1, Y1.x, S1);
            }

            uint[] H = Nat.Create(12);
            SecP384R1Field.Subtract(U1, U2, H);

            uint[] R = Nat.Create(12);
            SecP384R1Field.Subtract(S1, S2, R);

            // Check if b == this or b == -this
            if (Nat.IsZero(12, H))
            {
                if (Nat.IsZero(12, R))
                {
                    // this == b, i.e. this must be doubled
                    return(this.Twice());
                }

                // this == -b, i.e. the result is the point at infinity
                return(curve.Infinity);
            }

            uint[] HSquared = t3;
            SecP384R1Field.Square(H, HSquared);

            uint[] G = Nat.Create(12);
            SecP384R1Field.Multiply(HSquared, H, G);

            uint[] V = t3;
            SecP384R1Field.Multiply(HSquared, U1, V);

            SecP384R1Field.Negate(G, G);
            Nat384.Mul(S1, G, tt1);

            c = Nat.AddBothTo(12, V, V, G);
            SecP384R1Field.Reduce32(c, G);

            SecP384R1FieldElement X3 = new SecP384R1FieldElement(t4);

            SecP384R1Field.Square(R, X3.x);
            SecP384R1Field.Subtract(X3.x, G, X3.x);

            SecP384R1FieldElement Y3 = new SecP384R1FieldElement(G);

            SecP384R1Field.Subtract(V, X3.x, Y3.x);
            Nat384.Mul(Y3.x, R, tt2);
            SecP384R1Field.AddExt(tt1, tt2, tt1);
            SecP384R1Field.Reduce(tt1, Y3.x);

            SecP384R1FieldElement Z3 = new SecP384R1FieldElement(H);

            if (!Z1IsOne)
            {
                SecP384R1Field.Multiply(Z3.x, Z1.x, Z3.x);
            }
            if (!Z2IsOne)
            {
                SecP384R1Field.Multiply(Z3.x, Z2.x, Z3.x);
            }

            ECFieldElement[] zs = new ECFieldElement[] { Z3 };

            return(new SecP384R1Point(curve, X3, Y3, zs, IsCompressed));
        }
Example #5
0
        public override ECPoint Add(ECPoint b)
        {
            if (this.IsInfinity)
            {
                return(b);
            }
            if (b.IsInfinity)
            {
                return(this);
            }

            ECCurve curve = this.Curve;

            ECFieldElement X1 = this.RawXCoord;
            ECFieldElement X2 = b.RawXCoord;

            if (X1.IsZero)
            {
                if (X2.IsZero)
                {
                    return(curve.Infinity);
                }

                return(b.Add(this));
            }

            ECFieldElement L1 = this.RawYCoord, Z1 = this.RawZCoords[0];
            ECFieldElement L2 = b.RawYCoord, Z2 = b.RawZCoords[0];

            bool           Z1IsOne = Z1.IsOne;
            ECFieldElement U2 = X2, S2 = L2;

            if (!Z1IsOne)
            {
                U2 = U2.Multiply(Z1);
                S2 = S2.Multiply(Z1);
            }

            bool           Z2IsOne = Z2.IsOne;
            ECFieldElement U1 = X1, S1 = L1;

            if (!Z2IsOne)
            {
                U1 = U1.Multiply(Z2);
                S1 = S1.Multiply(Z2);
            }

            ECFieldElement A = S1.Add(S2);
            ECFieldElement B = U1.Add(U2);

            if (B.IsZero)
            {
                if (A.IsZero)
                {
                    return(Twice());
                }

                return(curve.Infinity);
            }

            ECFieldElement X3, L3, Z3;

            if (X2.IsZero)
            {
                // TODO This can probably be optimized quite a bit
                ECPoint p = this.Normalize();
                X1 = p.XCoord;
                ECFieldElement Y1 = p.YCoord;

                ECFieldElement Y2 = L2;
                ECFieldElement L  = Y1.Add(Y2).Divide(X1);

                X3 = L.Square().Add(L).Add(X1);
                if (X3.IsZero)
                {
                    return(new SecT283K1Point(curve, X3, curve.B, IsCompressed));
                }

                ECFieldElement Y3 = L.Multiply(X1.Add(X3)).Add(X3).Add(Y1);
                L3 = Y3.Divide(X3).Add(X3);
                Z3 = curve.FromBigInteger(BigInteger.One);
            }
            else
            {
                B = B.Square();

                ECFieldElement AU1 = A.Multiply(U1);
                ECFieldElement AU2 = A.Multiply(U2);

                X3 = AU1.Multiply(AU2);
                if (X3.IsZero)
                {
                    return(new SecT283K1Point(curve, X3, curve.B, IsCompressed));
                }

                ECFieldElement ABZ2 = A.Multiply(B);
                if (!Z2IsOne)
                {
                    ABZ2 = ABZ2.Multiply(Z2);
                }

                L3 = AU2.Add(B).SquarePlusProduct(ABZ2, L1.Add(Z1));

                Z3 = ABZ2;
                if (!Z1IsOne)
                {
                    Z3 = Z3.Multiply(Z1);
                }
            }

            return(new SecT283K1Point(curve, X3, L3, new ECFieldElement[] { Z3 }, IsCompressed));
        }
Example #6
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
  *
  * @deprecated Use ECCurve.createPoint to construct points
  */
 public SecP384R1Point(ECCurve curve, ECFieldElement x, ECFieldElement y)
     : this(curve, x, y, false)
 {
 }
Example #7
0
 public static ECDsa Create(ECCurve curve)
 {
     return s_provider.Create(curve);
 }
 private static ECCurve ConfigureCurve(ECCurve curve)
 {
     return(curve);
 }
Example #9
0
        public static WNafPreCompInfo Precompute(ECPoint p, int width, bool includeNegated)
        {
            ECCurve         c = p.Curve;
            WNafPreCompInfo wnafPreCompInfo = GetWNafPreCompInfo(c.GetPreCompInfo(p, PRECOMP_NAME));

            ECPoint[] preComp = wnafPreCompInfo.PreComp;
            if (preComp == null)
            {
                preComp = new ECPoint[] { p };
            }

            int preCompLen    = preComp.Length;
            int reqPreCompLen = 1 << System.Math.Max(0, width - 2);

            if (preCompLen < reqPreCompLen)
            {
                preComp = ResizeTable(preComp, reqPreCompLen);
                if (reqPreCompLen == 2)
                {
                    preComp[1] = preComp[0].ThreeTimes();
                }
                else
                {
                    ECPoint twiceP = wnafPreCompInfo.Twice;
                    if (twiceP == null)
                    {
                        twiceP = preComp[0].Twice();
                        wnafPreCompInfo.Twice = twiceP;
                    }

                    for (int i = preCompLen; i < reqPreCompLen; i++)
                    {
                        /*
                         * Compute the new ECPoints for the precomputation array. The values 1, 3, 5, ...,
                         * 2^(width-1)-1 times p are computed
                         */
                        preComp[i] = twiceP.Add(preComp[i - 1]);
                    }
                }

                /*
                 * Having oft-used operands in affine form makes operations faster.
                 */
                c.NormalizeAll(preComp);
            }

            wnafPreCompInfo.PreComp = preComp;

            if (includeNegated)
            {
                ECPoint[] preCompNeg = wnafPreCompInfo.PreCompNeg;

                int pos;
                if (preCompNeg == null)
                {
                    pos        = 0;
                    preCompNeg = new ECPoint[reqPreCompLen];
                }
                else
                {
                    pos = preCompNeg.Length;
                    if (pos < reqPreCompLen)
                    {
                        preCompNeg = ResizeTable(preCompNeg, reqPreCompLen);
                    }
                }

                while (pos < reqPreCompLen)
                {
                    preCompNeg[pos] = preComp[pos].Negate();
                    ++pos;
                }

                wnafPreCompInfo.PreCompNeg = preCompNeg;
            }

            c.SetPreCompInfo(p, PRECOMP_NAME, wnafPreCompInfo);

            return(wnafPreCompInfo);
        }
 /**
  * @deprecated Use ECCurve.createPoint to construct points
  */
 public SecT163R2Point(ECCurve curve, ECFieldElement x, ECFieldElement y)
     : this(curve, x, y, false)
 {
 }
Example #11
0
 public ECDomainParameters(ECCurve curve, ECPoint g, BigInteger n) : this(curve, g, n, BigInteger.One)
 {
 }
Example #12
0
 public ECDomainParameters(ECCurve curve, ECPoint g, BigInteger n, BigInteger h) : this(curve, g, n, h, null)
 {
 }
Example #13
0
        public void TestECDsa239BitPrime()
        {
            BigInteger r = new BigInteger("308636143175167811492622547300668018854959378758531778147462058306432176");
            BigInteger s = new BigInteger("323813553209797357708078776831250505931891051755007842781978505179448783");

            byte[] kData = BigIntegers.AsUnsignedByteArray(
                new BigInteger("700000017569056646655505781757157107570501575775705779575555657156756655"));

            SecureRandom k = FixedSecureRandom.From(kData);

            X9ECParameters     x9    = ECNamedCurveTable.GetByName("prime239v1");
            ECCurve            curve = x9.Curve;
            ECDomainParameters spec  = new ECDomainParameters(curve, x9.G, x9.N, x9.H);

            ECPrivateKeyParameters priKey = new ECPrivateKeyParameters(
                "ECDSA",
                new BigInteger("876300101507107567501066130761671078357010671067781776716671676178726717"), // d
                spec);

            ECPublicKeyParameters pubKey = new ECPublicKeyParameters(
                "ECDSA",
                curve.DecodePoint(Hex.Decode("025b6dc53bc61a2548ffb0f671472de6c9521a9d2d2534e65abfcbd5fe0c70")), // Q
                spec);

            ISigner sgr = SignerUtilities.GetSigner("ECDSA");

//			KeyFactory f = KeyFactory.GetInstance("ECDSA");
//			PrivateKey sKey = f.generatePrivate(priKey);
//			PublicKey vKey = f.generatePublic(pubKey);
            AsymmetricKeyParameter sKey = priKey;
            AsymmetricKeyParameter vKey = pubKey;

            sgr.Init(true, new ParametersWithRandom(sKey, k));

            byte[] message = Encoding.ASCII.GetBytes("abc");

            sgr.BlockUpdate(message, 0, message.Length);

            byte[] sigBytes = sgr.GenerateSignature();

            sgr.Init(false, vKey);

            sgr.BlockUpdate(message, 0, message.Length);

            if (!sgr.VerifySignature(sigBytes))
            {
                Fail("239 Bit EC verification failed");
            }

            BigInteger[] sig = DerDecode(sigBytes);

            if (!r.Equals(sig[0]))
            {
                Fail("r component wrong." + SimpleTest.NewLine
                     + " expecting: " + r + SimpleTest.NewLine
                     + " got      : " + sig[0]);
            }

            if (!s.Equals(sig[1]))
            {
                Fail("s component wrong." + SimpleTest.NewLine
                     + " expecting: " + s + SimpleTest.NewLine
                     + " got      : " + sig[1]);
            }
        }
Example #14
0
        public void TestGeneration()
        {
            ISigner s = SignerUtilities.GetSigner("DSA");

            byte[]       data = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
            SecureRandom rand = new SecureRandom();

            // KeyPairGenerator g = KeyPairGenerator.GetInstance("DSA");
            IAsymmetricCipherKeyPairGenerator g = GeneratorUtilities.GetKeyPairGenerator("DSA");

            // test exception
            //

            doTestBadStrength(513);
            doTestBadStrength(510);
            doTestBadStrength(1025);

            //g.initialize(512, rand);
            {
                DsaParametersGenerator pGen = new DsaParametersGenerator();
                pGen.Init(512, 80, rand);

                g.Init(new DsaKeyGenerationParameters(rand, pGen.GenerateParameters()));
            }

            AsymmetricCipherKeyPair p = g.GenerateKeyPair();

            AsymmetricKeyParameter sKey = p.Private;
            AsymmetricKeyParameter vKey = p.Public;

            s.Init(true, sKey);

            s.BlockUpdate(data, 0, data.Length);

            byte[] sigBytes = s.GenerateSignature();

            s = SignerUtilities.GetSigner("DSA");

            s.Init(false, vKey);

            s.BlockUpdate(data, 0, data.Length);

            if (!s.VerifySignature(sigBytes))
            {
                Fail("DSA verification failed");
            }



            //
            // ECDSA Fp generation test
            //
            s = SignerUtilities.GetSigner("ECDSA");

            X9ECParameters     x9     = ECNamedCurveTable.GetByName("prime239v1");
            ECCurve            curve  = x9.Curve;
            ECDomainParameters ecSpec = new ECDomainParameters(curve, x9.G, x9.N, x9.H);

            g = GeneratorUtilities.GetKeyPairGenerator("ECDSA");
            g.Init(new ECKeyGenerationParameters(ecSpec, rand));

            p = g.GenerateKeyPair();

            sKey = p.Private;
            vKey = p.Public;

            s.Init(true, sKey);

            s.BlockUpdate(data, 0, data.Length);

            sigBytes = s.GenerateSignature();

            s = SignerUtilities.GetSigner("ECDSA");

            s.Init(false, vKey);

            s.BlockUpdate(data, 0, data.Length);

            if (!s.VerifySignature(sigBytes))
            {
                Fail("ECDSA verification failed");
            }

            //
            // ECDSA F2m generation test
            //
            s = SignerUtilities.GetSigner("ECDSA");

            x9     = ECNamedCurveTable.GetByName("c2tnb239v1");
            curve  = x9.Curve;
            ecSpec = new ECDomainParameters(curve, x9.G, x9.N, x9.H);

            g = GeneratorUtilities.GetKeyPairGenerator("ECDSA");
            g.Init(new ECKeyGenerationParameters(ecSpec, rand));

            p = g.GenerateKeyPair();

            sKey = p.Private;
            vKey = p.Public;

            s.Init(true, sKey);

            s.BlockUpdate(data, 0, data.Length);

            sigBytes = s.GenerateSignature();

            s = SignerUtilities.GetSigner("ECDSA");

            s.Init(false, vKey);

            s.BlockUpdate(data, 0, data.Length);

            if (!s.VerifySignature(sigBytes))
            {
                Fail("ECDSA verification failed");
            }
        }
Example #15
0
 public static int GetByteLength(ECCurve c)
 {
     return((c.FieldSize + 7) / 8);
 }
 public ECNamedDomainParameters(DerObjectIdentifier name, ECCurve curve, ECPoint g, BigInteger n, BigInteger h, byte[] seed)
     : base(curve, g, n, h, seed)
 {
     this.name = name;
 }
 public ECNamedDomainParameters(DerObjectIdentifier name, ECCurve curve, ECPoint g, BigInteger n)
     : base(curve, g, n)
 {
     this.name = name;
 }
        private static void Validate(
            ECParameters parameters,
            ECCurve explicitCurve,
            byte[] msg,
            byte[] signature,
            HashAlgorithmName hashAlgorithm)
        {
            byte[] tamperedSignature = (byte[])signature.Clone();
            tamperedSignature[0] ^= 0xFF;

            using (ECDsa ecdsa = ECDsaFactory.Create())
            {
                ecdsa.ImportParameters(parameters);

                Assert.True(
                    ecdsa.VerifyData(msg, signature, hashAlgorithm),
                    "named verifies signature");

                Assert.False(
                    ecdsa.VerifyData(msg, tamperedSignature, hashAlgorithm),
                    "named verifies tampered");
            }

            if (ECDsaFactory.ExplicitCurvesSupported)
            {
                using (ECDsa ecdsa = ECDsaFactory.Create())
                {
                    parameters.Curve = explicitCurve;
                    ecdsa.ImportParameters(parameters);

                    Assert.True(
                        ecdsa.VerifyData(msg, signature, hashAlgorithm),
                        "explicit verifies signature");

                    Assert.False(
                        ecdsa.VerifyData(msg, tamperedSignature, hashAlgorithm),
                        "explicit verifies tampered");
                }
            }
        }
Example #19
0
 public X9ECPoint(ECCurve c, byte[] encoding)
 {
     this.c        = c;
     this.encoding = new DerOctetString(Arrays.Clone(encoding));
 }
Example #20
0
        internal static void CompareCurve(ECCurve c1, ECCurve c2)
        {
            if (c1.IsNamed)
            {
                Assert.True(c2.IsNamed);
                Assert.Equal(c1.Oid.FriendlyName, c2.Oid.FriendlyName);
            }
            else if (c1.IsExplicit)
            {
                Assert.True(c2.IsExplicit);
                Assert.Equal(c1.A, c2.A);
                Assert.Equal(c1.B, c2.B);
                Assert.Equal(c1.CurveType, c2.CurveType);
                Assert.Equal(c1.G.X, c2.G.X);
                Assert.Equal(c1.G.Y, c2.G.Y);
                Assert.Equal(c1.Cofactor, c2.Cofactor);
                Assert.Equal(c1.Order, c2.Order);
                Assert.Equal(c1.Seed, c2.Seed);
                Assert.Equal(c1.Hash, c2.Hash);

                if (c1.IsPrime)
                {
                    Assert.True(c2.IsPrime);
                    Assert.Equal(c1.Prime, c2.Prime);
                }
                else if (c1.IsCharacteristic2)
                {
                    Assert.True(c2.IsCharacteristic2);
                    Assert.Equal(c1.Polynomial, c2.Polynomial);
                }
            }
        }
Example #21
0
 public X9ECPoint(ECCurve c, Asn1OctetString s)
     : this(c, s.GetOctets())
 {
 }
Example #22
0
 public ECDsa Create(ECCurve curve)
 {
     return new ECDsaOpenSsl(curve);
 }
Example #23
0
 public override void GenerateKey(ECCurve curve)
 {
     throw new NotImplementedException();
 }
Example #24
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
  * 
  * @deprecated per-point compression property will be removed, refer
  *             {@link #getEncoded(bool)}
  */
 public SecP192K1Point(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");
 }
 public ECDsa Create(ECCurve curve)
 {
     return(ECDsa.Create(curve));
 }
Example #26
0
        public override ECPoint Add(ECPoint b)
        {
            if (base.IsInfinity)
            {
                return(b);
            }
            if (b.IsInfinity)
            {
                return(this);
            }
            if (this == b)
            {
                return(this.Twice());
            }
            ECCurve curve = this.Curve;
            SecP224R1FieldElement secP224R1FieldElement  = (SecP224R1FieldElement)base.RawXCoord;
            SecP224R1FieldElement secP224R1FieldElement2 = (SecP224R1FieldElement)base.RawYCoord;
            SecP224R1FieldElement secP224R1FieldElement3 = (SecP224R1FieldElement)b.RawXCoord;
            SecP224R1FieldElement secP224R1FieldElement4 = (SecP224R1FieldElement)b.RawYCoord;
            SecP224R1FieldElement secP224R1FieldElement5 = (SecP224R1FieldElement)base.RawZCoords[0];
            SecP224R1FieldElement secP224R1FieldElement6 = (SecP224R1FieldElement)b.RawZCoords[0];

            uint[] array  = Nat224.CreateExt();
            uint[] array2 = Nat224.Create();
            uint[] array3 = Nat224.Create();
            uint[] array4 = Nat224.Create();
            bool   isOne  = secP224R1FieldElement5.IsOne;

            uint[] array5;
            uint[] array6;
            if (isOne)
            {
                array5 = secP224R1FieldElement3.x;
                array6 = secP224R1FieldElement4.x;
            }
            else
            {
                array6 = array3;
                SecP224R1Field.Square(secP224R1FieldElement5.x, array6);
                array5 = array2;
                SecP224R1Field.Multiply(array6, secP224R1FieldElement3.x, array5);
                SecP224R1Field.Multiply(array6, secP224R1FieldElement5.x, array6);
                SecP224R1Field.Multiply(array6, secP224R1FieldElement4.x, array6);
            }
            bool isOne2 = secP224R1FieldElement6.IsOne;

            uint[] array7;
            uint[] array8;
            if (isOne2)
            {
                array7 = secP224R1FieldElement.x;
                array8 = secP224R1FieldElement2.x;
            }
            else
            {
                array8 = array4;
                SecP224R1Field.Square(secP224R1FieldElement6.x, array8);
                array7 = array;
                SecP224R1Field.Multiply(array8, secP224R1FieldElement.x, array7);
                SecP224R1Field.Multiply(array8, secP224R1FieldElement6.x, array8);
                SecP224R1Field.Multiply(array8, secP224R1FieldElement2.x, array8);
            }
            uint[] array9 = Nat224.Create();
            SecP224R1Field.Subtract(array7, array5, array9);
            uint[] array10 = array2;
            SecP224R1Field.Subtract(array8, array6, array10);
            if (!Nat224.IsZero(array9))
            {
                uint[] array11 = array3;
                SecP224R1Field.Square(array9, array11);
                uint[] array12 = Nat224.Create();
                SecP224R1Field.Multiply(array11, array9, array12);
                uint[] array13 = array3;
                SecP224R1Field.Multiply(array11, array7, array13);
                SecP224R1Field.Negate(array12, array12);
                Nat224.Mul(array8, array12, array);
                uint x = Nat224.AddBothTo(array13, array13, array12);
                SecP224R1Field.Reduce32(x, array12);
                SecP224R1FieldElement secP224R1FieldElement7 = new SecP224R1FieldElement(array4);
                SecP224R1Field.Square(array10, secP224R1FieldElement7.x);
                SecP224R1Field.Subtract(secP224R1FieldElement7.x, array12, secP224R1FieldElement7.x);
                SecP224R1FieldElement secP224R1FieldElement8 = new SecP224R1FieldElement(array12);
                SecP224R1Field.Subtract(array13, secP224R1FieldElement7.x, secP224R1FieldElement8.x);
                SecP224R1Field.MultiplyAddToExt(secP224R1FieldElement8.x, array10, array);
                SecP224R1Field.Reduce(array, secP224R1FieldElement8.x);
                SecP224R1FieldElement secP224R1FieldElement9 = new SecP224R1FieldElement(array9);
                if (!isOne)
                {
                    SecP224R1Field.Multiply(secP224R1FieldElement9.x, secP224R1FieldElement5.x, secP224R1FieldElement9.x);
                }
                if (!isOne2)
                {
                    SecP224R1Field.Multiply(secP224R1FieldElement9.x, secP224R1FieldElement6.x, secP224R1FieldElement9.x);
                }
                ECFieldElement[] zs = new ECFieldElement[]
                {
                    secP224R1FieldElement9
                };
                return(new SecP224R1Point(curve, secP224R1FieldElement7, secP224R1FieldElement8, zs, base.IsCompressed));
            }
            if (Nat224.IsZero(array10))
            {
                return(this.Twice());
            }
            return(curve.Infinity);
        }
Example #27
0
        public void TestRegenKeyExplicit(CurveDef curveDef)
        {
            ECParameters param, param2;
            ECDsa        ec, newEc;

            using (ec = ECDsaFactory.Create(curveDef.Curve))
            {
                param = ec.ExportExplicitParameters(true);
                Assert.NotEqual(null, param.D);
                using (newEc = ECDsaFactory.Create())
                {
                    newEc.ImportParameters(param);

                    // The curve name is not flowed on explicit export\import (by design) so this excercises logic
                    // that regenerates based on current curve values
                    newEc.GenerateKey(param.Curve);
                    param2 = newEc.ExportExplicitParameters(true);

                    // Only curve should match
                    ComparePrivateKey(param, param2, false);
                    ComparePublicKey(param.Q, param2.Q, false);
                    CompareCurve(param.Curve, param2.Curve);

                    // Specify same curve name
                    newEc.GenerateKey(curveDef.Curve);
                    Assert.Equal(curveDef.KeySize, newEc.KeySize);
                    param2 = newEc.ExportExplicitParameters(true);

                    // Only curve should match
                    ComparePrivateKey(param, param2, false);
                    ComparePublicKey(param.Q, param2.Q, false);
                    CompareCurve(param.Curve, param2.Curve);

                    // Specify different curve than current
                    if (param.Curve.IsPrime)
                    {
                        if (curveDef.Curve.Oid.FriendlyName != ECCurve.NamedCurves.nistP256.Oid.FriendlyName)
                        {
                            // Specify different curve (nistP256) by explicit value
                            newEc.GenerateKey(ECCurve.NamedCurves.nistP256);
                            Assert.Equal(256, newEc.KeySize);
                            param2 = newEc.ExportExplicitParameters(true);
                            // Keys should should not match
                            ComparePrivateKey(param, param2, false);
                            ComparePublicKey(param.Q, param2.Q, false);
                            // P,X,Y (and others) should not match
                            Assert.True(param2.Curve.IsPrime);
                            Assert.NotEqual(param.Curve.Prime, param2.Curve.Prime);
                            Assert.NotEqual(param.Curve.G.X, param2.Curve.G.X);
                            Assert.NotEqual(param.Curve.G.Y, param2.Curve.G.Y);

                            // Reset back to original
                            newEc.GenerateKey(param.Curve);
                            Assert.Equal(curveDef.KeySize, newEc.KeySize);
                            ECParameters copyOfParam1 = newEc.ExportExplicitParameters(true);
                            // Only curve should match
                            ComparePrivateKey(param, copyOfParam1, false);
                            ComparePublicKey(param.Q, copyOfParam1.Q, false);
                            CompareCurve(param.Curve, copyOfParam1.Curve);

                            // Set back to nistP256
                            newEc.GenerateKey(param2.Curve);
                            Assert.Equal(256, newEc.KeySize);
                            param2 = newEc.ExportExplicitParameters(true);
                            // Keys should should not match
                            ComparePrivateKey(param, param2, false);
                            ComparePublicKey(param.Q, param2.Q, false);
                            // P,X,Y (and others) should not match
                            Assert.True(param2.Curve.IsPrime);
                            Assert.NotEqual(param.Curve.Prime, param2.Curve.Prime);
                            Assert.NotEqual(param.Curve.G.X, param2.Curve.G.X);
                            Assert.NotEqual(param.Curve.G.Y, param2.Curve.G.Y);
                        }
                    }
                    else if (param.Curve.IsCharacteristic2)
                    {
                        if (curveDef.Curve.Oid.Value != ECDSA_Sect193r1_OID_VALUE)
                        {
                            if (ECDsaFactory.IsCurveValid(new Oid(ECDSA_Sect193r1_OID_VALUE)))
                            {
                                // Specify different curve by name
                                newEc.GenerateKey(ECCurve.CreateFromValue(ECDSA_Sect193r1_OID_VALUE));
                                Assert.Equal(193, newEc.KeySize);
                                param2 = newEc.ExportExplicitParameters(true);
                                // Keys should should not match
                                ComparePrivateKey(param, param2, false);
                                ComparePublicKey(param.Q, param2.Q, false);
                                // Polynomial,X,Y (and others) should not match
                                Assert.True(param2.Curve.IsCharacteristic2);
                                Assert.NotEqual(param.Curve.Polynomial, param2.Curve.Polynomial);
                                Assert.NotEqual(param.Curve.G.X, param2.Curve.G.X);
                                Assert.NotEqual(param.Curve.G.Y, param2.Curve.G.Y);
                            }
                        }
                    }
                }
            }
        }
Example #28
0
        public override ECPoint TwicePlus(ECPoint b)
        {
            if (this.IsInfinity)
            {
                return(b);
            }
            if (b.IsInfinity)
            {
                return(Twice());
            }

            ECCurve curve = this.Curve;

            ECFieldElement X1 = this.RawXCoord;

            if (X1.IsZero)
            {
                // A point with X == 0 is it's own Additive inverse
                return(b);
            }

            // NOTE: TwicePlus() only optimized for lambda-affine argument
            ECFieldElement X2 = b.RawXCoord, Z2 = b.RawZCoords[0];

            if (X2.IsZero || !Z2.IsOne)
            {
                return(Twice().Add(b));
            }

            ECFieldElement L1 = this.RawYCoord, Z1 = this.RawZCoords[0];
            ECFieldElement L2 = b.RawYCoord;

            ECFieldElement X1Sq = X1.Square();
            ECFieldElement L1Sq = L1.Square();
            ECFieldElement Z1Sq = Z1.Square();
            ECFieldElement L1Z1 = L1.Multiply(Z1);

            ECFieldElement T       = L1Sq.Add(L1Z1);
            ECFieldElement L2plus1 = L2.AddOne();
            ECFieldElement A       = L2plus1.Multiply(Z1Sq).Add(L1Sq).MultiplyPlusProduct(T, X1Sq, Z1Sq);
            ECFieldElement X2Z1Sq  = X2.Multiply(Z1Sq);
            ECFieldElement B       = X2Z1Sq.Add(T).Square();

            if (B.IsZero)
            {
                if (A.IsZero)
                {
                    return(b.Twice());
                }

                return(curve.Infinity);
            }

            if (A.IsZero)
            {
                return(new SecT283K1Point(curve, A, curve.B, IsCompressed));
            }

            ECFieldElement X3 = A.Square().Multiply(X2Z1Sq);
            ECFieldElement Z3 = A.Multiply(B).Multiply(Z1Sq);
            ECFieldElement L3 = A.Add(B).Square().MultiplyPlusProduct(T, L2plus1, Z3);

            return(new SecT283K1Point(curve, X3, L3, new ECFieldElement[] { Z3 }, IsCompressed));
        }
Example #29
0
 public X9Curve(
     ECCurve curve)
     : this(curve, null)
 {
 }
Example #30
0
        public override ECPoint Twice()
        {
            if (this.IsInfinity)
            {
                return(this);
            }

            ECCurve curve = this.Curve;

            SecP384R1FieldElement Y1 = (SecP384R1FieldElement)this.RawYCoord;

            if (Y1.IsZero)
            {
                return(curve.Infinity);
            }

            SecP384R1FieldElement X1 = (SecP384R1FieldElement)this.RawXCoord, Z1 = (SecP384R1FieldElement)this.RawZCoords[0];

            uint c;

            uint[] t1 = Nat.Create(12);
            uint[] t2 = Nat.Create(12);

            uint[] Y1Squared = Nat.Create(12);
            SecP384R1Field.Square(Y1.x, Y1Squared);

            uint[] T = Nat.Create(12);
            SecP384R1Field.Square(Y1Squared, T);

            bool Z1IsOne = Z1.IsOne;

            uint[] Z1Squared = Z1.x;
            if (!Z1IsOne)
            {
                Z1Squared = t2;
                SecP384R1Field.Square(Z1.x, Z1Squared);
            }

            SecP384R1Field.Subtract(X1.x, Z1Squared, t1);

            uint[] M = t2;
            SecP384R1Field.Add(X1.x, Z1Squared, M);
            SecP384R1Field.Multiply(M, t1, M);
            c = Nat.AddBothTo(12, M, M, M);
            SecP384R1Field.Reduce32(c, M);

            uint[] S = Y1Squared;
            SecP384R1Field.Multiply(Y1Squared, X1.x, S);
            c = Nat.ShiftUpBits(12, S, 2, 0);
            SecP384R1Field.Reduce32(c, S);

            c = Nat.ShiftUpBits(12, T, 3, 0, t1);
            SecP384R1Field.Reduce32(c, t1);

            SecP384R1FieldElement X3 = new SecP384R1FieldElement(T);

            SecP384R1Field.Square(M, X3.x);
            SecP384R1Field.Subtract(X3.x, S, X3.x);
            SecP384R1Field.Subtract(X3.x, S, X3.x);

            SecP384R1FieldElement Y3 = new SecP384R1FieldElement(S);

            SecP384R1Field.Subtract(S, X3.x, Y3.x);
            SecP384R1Field.Multiply(Y3.x, M, Y3.x);
            SecP384R1Field.Subtract(Y3.x, t1, Y3.x);

            SecP384R1FieldElement Z3 = new SecP384R1FieldElement(M);

            SecP384R1Field.Twice(Y1.x, Z3.x);
            if (!Z1IsOne)
            {
                SecP384R1Field.Multiply(Z3.x, Z1.x, Z3.x);
            }

            return(new SecP384R1Point(curve, X3, Y3, new ECFieldElement[] { Z3 }, IsCompressed));
        }
Example #31
0
        /// <summary>JoseJwt</summary>
        private static void JoseJwt()
        {
            #region Variables

            #region Env
            OperatingSystem os = Environment.OSVersion;

            // https://github.com/dotnet/corefx/issues/29404#issuecomment-385287947
            //   *.pfxから証明書を開く場合、X509KeyStorageFlags.Exportableの指定が必要な場合がある。
            //   Linuxのキーは常にエクスポート可能だが、WindowsやMacOSでは必ずしもそうではない。
            X509KeyStorageFlags x509KSF = 0;
            if (os.Platform == PlatformID.Win32NT)
            {
                x509KSF = X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.Exportable;
            }
            else //if (os.Platform == PlatformID.Unix)
            {
                x509KSF = X509KeyStorageFlags.DefaultKeySet;
            }
            #endregion

            #region Token
            string token = "";
            IDictionary <string, object> headers = null;
            IDictionary <string, object> payload = null;
            payload = new Dictionary <string, object>()
            {
                { "sub", "*****@*****.**" },
                { "exp", 1300819380 }
            };
            #endregion

            #region Keys

            byte[] secretKey = null;
            byte[] x         = null;
            byte[] y         = null;
            byte[] d         = null;

            X509Certificate2 publicX509Key  = null;
            X509Certificate2 privateX509Key = null;

            RSA rsa = null;
            //DSA dsa = null;

            CngKey publicKeyOfCng  = null;
            CngKey privateKeyOfCng = null;

            #endregion

            #endregion

            #region JWT

            #region Unsecured JWT
            // Creating Plaintext (unprotected) Tokens
            // https://github.com/dvsekhvalnov/jose-jwt#creating-plaintext-unprotected-tokens
            token = "";
            token = JWT.Encode(payload, null, JwsAlgorithm.none);
            MyDebug.OutputDebugAndConsole("JwsAlgorithm.none", token);
            #endregion

            #region JWS (Creating signed Tokens)
            // https://github.com/dvsekhvalnov/jose-jwt#creating-signed-tokens

            #region HS-* family
            // HS256, HS384, HS512
            // https://github.com/dvsekhvalnov/jose-jwt#hs--family
            secretKey = new byte[] { 164, 60, 194, 0, 161, 189, 41, 38, 130, 89, 141, 164, 45, 170, 159, 209, 69, 137, 243, 216, 191, 131, 47, 250, 32, 107, 231, 117, 37, 158, 225, 234 };
            token     = "";
            token     = JWT.Encode(payload, secretKey, JwsAlgorithm.HS256);
            Program.VerifyResult("JwsAlgorithm.HS256", token, secretKey);
            #endregion

            #region RS-* and PS-* family
            // RS256, RS384, RS512 and PS256, PS384, PS512
            // https://github.com/dvsekhvalnov/jose-jwt#rs--and-ps--family
            // X509Certificate2 x509Certificate2 = new X509Certificate2();
            privateX509Key = new X509Certificate2(Program.PrivateRsaX509Path, Program.PfxPassword, x509KSF);
            publicX509Key  = new X509Certificate2(Program.PublicRsaX509Path, "", x509KSF);

            token = "";


#if NETCORE
            rsa = (RSA)privateX509Key.PrivateKey;
#else
            // .net frameworkでは、何故かコレが必要。
            rsa = (RSA)AsymmetricAlgorithmCmnFunc.CreateSameKeySizeSP(privateX509Key.PrivateKey);
#endif
            token = JWT.Encode(payload, rsa, JwsAlgorithm.RS256);
            Program.VerifyResult("JwsAlgorithm.RS256", token, rsa);

            #endregion

            #region ES- * family
            // ES256, ES384, ES512 ECDSA signatures
            // https://github.com/dvsekhvalnov/jose-jwt#es---family

            x = new byte[] { 4, 114, 29, 223, 58, 3, 191, 170, 67, 128, 229, 33, 242, 178, 157, 150, 133, 25, 209, 139, 166, 69, 55, 26, 84, 48, 169, 165, 67, 232, 98, 9 };
            y = new byte[] { 131, 116, 8, 14, 22, 150, 18, 75, 24, 181, 159, 78, 90, 51, 71, 159, 214, 186, 250, 47, 207, 246, 142, 127, 54, 183, 72, 72, 253, 21, 88, 53 };
            d = new byte[] { 42, 148, 231, 48, 225, 196, 166, 201, 23, 190, 229, 199, 20, 39, 226, 70, 209, 148, 29, 70, 125, 14, 174, 66, 9, 198, 80, 251, 95, 107, 98, 206 };

            if (os.Platform == PlatformID.Win32NT)
            {
                // https://github.com/dvsekhvalnov/jose-jwt/blob/master/jose-jwt/Security/Cryptography/EccKey.cs
                privateKeyOfCng = EccKey.New(x, y, d);
                publicKeyOfCng  = EccKey.New(x, y);

                token = "";
                token = JWT.Encode(payload, privateKeyOfCng, JwsAlgorithm.ES256);
                Program.VerifyResult("JwsAlgorithm.ES256", token, publicKeyOfCng);
            }
            else //if (os.Platform == PlatformID.Unix)
            {
#if NETCORE
                ECParameters eCParameters = new ECParameters();

                // Curve
                eCParameters.Curve =
                    EccPublicKeyConverter.GetECCurveFromCrvString(
                        EccPublicKeyConverter.GetCrvStringFromXCoordinate(x));

                // x, y, d
                eCParameters.Q.X = x;
                eCParameters.Q.Y = y;
                eCParameters.D   = d;
                ECDsaOpenSsl eCDsaOpenSsl = new ECDsaOpenSsl(eCParameters.Curve);
                eCDsaOpenSsl.ImportParameters(eCParameters);

                token = "";
                token = JWT.Encode(payload, eCDsaOpenSsl, JwsAlgorithm.ES256);
                Program.VerifyResult("JwsAlgorithm.ES256", token, eCDsaOpenSsl);
#endif
            }

#if NETCORE || NET47
            privateX509Key = new X509Certificate2(Program.PrivateECDsaX509Path, Program.PfxPassword);
            publicX509Key  = new X509Certificate2(Program.PublicECDsaX509Path, "");

            try
            {
#if NETCORE
                if (os.Platform == PlatformID.Win32NT)
                {
                }
                else //if (os.Platform == PlatformID.Unix)
                {
                    // ECCurveを分析してみる。
                    ECCurve eCCurve = ((ECDsaOpenSsl)privateX509Key.GetECDsaPrivateKey()).ExportExplicitParameters(true).Curve;
                    MyDebug.OutputDebugAndConsole("Inspect ECCurve", ObjectInspector.Inspect(eCCurve));
                }
#endif
                token = "";
                token = JWT.Encode(payload, privateX509Key.GetECDsaPrivateKey(), JwsAlgorithm.ES256);
                Program.VerifyResult("JwsAlgorithm.ES256", token, publicX509Key.GetECDsaPublicKey());
            }
            catch (Exception ex)
            {
                MyDebug.OutputDebugAndConsole("JwsAlgorithm.ES256", ex.GetType().ToString() + ", " + ex.Message);
            }
#endif

            #endregion

            #endregion

            #region JWE (Creating encrypted Tokens)
            // https://github.com/dvsekhvalnov/jose-jwt#creating-encrypted-tokens

            #region RSA-* key management family of algorithms
            // RSA-OAEP-256, RSA-OAEP and RSA1_5 key
            // https://github.com/dvsekhvalnov/jose-jwt#rsa--key-management-family-of-algorithms
            privateX509Key = new X509Certificate2(Program.PrivateRsaX509Path, Program.PfxPassword, x509KSF);
            publicX509Key  = new X509Certificate2(Program.PublicRsaX509Path, "", x509KSF);

            // RSAES-PKCS1-v1_5 and AES_128_CBC_HMAC_SHA_256
            token = "";
            token = JWT.Encode(payload, publicX509Key.PublicKey.Key, JweAlgorithm.RSA1_5, JweEncryption.A128CBC_HS256);
            Program.VerifyResult("JweAlgorithm.RSA1_5, JweEncryption.A128CBC_HS256", token, privateX509Key.PrivateKey);

            // RSAES-OAEP and AES GCM
            try
            {
                token = "";
                token = JWT.Encode(payload, publicX509Key.PublicKey.Key, JweAlgorithm.RSA_OAEP, JweEncryption.A256GCM);
                Program.VerifyResult("JweAlgorithm.RSA_OAEP, JweEncryption.A256GCM", token, privateX509Key.PrivateKey);
            }
            catch (Exception ex)
            {
                // Unhandled Exception: System.DllNotFoundException: Unable to load DLL 'bcrypt.dll' at ubunntu
                MyDebug.OutputDebugAndConsole("JweAlgorithm.RSA_OAEP, JweEncryption.A256GCM", ex.GetType().ToString() + ", " + ex.Message);
            }
            #endregion

            #region Other key management family of algorithms

            secretKey = new byte[] { 164, 60, 194, 0, 161, 189, 41, 38, 130, 89, 141, 164, 45, 170, 159, 209, 69, 137, 243, 216, 191, 131, 47, 250, 32, 107, 231, 117, 37, 158, 225, 234 };

            #region DIR direct pre-shared symmetric key family of algorithms
            // https://github.com/dvsekhvalnov/jose-jwt#dir-direct-pre-shared-symmetric-key-family-of-algorithms
            token = "";
            token = JWT.Encode(payload, secretKey, JweAlgorithm.DIR, JweEncryption.A128CBC_HS256);
            Program.VerifyResult("JweAlgorithm.DIR, JweEncryption.A128CBC_HS256", token, secretKey);
            #endregion

            #region AES Key Wrap key management family of algorithms
            // AES128KW, AES192KW and AES256KW key management
            // https://github.com/dvsekhvalnov/jose-jwt#aes-key-wrap-key-management-family-of-algorithms
            token = "";
            token = JWT.Encode(payload, secretKey, JweAlgorithm.A256KW, JweEncryption.A256CBC_HS512);
            Program.VerifyResult("JweAlgorithm.A256KW, JweEncryption.A256CBC_HS512", token, secretKey);
            #endregion

            #region AES GCM Key Wrap key management family of algorithms
            // AES128GCMKW, AES192GCMKW and AES256GCMKW key management
            // https://github.com/dvsekhvalnov/jose-jwt#aes-gcm-key-wrap-key-management-family-of-algorithms
            try
            {
                token = "";
                token = JWT.Encode(payload, secretKey, JweAlgorithm.A256GCMKW, JweEncryption.A256CBC_HS512);
                Program.VerifyResult("JweAlgorithm.A256GCMKW, JweEncryption.A256CBC_HS512", token, secretKey);
            }
            catch (Exception ex)
            {
                // Unhandled Exception: System.DllNotFoundException: Unable to load DLL 'bcrypt.dll' at ubunntu
                MyDebug.OutputDebugAndConsole("JweAlgorithm.A256GCMKW, JweEncryption.A256CBC_HS512", ex.GetType().ToString() + ", " + ex.Message);
            }
            #endregion

            #region ECDH-ES and ECDH-ES with AES Key Wrap key management family of algorithms
            // ECDH-ES and ECDH-ES+A128KW, ECDH-ES+A192KW, ECDH-ES+A256KW key management
            // https://github.com/dvsekhvalnov/jose-jwt#ecdh-es-and-ecdh-es-with-aes-key-wrap-key-management-family-of-algorithms
            try
            {
                x = new byte[] { 4, 114, 29, 223, 58, 3, 191, 170, 67, 128, 229, 33, 242, 178, 157, 150, 133, 25, 209, 139, 166, 69, 55, 26, 84, 48, 169, 165, 67, 232, 98, 9 };
                y = new byte[] { 131, 116, 8, 14, 22, 150, 18, 75, 24, 181, 159, 78, 90, 51, 71, 159, 214, 186, 250, 47, 207, 246, 142, 127, 54, 183, 72, 72, 253, 21, 88, 53 };
                publicKeyOfCng = EccKey.New(x, y, usage: CngKeyUsages.KeyAgreement);
                token          = "";
                token          = JWT.Encode(payload, publicKeyOfCng, JweAlgorithm.ECDH_ES, JweEncryption.A256GCM);
                Program.VerifyResult("JweAlgorithm.ECDH_ES, JweEncryption.A256GCM", token, publicKeyOfCng);
            }
            catch (Exception ex)
            {
                // System.NotImplementedException: 'not yet'
                MyDebug.OutputDebugAndConsole("JweAlgorithm.ECDH_ES, JweEncryption.A256GCM", ex.GetType().ToString() + ", " + ex.Message);
            }
            #endregion

            #region PBES2 using HMAC SHA with AES Key Wrap key management family of algorithms
            token = "";
            token = JWT.Encode(payload, "top secret", JweAlgorithm.PBES2_HS256_A128KW, JweEncryption.A256CBC_HS512);
            Program.VerifyResult("JweAlgorithm.PBES2_HS256_A128KW, JweEncryption.A256CBC_HS512", token, "top secret");
            #endregion

            #endregion

            #endregion

            #endregion

            #region ELSE

            #region Additional utilities
            // https://github.com/dvsekhvalnov/jose-jwt#additional-utilities

            #region Adding extra headers
            // https://github.com/dvsekhvalnov/jose-jwt#adding-extra-headers

            headers = new Dictionary <string, object>()
            {
                { "typ", "JWT" },
                { "cty", "JWT" },
                { "keyid", "111-222-333" }
            };

            privateX509Key = new X509Certificate2(Program.PrivateRsaX509Path, Program.PfxPassword, x509KSF);
            publicX509Key  = new X509Certificate2(Program.PublicRsaX509Path, "", x509KSF);

#if NETCORE
            rsa = (RSA)privateX509Key.PrivateKey;
#else
            // .net frameworkでは、何故かコレが必要。
            rsa = (RSA)AsymmetricAlgorithmCmnFunc.CreateSameKeySizeSP(privateX509Key.PrivateKey);
#endif

            token = "";
            token = JWT.Encode(payload, rsa, JwsAlgorithm.RS256, extraHeaders: headers);
            Program.VerifyResult("Adding extra headers to RS256", token, rsa);
            #endregion

            #region Strict validation
            // https://github.com/dvsekhvalnov/jose-jwt#strict-validation
            // 厳密な検証では、Algorithmを指定可能
            MyDebug.OutputDebugAndConsole("Strict validation(RS256)", JWT.Decode(token, rsa, JwsAlgorithm.RS256));
            #endregion

            #region Two-phase validation
            // https://github.com/dvsekhvalnov/jose-jwt#two-phase-validation
            // ヘッダのkeyidクレームからキーを取り出して復号化する方法。
            //headers = JWT.Headers(token);
            // ・・・
            //string hoge = JWT.Decode(token, "key");
            #endregion

            #region Working with binary payload
            // https://github.com/dvsekhvalnov/jose-jwt#working-with-binary-payload
            #endregion

            #endregion

            #region Settings
            // https://github.com/dvsekhvalnov/jose-jwt#settings
            // グローバル設定

            #region Example of JWTSettings
            // https://github.com/dvsekhvalnov/jose-jwt#example-of-jwtsettings

            #endregion

            #region Customizing json <-> object parsing & mapping
            // https://github.com/dvsekhvalnov/jose-jwt#customizing-json---object-parsing--mapping
            // マッピング
            // https://github.com/dvsekhvalnov/jose-jwt#example-of-newtonsoftjson-mapper
            // https://github.com/dvsekhvalnov/jose-jwt#example-of-servicestack-mapper

            #endregion

            #region Customizing algorithm implementations
            // https://github.com/dvsekhvalnov/jose-jwt#customizing-algorithm-implementations
            // https://github.com/dvsekhvalnov/jose-jwt#example-of-custom-algorithm-implementation
            #endregion

            #region Providing aliases
            // https://github.com/dvsekhvalnov/jose-jwt#providing-aliases
            #endregion

            #endregion

            #region Dealing with keys
            // https://github.com/dvsekhvalnov/jose-jwt#dealing-with-keys
            // https://github.com/dvsekhvalnov/jose-jwt#rsacryptoserviceprovider
            // - http://stackoverflow.com/questions/7444586/how-can-i-sign-a-file-using-rsa-and-sha256-with-net
            // - http://hintdesk.com/c-how-to-fix-invalid-algorithm-specified-when-signing-with-sha256/
            // https://github.com/dvsekhvalnov/jose-jwt#if-you-have-only-rsa-private-key
            // - http://www.donaldsbaconbytes.com/2016/08/create-jwt-with-a-private-rsa-key/
            #endregion

            #region Strong-Named assembly
            // https://github.com/dvsekhvalnov/jose-jwt#strong-named-assembly
            // - https://github.com/dvsekhvalnov/jose-jwt/issues/5
            // - https://github.com/brutaldev/StrongNameSigner
            #endregion

            #region More examples
            // https://github.com/dvsekhvalnov/jose-jwt#more-examples
            // https://github.com/dvsekhvalnov/jose-jwt/blob/master/UnitTests/TestSuite.cs
            #endregion

            #endregion
        }
Example #32
0
 internal SecP384R1Point(ECCurve curve, ECFieldElement x, ECFieldElement y, ECFieldElement[] zs, bool withCompression)
     : base(curve, x, y, zs, withCompression)
 {
 }
Example #33
0
		public ECDsaOpenSsl (ECCurve curve)
		{
			throw new NotImplementedException ();
		}
Example #34
0
 public ECDsa Create(ECCurve curve)
 {
     return new ECDsaCng(curve);
 }
Example #35
0
 public ECDsa(ECPoint publicKey)
 {
     this.publicKey = publicKey;
     this.curve = publicKey.Curve;
 }
Example #36
0
 /// <summary>
 /// Creates an instance of the platform specific implementation of the cref="ECDsa" algorithm.
 /// </summary>
 /// <param name="curve">
 /// The <see cref="ECCurve"/> representing the elliptic curve.
 /// </param>
 public static ECDsa Create(ECCurve curve)
 {
     return new ECDsaImplementation.ECDsaOpenSsl(curve);
 }
Example #37
0
		public SecP256K1Point(ECCurve curve, ECFieldElement x, ECFieldElement y, ECFieldElement[] zs,
			bool withCompression)
			: base(curve, x, y, zs, withCompression)
		{
		}
Example #38
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
  * 
  * @deprecated per-point compression property will be removed, refer
  *             {@link #getEncoded(bool)}
  */
 public SecP160K1Point(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");
 }
        public static int GetCombSize(ECCurve c)
        {
            BigInteger order = c.Order;

            return(order == null ? c.FieldSize + 1 : order.BitLength);
        }
Example #40
0
 public ECDsa(byte[] privateKey, ECCurve curve)
     : this(curve.G * privateKey)
 {
     this.privateKey = privateKey;
 }
Example #41
0
 private static ECCurve ConfigureCurveGlv(ECCurve c, GlvTypeBParameters p)
 {
     return(c.Configure().SetEndomorphism(new GlvTypeBEndomorphism(c, p)).Create());
 }
 public static int GetCombSize(ECCurve c)
 {
     BigInteger order = c.Order;
     return order == null ? c.FieldSize + 1 : order.BitLength;
 }
Example #43
0
        // 5.4 pg 29

        /**
         * return true if the value r and s represent a DSA signature for
         * the passed in message (for standard DSA the message should be
         * a SHA-1 hash of the real message to be verified).
         */
        public virtual bool VerifySignature(byte[] message, BigInteger r, BigInteger s)
        {
            BigInteger n = key.Parameters.N;

            // r and s should both in the range [1,n-1]
            if (r.SignValue < 1 || s.SignValue < 1 ||
                r.CompareTo(n) >= 0 || s.CompareTo(n) >= 0)
            {
                return(false);
            }

            BigInteger e = CalculateE(n, message);
            BigInteger c = s.ModInverse(n);

            BigInteger u1 = e.Multiply(c).Mod(n);
            BigInteger u2 = r.Multiply(c).Mod(n);

            ECPoint G = key.Parameters.G;
            ECPoint Q = ((ECPublicKeyParameters)key).Q;

            ECPoint point = ECAlgorithms.SumOfTwoMultiplies(G, u1, Q, u2);

            if (point.IsInfinity)
            {
                return(false);
            }

            /*
             * If possible, avoid normalizing the point (to save a modular inversion in the curve field).
             *
             * There are ~cofactor elements of the curve field that reduce (modulo the group order) to 'r'.
             * If the cofactor is known and small, we generate those possible field values and project each
             * of them to the same "denominator" (depending on the particular projective coordinates in use)
             * as the calculated point.X. If any of the projected values matches point.X, then we have:
             *     (point.X / Denominator mod p) mod n == r
             * as required, and verification succeeds.
             *
             * Based on an original idea by Gregory Maxwell (https://github.com/gmaxwell), as implemented in
             * the libsecp256k1 project (https://github.com/bitcoin/secp256k1).
             */
            ECCurve curve = point.Curve;

            if (curve != null)
            {
                BigInteger cofactor = curve.Cofactor;
                if (cofactor != null && cofactor.CompareTo(Eight) <= 0)
                {
                    ECFieldElement D = GetDenominator(curve.CoordinateSystem, point);
                    if (D != null && !D.IsZero)
                    {
                        ECFieldElement X = point.XCoord;
                        while (curve.IsValidFieldElement(r))
                        {
                            ECFieldElement R = curve.FromBigInteger(r).Multiply(D);
                            if (R.Equals(X))
                            {
                                return(true);
                            }
                            r = r.Add(n);
                        }
                        return(false);
                    }
                }
            }

            BigInteger v = point.Normalize().AffineXCoord.ToBigInteger().Mod(n);

            return(v.Equals(r));
        }
 /**
  * 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
  *
  * @deprecated Use ECCurve.CreatePoint to construct points
  */
 public Curve25519Point(ECCurve curve, ECFieldElement x, ECFieldElement y)
     : this(curve, x, y, false)
 {
 }
Example #45
0
 /**
  * @deprecated Use ECCurve.createPoint to construct points
  */
 public SecT193R2Point(ECCurve curve, ECFieldElement x, ECFieldElement y)
     : this(curve, x, y, false)
 {
 }
 public GlvTypeBEndomorphism(ECCurve curve, GlvTypeBParameters parameters)
 {
     this.m_curve = curve;
     this.m_parameters = parameters;
     this.m_pointMap = new ScaleXPointMap(curve.FromBigInteger(parameters.Beta));
 }
Example #47
0
 public ECDsa Create(ECCurve curve)
 {
     return ECDsa.Create(curve);
 }
Example #48
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
  * 
  * @deprecated Use ECCurve.createPoint to construct points
  */
 public SecP192K1Point(ECCurve curve, ECFieldElement x, ECFieldElement y)
     : this(curve, x, y, false)
 {
 }
Example #49
0
 public static ECDsa Create(ECCurve curve)
 {
     return(s_provider.Create(curve));
 }
Example #50
0
 internal SecP192K1Point(ECCurve curve, ECFieldElement x, ECFieldElement y, ECFieldElement[] zs,
     bool withCompression)
     : base(curve, x, y, zs, withCompression)
 {
 }
Example #51
0
        public override ECPoint Twice()
        {
            if (base.IsInfinity)
            {
                return(this);
            }
            ECCurve curve = this.Curve;
            SecP224R1FieldElement secP224R1FieldElement = (SecP224R1FieldElement)base.RawYCoord;

            if (secP224R1FieldElement.IsZero)
            {
                return(curve.Infinity);
            }
            SecP224R1FieldElement secP224R1FieldElement2 = (SecP224R1FieldElement)base.RawXCoord;
            SecP224R1FieldElement secP224R1FieldElement3 = (SecP224R1FieldElement)base.RawZCoords[0];

            uint[] array  = Nat224.Create();
            uint[] array2 = Nat224.Create();
            uint[] array3 = Nat224.Create();
            SecP224R1Field.Square(secP224R1FieldElement.x, array3);
            uint[] array4 = Nat224.Create();
            SecP224R1Field.Square(array3, array4);
            bool isOne = secP224R1FieldElement3.IsOne;

            uint[] array5 = secP224R1FieldElement3.x;
            if (!isOne)
            {
                array5 = array2;
                SecP224R1Field.Square(secP224R1FieldElement3.x, array5);
            }
            SecP224R1Field.Subtract(secP224R1FieldElement2.x, array5, array);
            uint[] array6 = array2;
            SecP224R1Field.Add(secP224R1FieldElement2.x, array5, array6);
            SecP224R1Field.Multiply(array6, array, array6);
            uint x = Nat224.AddBothTo(array6, array6, array6);

            SecP224R1Field.Reduce32(x, array6);
            uint[] array7 = array3;
            SecP224R1Field.Multiply(array3, secP224R1FieldElement2.x, array7);
            x = Nat.ShiftUpBits(7, array7, 2, 0u);
            SecP224R1Field.Reduce32(x, array7);
            x = Nat.ShiftUpBits(7, array4, 3, 0u, array);
            SecP224R1Field.Reduce32(x, array);
            SecP224R1FieldElement secP224R1FieldElement4 = new SecP224R1FieldElement(array4);

            SecP224R1Field.Square(array6, secP224R1FieldElement4.x);
            SecP224R1Field.Subtract(secP224R1FieldElement4.x, array7, secP224R1FieldElement4.x);
            SecP224R1Field.Subtract(secP224R1FieldElement4.x, array7, secP224R1FieldElement4.x);
            SecP224R1FieldElement secP224R1FieldElement5 = new SecP224R1FieldElement(array7);

            SecP224R1Field.Subtract(array7, secP224R1FieldElement4.x, secP224R1FieldElement5.x);
            SecP224R1Field.Multiply(secP224R1FieldElement5.x, array6, secP224R1FieldElement5.x);
            SecP224R1Field.Subtract(secP224R1FieldElement5.x, array, secP224R1FieldElement5.x);
            SecP224R1FieldElement secP224R1FieldElement6 = new SecP224R1FieldElement(array6);

            SecP224R1Field.Twice(secP224R1FieldElement.x, secP224R1FieldElement6.x);
            if (!isOne)
            {
                SecP224R1Field.Multiply(secP224R1FieldElement6.x, secP224R1FieldElement3.x, secP224R1FieldElement6.x);
            }
            return(new SecP224R1Point(curve, secP224R1FieldElement4, secP224R1FieldElement5, new ECFieldElement[]
            {
                secP224R1FieldElement6
            }, base.IsCompressed));
        }