示例#1
0
        public I2PSigningPublicKey(I2PSigningPrivateKey privkey)
            : base(privkey.Certificate)
        {
            switch (Certificate.SignatureType)
            {
            case SigningKeyTypes.DSA_SHA1:
                Key = new BufLen(I2PConstants.DsaG.ModPow(privkey.ToBigInteger(), I2PConstants.DsaP).ToByteArrayUnsigned());
                break;

            case I2PSigningKey.SigningKeyTypes.ECDSA_SHA256_P256:
            {
                var param  = NistNamedCurves.GetByName("P-256");
                var domain = new ECDomainParameters(param.Curve, param.G, param.N, param.H);

                var q           = domain.G.Multiply(privkey.ToBigInteger());
                var publicparam = new ECPublicKeyParameters(q, domain);
                Key = new BufLen(publicparam.Q.GetEncoded(), 1);
            }
            break;

            case I2PSigningKey.SigningKeyTypes.ECDSA_SHA384_P384:
            {
                var param  = NistNamedCurves.GetByName("P-384");
                var domain = new ECDomainParameters(param.Curve, param.G, param.N, param.H);

                var q           = domain.G.Multiply(privkey.ToBigInteger());
                var publicparam = new ECPublicKeyParameters(q, domain);
                Key = new BufLen(publicparam.Q.GetEncoded(), 1);
            }
            break;

            case I2PSigningKey.SigningKeyTypes.ECDSA_SHA512_P521:
            {
                var param  = NistNamedCurves.GetByName("P-521");
                var domain = new ECDomainParameters(param.Curve, param.G, param.N, param.H);

                var q           = domain.G.Multiply(privkey.ToBigInteger());
                var publicparam = new ECPublicKeyParameters(q, domain);
                Key = new BufLen(publicparam.Q.GetEncoded(), 1);
            }
            break;

            case SigningKeyTypes.EdDSA_SHA512_Ed25519:
                Key = new BufLen(Chaos.NaCl.Ed25519.PublicKeyFromSeed(privkey.Key.ToByteArray()));
                break;

            default:
                throw new NotImplementedException();
            }
        }
示例#2
0
        private static AsymmetricCipherKeyPair GenerateKeys()
        {
            var curve        = NistNamedCurves.GetByName("P-256");
            var domainParams = new ECDomainParameters(curve.Curve, curve.G, curve.N, curve.H, curve.GetSeed());

            var secureRandom = new SecureRandom();
            var keyParams    = new ECKeyGenerationParameters(domainParams, secureRandom);

            var generator = new ECKeyPairGenerator("ECDSA");

            generator.Init(keyParams);

            return(generator.GenerateKeyPair());
        }
示例#3
0
        public void TestECDsaP224Sha224()
        {
            X9ECParameters p          = NistNamedCurves.GetByName("P-224");
            var            parameters = new ECDomainParameters(p.Curve, p.G, p.N, p.H);
            var            priKey     = new ECPrivateKeyParameters(
                new BigInteger("6081831502424510080126737029209236539191290354021104541805484120491"), // d
                parameters);
            SecureRandom k =
                FixedSecureRandom.From(
                    BigIntegers.AsUnsignedByteArray(
                        new BigInteger("15456715103636396133226117016818339719732885723579037388121116732601")));

            byte[] m = Hex.Decode("8797A3C693CC292441039A4E6BAB7387F3B4F2A63D00ED384B378C79");

            var dsa = new ECDsaSigner();

            dsa.Init(true, new ParametersWithRandom(priKey, k));

            IBigInteger[] sig = dsa.GenerateSignature(m);

            IBigInteger r = new BigInteger("26477406756127720855365980332052585411804331993436302005017227573742");
            IBigInteger s = new BigInteger("17694958233103667059888193972742186995283044672015112738919822429978");

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

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

            // Verify the signature
            var pubKey = new ECPublicKeyParameters(
                parameters.Curve.DecodePoint(Hex.Decode("03FD44EC11F9D43D9D23B1E1D1C9ED6519B40ECF0C79F48CF476CC43F1")),
                // Q
                parameters);

            dsa.Init(false, pubKey);
            if (!dsa.VerifySignature(m, sig[0], sig[1]))
            {
                Fail("signature fails");
            }
        }
示例#4
0
        private static AsymmetricCipherKeyPair getKATKeyPair()
        {
            X9ECParameters         p          = NistNamedCurves.GetByName("P-256");
            EcDomainParameters     parameters = new EcDomainParameters(p.Curve, p.G, p.N, p.H);
            ECPrivateKeyParameters priKey     = new ECPrivateKeyParameters(
                new BigInteger("20186677036482506117540275567393538695075300175221296989956723148347484984008"),                 // d
                parameters);

            // Verify the signature
            ECPublicKeyParameters pubKey = new ECPublicKeyParameters(
                parameters.Curve.DecodePoint(Hex.Decode("03596375E6CE57E0F20294FC46BDFCFD19A39F8161B58695B3EC5B3D16427C274D")),                 // Q
                parameters);

            return(new AsymmetricCipherKeyPair(pubKey, priKey));
        }
        private BigInteger[] SignData(BigInteger privateKey, byte[] data)
        {
            // TODO: put curve name
            string                 curveName     = "";
            var                    curve         = NistNamedCurves.GetByName(curveName);
            ECDomainParameters     ecSpec        = new ECDomainParameters(curve.Curve, curve.G, curve.N, curve.H);
            ECPrivateKeyParameters keyParameters = new ECPrivateKeyParameters(privateKey, ecSpec);
            IDsaKCalculator        kCalculator   = new HMacDsaKCalculator(new Sha256Digest());
            ECDsaSigner            signer        = new ECDsaSigner(kCalculator);

            signer.Init(true, keyParameters);
            BigInteger[] signature = signer.GenerateSignature(data);

            return(signature);
        }
        public void NoncompliantGetByName(string arg)
        {
            X9ECParameters curve = null;

            // Elliptic curves always have the key length as part of their names. Rule implementation looks for this
            // key length pattern, so that all curves with a key length smaller than 224 will raise an issue
            curve = SecNamedCurves.GetByName("secp192k1");             // Noncompliant {{Use a key length of at least 224 bits for EC cipher algorithm.}}
            curve = SecNamedCurves.GetByName("secp192r1");             // Noncompliant
            curve = SecNamedCurves.GetByName("sect163k1");             // Noncompliant
            curve = SecNamedCurves.GetByName("sect163r1");             // Noncompliant
            curve = SecNamedCurves.GetByName("sect163r2");             // Noncompliant
            curve = SecNamedCurves.GetByName("sect193r1");             // Noncompliant
            curve = SecNamedCurves.GetByName("sect193r2");             // Noncompliant

            curve = X962NamedCurves.GetByName("prime192v1");           // Noncompliant
            curve = X962NamedCurves.GetByName("prime192v2");           // Noncompliant
            curve = X962NamedCurves.GetByName("prime192v3");           // Noncompliant
            curve = X962NamedCurves.GetByName("c2pnb163v1");           // Noncompliant
            curve = X962NamedCurves.GetByName("c2pnb163v2");           // Noncompliant
            curve = X962NamedCurves.GetByName("c2pnb163v3");           // Noncompliant
            curve = X962NamedCurves.GetByName("c2pnb176w1");           // Noncompliant
            curve = X962NamedCurves.GetByName("c2tnb191v1");           // Noncompliant
            curve = X962NamedCurves.GetByName("c2tnb191v2");           // Noncompliant
            curve = X962NamedCurves.GetByName("c2tnb191v3");           // Noncompliant
            curve = X962NamedCurves.GetByName("c2pnb208w1");           // Noncompliant

            curve = TeleTrusTNamedCurves.GetByName("brainpoolp160r1"); // Noncompliant
            curve = TeleTrusTNamedCurves.GetByName("brainpoolp160t1"); // Noncompliant
            curve = TeleTrusTNamedCurves.GetByName("brainpoolp192r1"); // Noncompliant
            curve = TeleTrusTNamedCurves.GetByName("brainpoolp192t1"); // Noncompliant

            curve = NistNamedCurves.GetByName("B-163");                // Noncompliant
            curve = NistNamedCurves.GetByName("K-163");                // Noncompliant
            curve = NistNamedCurves.GetByName("P-192");                // Noncompliant

            curve = ECNamedCurveTable.GetByName("secp192k1");          // Noncompliant
            curve = ECNamedCurveTable.GetByName("c2pnb208w1");         // Noncompliant
            curve = ECNamedCurveTable.GetByName("brainpoolp192t1");    // Noncompliant
            curve = ECNamedCurveTable.GetByName("B-163");              // Noncompliant

            ECNamedCurveTable.GetByName(arg);                          // Compliant
            var variable = "RandomString";

            ECNamedCurveTable.GetByName(variable);  // Compliant
            variable = "B-163";
            ECNamedCurveTable.GetByName(variable);  // Noncompliant
        }
示例#7
0
        public static void NewKey()
        {
            if (false)
            {
                X9ECParameters p = NistNamedCurves.GetByName("P-256");

                ECDomainParameters parameters = new ECDomainParameters(p.Curve, p.G, p.N, p.H);

                ECKeyPairGenerator        pGen     = new ECKeyPairGenerator();
                ECKeyGenerationParameters genParam = new ECKeyGenerationParameters(parameters, new Org.BouncyCastle.Security.SecureRandom());
                pGen.Init(genParam);

                AsymmetricCipherKeyPair p1 = pGen.GenerateKeyPair();

                CBORObject epk = CBORObject.NewMap();
                epk.Add(CoseKeyKeys.KeyType, GeneralValues.KeyType_EC);
                epk.Add(CoseKeyParameterKeys.EC_Curve, "P-384");
                ECPublicKeyParameters priv = (ECPublicKeyParameters)p1.Public;
                epk.Add(CoseKeyParameterKeys.EC_X, priv.Q.Normalize().XCoord.ToBigInteger().ToByteArrayUnsigned());
                epk.Add(CoseKeyParameterKeys.EC_Y, priv.Q.Normalize().YCoord.ToBigInteger().ToByteArrayUnsigned());
                epk.Add(CoseKeyParameterKeys.EC_D, ((ECPrivateKeyParameters)p1.Private).D.ToByteArrayUnsigned());

                string xxx = epk.ToJSONString();
            }
            else
            {
                X9ECParameters p = CustomNamedCurves.GetByName("CURVE25519");

                ECDomainParameters parameters = new ECDomainParameters(p.Curve, p.G, p.N, p.H);

                ECKeyPairGenerator        pGen     = new ECKeyPairGenerator();
                ECKeyGenerationParameters genParam = new ECKeyGenerationParameters(parameters, new Org.BouncyCastle.Security.SecureRandom());
                pGen.Init(genParam);

                AsymmetricCipherKeyPair p1 = pGen.GenerateKeyPair();

                CBORObject epk = CBORObject.NewMap();
                epk.Add(CoseKeyKeys.KeyType, GeneralValues.KeyType_OKP);
                epk.Add(CoseKeyParameterKeys.OKP_Curve, GeneralValues.X25519);
                ECPublicKeyParameters priv = (ECPublicKeyParameters)p1.Public;
                epk.Add(CoseKeyParameterKeys.EC_X, priv.Q.Normalize().XCoord.ToBigInteger().ToByteArrayUnsigned());
                epk.Add(CoseKeyParameterKeys.EC_D, ((ECPrivateKeyParameters)p1.Private).D.ToByteArrayUnsigned());

                string xxx = epk.ToJSONString();
            }
        }
示例#8
0
        public void TestECDsaP256Sha256()
        {
            X9ECParameters         p          = NistNamedCurves.GetByName("P-256");
            ECDomainParameters     parameters = new ECDomainParameters(p.Curve, p.G, p.N, p.H);
            ECPrivateKeyParameters priKey     = new ECPrivateKeyParameters(
                new BigInteger("20186677036482506117540275567393538695075300175221296989956723148347484984008"), // d
                parameters);
            SecureRandom k = FixedSecureRandom.From(BigIntegers.AsUnsignedByteArray(new BigInteger("72546832179840998877302529996971396893172522460793442785601695562409154906335")));

            byte[] M = Hex.Decode("1BD4ED430B0F384B4E8D458EFF1A8A553286D7AC21CB2F6806172EF5F94A06AD");

            ECDsaSigner dsa = new ECDsaSigner();

            dsa.Init(true, new ParametersWithRandom(priKey, k));

            BigInteger[] sig = dsa.GenerateSignature(M);

            BigInteger r = new BigInteger("97354732615802252173078420023658453040116611318111190383344590814578738210384");
            BigInteger s = new BigInteger("98506158880355671805367324764306888225238061309262649376965428126566081727535");

            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]);
            }

            // Verify the signature
            ECPublicKeyParameters pubKey = new ECPublicKeyParameters(
                parameters.Curve.DecodePoint(Hex.Decode("03596375E6CE57E0F20294FC46BDFCFD19A39F8161B58695B3EC5B3D16427C274D")), // Q
                parameters);

            dsa.Init(false, pubKey);
            if (!dsa.VerifySignature(M, sig[0], sig[1]))
            {
                Fail("signature fails");
            }
        }
示例#9
0
        public X9ECParameters GetCurve()
        {
            CBORObject cborKeyType = m_map[CoseKeyKeys.KeyType];

            if (cborKeyType == null)
            {
                throw new CoseException("Malformed key struture");
            }
            if ((cborKeyType.Type != CBORType.Number) &&
                !((cborKeyType == GeneralValues.KeyType_EC) || (cborKeyType == GeneralValues.KeyType_OKP)))
            {
                throw new CoseException("Not an EC key");
            }

            CBORObject cborCurve = m_map[CoseKeyParameterKeys.EC_Curve];

            if (cborCurve.Type == CBORType.Number)
            {
                switch ((GeneralValuesInt)cborCurve.AsInt32())
                {
                case GeneralValuesInt.P256: return(NistNamedCurves.GetByName("P-256"));

                case GeneralValuesInt.P384: return(NistNamedCurves.GetByName("P-384"));

                case GeneralValuesInt.P521: return(NistNamedCurves.GetByName("P-521"));

                case GeneralValuesInt.X25519: return(CustomNamedCurves.GetByName("CURVE25519"));

                default:
                    throw new CoseException("Unsupported key type: " + cborKeyType.AsInt32());
                }
            }
            else if (cborCurve.Type == CBORType.TextString)
            {
                switch (cborCurve.AsString())
                {
                default:
                    throw new CoseException("Unsupported key type: " + cborKeyType.AsString());
                }
            }
            else
            {
                throw new CoseException("Incorrectly encoded key type");
            }
        }
示例#10
0
        public static bool Verify(byte[] message, byte[] signature, byte[] pubkey, Phantasma.Cryptography.ECC.ECDsaCurve phaCurve = Phantasma.Cryptography.ECC.ECDsaCurve.Secp256r1, SignatureFormat signatureFormat = SignatureFormat.Concatenated)
        {
            var signer = SignerUtilities.GetSigner("SHA256withECDSA");

            Org.BouncyCastle.Asn1.X9.X9ECParameters curve;
            switch (phaCurve)
            {
            case Phantasma.Cryptography.ECC.ECDsaCurve.Secp256k1:
                curve = Org.BouncyCastle.Asn1.Sec.SecNamedCurves.GetByName("secp256k1");
                break;

            default:
                curve = NistNamedCurves.GetByName("P-256");
                break;
            }
            var dom = new ECDomainParameters(curve.Curve, curve.G, curve.N, curve.H);

            var point = dom.Curve.DecodePoint(pubkey);
            var publicKeyParameters = new ECPublicKeyParameters(point, dom);

            signer.Init(false, publicKeyParameters);
            signer.BlockUpdate(message, 0, message.Length);

            switch (signatureFormat)
            {
            case SignatureFormat.Concatenated:
                // We convert from concatenated "raw" R + S format to DER format that Bouncy Castle uses.
                signature = new Org.BouncyCastle.Asn1.DerSequence(
                    // first 32 bytes is "r" number
                    new Org.BouncyCastle.Asn1.DerInteger(new BigInteger(1, signature.Take(32).ToArray())),
                    // last 32 bytes is "s" number
                    new Org.BouncyCastle.Asn1.DerInteger(new BigInteger(1, signature.Skip(32).ToArray())))
                            .GetDerEncoded();
                break;

            case SignatureFormat.DEREncoded:
                // Do nothing, signature already DER-encoded.
                break;

            default:
                throw new Exception("Unknown signature format");
            }

            return(signer.VerifySignature(signature));
        }
示例#11
0
        public void TestECDsaP521Sha512()
        {
            X9ECParameters         p          = NistNamedCurves.GetByName("P-521");
            ECDomainParameters     parameters = new ECDomainParameters(p.Curve, p.G, p.N, p.H);
            ECPrivateKeyParameters priKey     = new ECPrivateKeyParameters(
                new BigInteger("617573726813476282316253885608633222275541026607493641741273231656161177732180358888434629562647985511298272498852936680947729040673640492310550142822667389"), // d
                parameters);
            SecureRandom k = FixedSecureRandom.From(BigIntegers.AsUnsignedByteArray(new BigInteger("6806532878215503520845109818432174847616958675335397773700324097584974639728725689481598054743894544060040710846048585856076812050552869216017728862957612913")));

            byte[] M = Hex.Decode("6893B64BD3A9615C39C3E62DDD269C2BAAF1D85915526083183CE14C2E883B48B193607C1ED871852C9DF9C3147B574DC1526C55DE1FE263A676346A20028A66");

            ECDsaSigner dsa = new ECDsaSigner();

            dsa.Init(true, new ParametersWithRandom(priKey, k));

            BigInteger[] sig = dsa.GenerateSignature(M);

            BigInteger r = new BigInteger("1368926195812127407956140744722257403535864168182534321188553460365652865686040549247096155740756318290773648848859639978618869784291633651685766829574104630");
            BigInteger s = new BigInteger("1624754720348883715608122151214003032398685415003935734485445999065609979304811509538477657407457976246218976767156629169821116579317401249024208611945405790");

            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]);
            }

            // Verify the signature
            ECPublicKeyParameters pubKey = new ECPublicKeyParameters(
                parameters.Curve.DecodePoint(Hex.Decode("020145E221AB9F71C5FE740D8D2B94939A09E2816E2167A7D058125A06A80C014F553E8D6764B048FB6F2B687CEC72F39738F223D4CE6AFCBFF2E34774AA5D3C342CB3")), // Q
                parameters);

            dsa.Init(false, pubKey);
            if (!dsa.VerifySignature(M, sig[0], sig[1]))
            {
                Fail("signature fails");
            }
        }
示例#12
0
        /// <summary>
        /// Creates a random key pair from given curve name
        /// </summary>
        /// <param name="curveName"></param>
        /// <returns></returns>
        public List <byte[]> CreateRandomKeyPair(string curveName)
        {
            var keyPair = new List <byte[]>();
            var ecp     = TeleTrusTNamedCurves.GetByName(curveName);

            if (ecp == null)
            {
                ecp = NistNamedCurves.GetByName(curveName);
            }
            AsymmetricCipherKeyPair kp        = null;
            ECPublicKeyParameters   publicKey = null;
            bool success = false;

            while (!success)
            {
                IAsymmetricCipherKeyPairGenerator kpg = GeneratorUtilities.GetKeyPairGenerator("ECDSA");

                var parameters = new ECDomainParameters(ecp.Curve, ecp.G, ecp.N, ecp.H, ecp.GetSeed());
                var ecP        = new ECKeyGenerationParameters(parameters, new SecureRandom());
                kpg.Init(ecP);
                kp = kpg.GenerateKeyPair();

                publicKey = (ECPublicKeyParameters)kp.Public;
                publicKey = SetPublicUncompressed(publicKey);

                byte[] x = publicKey.Q.AffineXCoord.ToBigInteger().ToByteArrayUnsigned();
                byte[] y = publicKey.Q.AffineYCoord.ToBigInteger().ToByteArrayUnsigned();
                if (x.Length == y.Length)
                {
                    success = true;
                }
            }
            ECPrivateKeyParameters privateKey = (ECPrivateKeyParameters)kp.Private;

            if (KeysVerified(privateKey, publicKey, curveName))
            {
                var privateBytes = privateKey.D.ToByteArrayUnsigned();
                var pubKeyBytes  = publicKey.Q.GetEncoded();
                keyPair.Add(privateBytes);
                keyPair.Add(pubKeyBytes);
            }

            return(keyPair);
        }
示例#13
0
//		private static ECDomainParameters GetCurveParameters(
        private static X9ECParameters GetCurveParameters(
            string name)
        {
            X9ECParameters ecP = X962NamedCurves.GetByName(name);

            if (ecP == null)
            {
                ecP = SecNamedCurves.GetByName(name);
                if (ecP == null)
                {
                    ecP = NistNamedCurves.GetByName(name);
                    if (ecP == null)
                    {
                        throw new Exception("unknown curve name: " + name);
                    }
                }
            }

//			return new ECDomainParameters(ecP.Curve, ecP.G, ecP.N, ecP.H, ecP.GetSeed());
            return(ecP);
        }
示例#14
0
        public static Byte[] getSharedSecret(Byte[] PrivateKeyIn, Byte[] PublicKeyIn)
        {
            ECDHCBasicAgreement    agreement = new ECDHCBasicAgreement();
            X9ECParameters         curve     = null;
            ECDomainParameters     ecParam   = null;
            ECPrivateKeyParameters privKey   = null;
            ECPublicKeyParameters  pubKey    = null;
            ECPoint point = null;

            curve   = NistNamedCurves.GetByName("P-256");
            ecParam = new ECDomainParameters(curve.Curve, curve.G, curve.N, curve.H, curve.GetSeed());
            privKey = new ECPrivateKeyParameters(new BigInteger(PrivateKeyIn), ecParam);
            point   = ecParam.Curve.DecodePoint(PublicKeyIn);
            pubKey  = new ECPublicKeyParameters(point, ecParam);

            agreement.Init(privKey);

            BigInteger secret = agreement.CalculateAgreement(pubKey);

            return(secret.ToByteArrayUnsigned());
        }
示例#15
0
        public ICipherParameters AsPublicKey()
        {
            if (PublicKeyX != null)
            {
                return(PublicKeyX);
            }

            switch (_json["kty"].AsString())
            {
            case "EC":
                X9ECParameters        p          = NistNamedCurves.GetByName(this.AsString("crv"));
                ECDomainParameters    parameters = new ECDomainParameters(p.Curve, p.G, p.N, p.H);
                ECPoint               point      = p.Curve.CreatePoint(this.AsBigInteger("x"), this.AsBigInteger("y"));
                ECPublicKeyParameters pubKey     = new ECPublicKeyParameters(point, parameters);
                PublicKeyX = pubKey;
                break;
            }


            return(PublicKeyX);
        }
示例#16
0
        /**
         * return a X9ECParameters object representing the passed in named
         * curve. The routine returns null if the curve is not present.
         *
         * @param name the name of the curve requested
         * @return an X9ECParameters object or null if the curve is not available.
         */
        public static X9ECParameters GetByName(string name)
        {
            X9ECParameters ecP = X962NamedCurves.GetByName(name);

            if (ecP == null)
            {
                ecP = SecNamedCurves.GetByName(name);
            }

            if (ecP == null)
            {
                ecP = TeleTrusTNamedCurves.GetByName(name);
            }

            if (ecP == null)
            {
                ecP = NistNamedCurves.GetByName(name);
            }

            return(ecP);
        }
示例#17
0
        public static byte[] GetSharedSecret(byte[] localPrivateKeyBytes, byte[] remotePublicKeyBytes)
        {
            var             curve = NistNamedCurves.GetByName("P-256");
            var             dom   = new ECDomainParameters(curve.Curve, curve.G, curve.N, curve.H);
            ECKeyParameters privateKeyParameters = new ECPrivateKeyParameters(new BigInteger(1, localPrivateKeyBytes), dom);

            var q = curve.Curve.DecodePoint(new byte[] { 0x04 }.Concat(remotePublicKeyBytes).ToArray());

            ECKeyParameters publicKeyParameters = new ECPublicKeyParameters(q, dom);

            var agreement = new ECDHBasicAgreement();

            agreement.Init(privateKeyParameters);

            using (var sha = SHA256.Create())
            {
                // CalculateAgreement returns a BigInteger, whose length is variable, and bits are not whitened, so hash it.
                var temp = agreement.CalculateAgreement(publicKeyParameters).ToByteArray();
                return(sha.ComputeHash(temp));
            }
        }
        public static BigInteger CalculateSharedKey(BigInteger BIx, BigInteger BIy, ECPrivateKeyParameters privateKey)
        {
            IBasicAgreement aKeyAgree = AgreementUtilities.GetBasicAgreement("ECDH");

            aKeyAgree.Init(privateKey);

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

            FpCurve c = (FpCurve)ecSpec.Curve;

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

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

            BigInteger k1 = aKeyAgree.CalculateAgreement(publicKey);

            return(k1);
        }
示例#19
0
        static void ECCTest()
        {
            string curveName = "P-521";
            var    ecP1      = AnssiNamedCurves.GetByName("FRP256v1");
            var    ecP21     = TeleTrusTNamedCurves.GetByName("brainpoolp512t1");
            var    ecP       = NistNamedCurves.GetByName(curveName);
            var    random    = new SecureRandom();

            var eCDomainParameters = new ECDomainParameters(ecP.Curve, ecP.G, ecP.N, ecP.H, ecP.GetSeed());
            var pGen     = new ECKeyPairGenerator();
            var genParam = new ECKeyGenerationParameters(
                eCDomainParameters,
                random);

            pGen.Init(genParam);
            var asymmetricCipherKeyPair = pGen.GenerateKeyPair();

            var senderPrivate = ((ECPrivateKeyParameters)asymmetricCipherKeyPair.Private).D.ToByteArray();
            var senderPublic  = ((ECPublicKeyParameters)asymmetricCipherKeyPair.Public).Q.GetEncoded();

            var asymmetricCipherKeyPairA = pGen.GenerateKeyPair();

            var recieverPrivate = ((ECPrivateKeyParameters)asymmetricCipherKeyPairA.Private).D.ToByteArray();

            var recieverPublic = ((ECPublicKeyParameters)asymmetricCipherKeyPairA.Public).Q.GetEncoded();

            var sharedSecret = GetSharedSecretValue(asymmetricCipherKeyPair, asymmetricCipherKeyPairA);

            var deriveSecret = DeriveSymmetricKeyFromSharedSecret(sharedSecret);

            var    encrypted = Encrypt(Encoding.UTF8.GetBytes(original), deriveSecret);
            var    roundtrip = Encoding.UTF8.GetString(Decrypt(encrypted, deriveSecret));
            string hex       = Epic.Converters.HexString.Encode(encrypted);
            string base64    = Convert.ToBase64String(encrypted);

            Console.WriteLine("Byte:   {0}", encrypted.Length);
            Console.WriteLine("Hex:   {0}, {1}", hex.Length, hex);
            Console.WriteLine("Base64:   {0}, {1}", base64.Length, base64);
            Console.WriteLine("Decode: {0}", roundtrip);
        }
示例#20
0
        public static SqlString getSignature(SqlString keySize, SqlString PrivateKey, SqlString Message)
        {
            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;
            ECCurve curve = ecParams.Curve;

            //private Key
            BigInteger             d             = new BigInteger(PrivateKey.ToString(), 10);
            ECPrivateKeyParameters keyParameters = new ECPrivateKeyParameters(d, domainParameters);

            //public key
            ECPoint q = domainParameters.G.Multiply(d);
            ECPublicKeyParameters pubkeyParam = new ECPublicKeyParameters(q, domainParameters);

            string s            = Message.ToString();
            var    signature    = BCFunctions.GetSignature(s, keyParameters);
            var    signedString = Convert.ToBase64String(signature);
            var    txtSignature = signedString;

            return(txtSignature);
        }
示例#21
0
    public byte[] Sign(byte[] message, byte[] prikey, byte[] pubkey)
    {
      X9ECParameters ecParams = NistNamedCurves.GetByName("P-256");
      ECDomainParameters domainParameters = new ECDomainParameters(ecParams.Curve, ecParams.G, ecParams.N,
        ecParams.H, ecParams.GetSeed());
      ECPrivateKeyParameters privKeyParam = new ECPrivateKeyParameters(
          new BigInteger(1, prikey), // d
          domainParameters);
      ISigner signer = SignerUtilities.GetSigner("SHA-256withECDSA");
      signer.Init(true, privKeyParam);
      signer.BlockUpdate(message, 0, message.Length);

      //https://crypto.stackexchange.com/questions/1795/how-can-i-convert-a-der-ecdsa-signature-to-asn-1
      var signature = signer.GenerateSignature();
      var resSignature = new byte[64];
      int i = signature[3] == 33 ? 5 : 4;
      Array.Copy(signature, i, resSignature, 0, 32);
      i += 32 + 1;
      i = signature[i] == 33 ? i + 2 : i + 1;
      Array.Copy(signature, i, resSignature, 32, 32);
      return resSignature;
    }
示例#22
0
        public static X9ECParameters GetByName(string name)
        {
            X9ECParameters byName = X962NamedCurves.GetByName(name);

            if (byName == null)
            {
                byName = SecNamedCurves.GetByName(name);
            }
            if (byName == null)
            {
                byName = NistNamedCurves.GetByName(name);
            }
            if (byName == null)
            {
                byName = TeleTrusTNamedCurves.GetByName(name);
            }
            if (byName == null)
            {
                byName = AnssiNamedCurves.GetByName(name);
            }
            return(byName);
        }
示例#23
0
        public static byte[] Sign(byte[] message, byte[] prikey, byte[] pubkey)
        {
            var             signer = SignerUtilities.GetSigner("SHA256withECDSA");
            var             curve  = NistNamedCurves.GetByName("P-256");
            var             dom    = new ECDomainParameters(curve.Curve, curve.G, curve.N, curve.H);
            ECKeyParameters privateKeyParameters = new ECPrivateKeyParameters(new BigInteger(1, prikey), dom);

            signer.Init(true, privateKeyParameters);
            signer.BlockUpdate(message, 0, message.Length);
            var sig = signer.GenerateSignature();

            return(TranscodeSignatureToConcat(sig, 64));

#if OLD_VERSION
#if NET461
            const int ECDSA_PRIVATE_P256_MAGIC = 0x32534345;
            prikey = BitConverter.GetBytes(ECDSA_PRIVATE_P256_MAGIC).Concat(BitConverter.GetBytes(32)).Concat(pubkey).Concat(prikey).ToArray();
            using (CngKey key = CngKey.Import(prikey, CngKeyBlobFormat.EccPrivateBlob))
                using (ECDsaCng ecdsa = new ECDsaCng(key))
                {
                    return(ecdsa.SignData(message, HashAlgorithmName.SHA256));
                }
#else
            using (var ecdsa = ECDsa.Create(new ECParameters
            {
                Curve = ECCurve.NamedCurves.nistP256,
                D = prikey,
                Q = new ECPoint
                {
                    X = pubkey.Take(32).ToArray(),
                    Y = pubkey.Skip(32).ToArray()
                }
            }))
            {
                return(ecdsa.SignData(message, HashAlgorithmName.SHA256));
            }
#endif
#endif
        }
示例#24
0
        public void Should_GeneratePointOnCurve_When_RandomHashesArePassed()
        {
            var curveParams = NistNamedCurves.GetByName("P-256");

            var swu    = new Swu(((FpCurve)curveParams.Curve).Q, curveParams.Curve.B.ToBigInteger());
            var rng    = new SecureRandom();
            var sha    = new Sha512tDigest(256);
            var random = new byte[32];

            for (int i = 0; i <= 10000; i++)
            {
                var hash = new byte[32];

                rng.NextBytes(random);
                sha.BlockUpdate(random, 0, random.Length);
                sha.DoFinal(hash, 0);

                var(x, y) = swu.HashToPoint(hash);
                Assert.True(curveParams.Curve.CreatePoint(x, y).IsValid());

                sha.Reset();
            }
        }
示例#25
0
        void OnSvAppSecureHandshake(string id, JsonObj args)
        {
            // https://davidtavarez.github.io/2019/implementing-elliptic-curve-diffie-hellman-c-sharp/
            X9ECParameters     x9Params     = NistNamedCurves.GetByName("P-521");
            ECDomainParameters domainParams = new ECDomainParameters(x9Params.Curve, x9Params.G, x9Params.N, x9Params.H, x9Params.GetSeed());
            ECKeyPairGenerator generator    = (ECKeyPairGenerator)GeneratorUtilities.GetKeyPairGenerator("ECDH");

            generator.Init(new ECKeyGenerationParameters(domainParams, new SecureRandom()));
            AsymmetricCipherKeyPair aliceKeyPair         = generator.GenerateKeyPair();
            ECPublicKeyParameters   alicePublicKeyParams = (ECPublicKeyParameters)aliceKeyPair.Public;

            string bobKey = args.Get <string>("key");

            byte[] bobKeyBytes = System.Convert.FromBase64String(bobKey);
            var    bobPoint    = x9Params.Curve.DecodePoint(bobKeyBytes);
            ECPublicKeyParameters bobPublicKeyParams = new ECPublicKeyParameters("ECDH", bobPoint, SecObjectIdentifiers.SecP521r1);

            IBasicAgreement agreement = AgreementUtilities.GetBasicAgreement("ECDH");

            agreement.Init(aliceKeyPair.Private);
            BigInteger sharedSecret = agreement.CalculateAgreement(bobPublicKeyParams);

            IDigest digest = new Sha256Digest();

            byte[] sharedSecretBytes = sharedSecret.ToBytes(66);
            digest.BlockUpdate(sharedSecretBytes, 0, sharedSecretBytes.Length);
            derivedKeyBytes = new byte[digest.GetDigestSize()];
            digest.DoFinal(derivedKeyBytes, 0);

            Debug.Log(System.BitConverter.ToString(sharedSecretBytes));
            Debug.Log(System.Convert.ToBase64String(derivedKeyBytes));

            ReturnSuccess(id, new JsonObj()
            {
                ["key"] = alicePublicKeyParams.Q.GetEncoded(),
            });
        }
示例#26
0
        /// <summary>
        /// Creates a Signature
        /// </summary>
        /// <param name="data"></param>
        /// <param name="privateKey"></param>
        /// <param name="curveName"></param>
        /// <returns></returns>
        public byte[] CreateSignature(byte[] data, byte[] privateKey, string curveName)
        {
            //Get the curve type ec parameters
            var ecp = TeleTrusTNamedCurves.GetByName(curveName);

            if (ecp == null)
            {
                ecp = NistNamedCurves.GetByName(curveName);
            }
            var domainParameters = new ECDomainParameters(ecp.Curve, ecp.G, ecp.N, ecp.H, ecp.GetSeed());
            var myPriKey         = new ECPrivateKeyParameters(new BigInteger(1, privateKey), domainParameters);

            //Create the signer and initialize with private key
            var dsa = new ECDsaSigner();

            dsa.Init(true, myPriKey);

            //The signature halves must be equal in length
            BigInteger[] signature;
            do
            {
                signature = dsa.GenerateSignature(data);
            }while (signature[0].ToByteArrayUnsigned().Length != signature[1].ToByteArrayUnsigned().Length);

            //Save both halves in a list
            var sign = new List <byte>();

            foreach (var bigInt in signature)
            {
                foreach (var bite in bigInt.ToByteArrayUnsigned())
                {
                    sign.Add(bite);
                }
            }

            return(sign.ToArray());
        }
示例#27
0
        public static byte[] Sign(byte[] message, byte[] prikey, byte[] pubkey, Phantasma.Cryptography.ECC.ECDsaCurve phaCurve = Phantasma.Cryptography.ECC.ECDsaCurve.Secp256r1, SignatureFormat signatureFormat = SignatureFormat.Concatenated)
        {
            var signer = SignerUtilities.GetSigner("SHA256withECDSA");

            Org.BouncyCastle.Asn1.X9.X9ECParameters curve;
            switch (phaCurve)
            {
            case Phantasma.Cryptography.ECC.ECDsaCurve.Secp256k1:
                curve = Org.BouncyCastle.Asn1.Sec.SecNamedCurves.GetByName("secp256k1");
                break;

            default:
                curve = NistNamedCurves.GetByName("P-256");
                break;
            }
            var             dom = new ECDomainParameters(curve.Curve, curve.G, curve.N, curve.H);
            ECKeyParameters privateKeyParameters = new ECPrivateKeyParameters(new BigInteger(1, prikey), dom);

            signer.Init(true, privateKeyParameters);
            signer.BlockUpdate(message, 0, message.Length);
            var sig = signer.GenerateSignature();

            switch (signatureFormat)
            {
            case SignatureFormat.Concatenated:
                // We convert from default DER format that Bouncy Castle uses to concatenated "raw" R + S format.
                return(TranscodeSignatureToConcat(sig, 64));

            case SignatureFormat.DEREncoded:
                // Return DER-encoded signature unchanged.
                return(sig);

            default:
                throw new Exception("Unknown signature format");
            }
        }
示例#28
0
        /// <summary>
        /// Verifies the signature
        /// </summary>
        /// <param name="data"></param>
        /// <param name="signature"></param>
        /// <param name="publicKey"></param>
        /// <param name="curveName"></param>
        /// <returns></returns>
        public bool VerifiySignature(byte[] data, byte[] signature, byte[] publicKey, string curveName)
        {
            //Get curve type ec parameters
            var ecp = TeleTrusTNamedCurves.GetByName(curveName);

            if (ecp == null)
            {
                ecp = NistNamedCurves.GetByName(curveName);
            }
            var domainParameters = new ECDomainParameters(ecp.Curve, ecp.G, ecp.N, ecp.H, ecp.GetSeed());
            var publicKeyParam   = CreatePublicKeyParam(domainParameters, publicKey);

            //Create the signer and initialize with public key
            var dsa = new ECDsaSigner();

            dsa.Init(false, publicKeyParam);

            var r = new BigInteger(1, signature.Take(signature.Length / 2).ToArray());
            var s = new BigInteger(1, signature.Skip(signature.Length / 2).ToArray());

            var verified = dsa.VerifySignature(data, r, s);

            return(verified);
        }
示例#29
0
        public static byte[] Sign(byte[] message, byte[] prikey, byte[] pubkey, Phantasma.Cryptography.ECC.ECDsaCurve phaCurve = Phantasma.Cryptography.ECC.ECDsaCurve.Secp256r1)
        {
            var signer = SignerUtilities.GetSigner("SHA256withECDSA");

            Org.BouncyCastle.Asn1.X9.X9ECParameters curve;
            switch (phaCurve)
            {
            case Phantasma.Cryptography.ECC.ECDsaCurve.Secp256k1:
                curve = Org.BouncyCastle.Asn1.Sec.SecNamedCurves.GetByName("secp256k1");
                break;

            default:
                curve = NistNamedCurves.GetByName("P-256");
                break;
            }
            var             dom = new ECDomainParameters(curve.Curve, curve.G, curve.N, curve.H);
            ECKeyParameters privateKeyParameters = new ECPrivateKeyParameters(new BigInteger(1, prikey), dom);

            signer.Init(true, privateKeyParameters);
            signer.BlockUpdate(message, 0, message.Length);
            var sig = signer.GenerateSignature();

            return(TranscodeSignatureToConcat(sig, 64));
        }
        public byte[] Decrypt(byte[] buffer, byte[] senderPublicKeyBytes, byte[] salt)
        {
            var ecP = NistNamedCurves.GetByName("P-256");
            ECDomainParameters eCDomainParameters = new ECDomainParameters(ecP.Curve, ecP.G, ecP.N);

            ECPoint pt = ecP.Curve.DecodePoint(senderPublicKeyBytes);
            ECPublicKeyParameters senderPublicKey = new ECPublicKeyParameters(pt, eCDomainParameters);

            var(key, nonce) = DeriveKeyAndNonce(salt, AuthSecret, senderPublicKey, publicKey, privateKey);

            byte[] result = new byte[0];
            var    start  = 0;

            // TODO: this is not tested with more than one iteration
            for (uint i = 0; start < buffer.Length; ++i)
            {
                var end = start + CHUNK_SIZE;
                if (end == buffer.Length)
                {
                    throw new InvalidOperationException("Truncated payload");
                }

                end = Math.Min(end, buffer.Length);

                if (end - start <= TAG_LENGTH)
                {
                    throw new InvalidOperationException("Invalid block: too small at " + i);
                }

                byte[] block = DecryptRecord(key, nonce, i, ByteArray.Slice(buffer, start, end), end >= buffer.Length);
                result = ByteArray.Concat(result, block);
                start  = end;
            }

            return(result);
        }