private ECPrivateKeyParameters ParseKey(string data)
        {
            Dictionary <string, string> values = ToDictionnary(data);

            var curveName = values["curve"].Replace("NIST", "");
            var curve     = SecNamedCurves.GetByOid(curves[curveName]);
            var domain    = new ECDomainParameters(curve.Curve, curve.G, new BigInteger(values["q"], 16), curve.H);

            Assert.Equal(domain.N, curve.N);

            var key = new ECPrivateKeyParameters(new BigInteger(values["x"], 16), domain);

            ECPoint pub = curve.G.Multiply(key.D);

            Assert.Equal(pub.X.ToBigInteger(), new BigInteger(values["Ux"], 16));
            Assert.Equal(pub.Y.ToBigInteger(), new BigInteger(values["Uy"], 16));

            return(key);
        }
        private void TestSig(ECPrivateKeyParameters key, DeterministicSigTest test)
        {
            if (test.Hash.Equals("SHA-1", StringComparison.OrdinalIgnoreCase))
            {
                return;
            }
            var dsa = new DeterministicECDSA(GetHash(test.Hash), false);

            dsa.setPrivateKey(key);
            dsa.update(Encoding.UTF8.GetBytes(test.Message));
            var result = dsa.sign();

            var signature = ECDSASignature.FromDER(result);

#pragma warning disable 618
            Assert.Equal(test.S, signature.S);
            Assert.Equal(test.R, signature.R);
#pragma warning restore 618
        }
예제 #3
0
        public override void GenerateClientKeyExchange(Stream output)
        {
            if (mPskIdentityHint == null)
            {
                mPskIdentity.SkipIdentityHint();
            }
            else
            {
                mPskIdentity.NotifyIdentityHint(mPskIdentityHint);
            }

            byte[] psk_identity = mPskIdentity.GetPskIdentity();
            if (psk_identity == null)
            {
                throw new TlsFatalAlert(AlertDescription.internal_error);
            }

            this.mPsk = mPskIdentity.GetPsk();
            if (mPsk == null)
            {
                throw new TlsFatalAlert(AlertDescription.internal_error);
            }

            TlsUtilities.WriteOpaque16(psk_identity, output);

            mContext.SecurityParameters.pskIdentity = psk_identity;

            if (this.mKeyExchange == KeyExchangeAlgorithm.DHE_PSK)
            {
                this.mDHAgreePrivateKey = TlsDHUtilities.GenerateEphemeralClientKeyExchange(mContext.SecureRandom,
                                                                                            mDHParameters, output);
            }
            else if (this.mKeyExchange == KeyExchangeAlgorithm.ECDHE_PSK)
            {
                this.mECAgreePrivateKey = TlsEccUtilities.GenerateEphemeralClientKeyExchange(mContext.SecureRandom,
                                                                                             mServerECPointFormats, mECAgreePublicKey.Parameters, output);
            }
            else if (this.mKeyExchange == KeyExchangeAlgorithm.RSA_PSK)
            {
                this.mPremasterSecret = TlsRsaUtilities.GenerateEncryptedPreMasterSecret(mContext,
                                                                                         this.mRsaServerPublicKey, output);
            }
        }
예제 #4
0
        private void checkSignature(
            int size,
            ECPrivateKeyParameters sKey,
            ECPublicKeyParameters vKey,
            ISigner sgr,
            SecureRandom k,
            byte[]                                      message,
            BigInteger r,
            BigInteger s)
        {
            sgr.Init(true, new ParametersWithRandom(sKey, k));

            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(size + " bit EC verification failed");
            }

            BigInteger[] sig = derDecode(sigBytes);

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

            if (!s.Equals(sig[1]))
            {
                Fail(size + "bit"
                     + ": s component wrong." + SimpleTest.NewLine
                     + " expecting: " + s + SimpleTest.NewLine
                     + " got      : " + sig[1]);
            }
        }
예제 #5
0
        public static ECPrivateKeyParameters loadprikey(string privateKey)
        {
            string prik;

            if (!privateKey.Contains("PRIVATE KEY"))
            {
                prik = ReadPK(privateKey);
            }
            else
            {
                prik = privateKey;
            }
            TextReader ptr = new StringReader(prik);

            Org.BouncyCastle.OpenSsl.PemReader pem           = new Org.BouncyCastle.OpenSsl.PemReader(ptr);
            ECPrivateKeyParameters             sm2PrivateKey = (ECPrivateKeyParameters)pem.ReadObject();

            return(sm2PrivateKey);
        }
예제 #6
0
        public SimulatedU2FKey([NotNull] X509Certificate vendorCertificate,
                               [NotNull] ECPrivateKeyParameters certificatePrivateKey, [NotNull] IKeyPairGenerator keyPairGenerator,
                               [NotNull] IKeyHandleGenerator keyHandleGenerator, [NotNull] IKeyDataStore dataStore,
                               [NotNull] IUserPresenceVerifier userPresenceVerifier, [NotNull] IKeyCrypto crypto)
        {
            if (vendorCertificate == null)
            {
                throw new ArgumentNullException(nameof(vendorCertificate));
            }
            if (certificatePrivateKey == null)
            {
                throw new ArgumentNullException(nameof(certificatePrivateKey));
            }
            if (keyPairGenerator == null)
            {
                throw new ArgumentNullException(nameof(keyPairGenerator));
            }
            if (keyHandleGenerator == null)
            {
                throw new ArgumentNullException(nameof(keyHandleGenerator));
            }
            if (dataStore == null)
            {
                throw new ArgumentNullException(nameof(dataStore));
            }
            if (userPresenceVerifier == null)
            {
                throw new ArgumentNullException(nameof(userPresenceVerifier));
            }
            if (crypto == null)
            {
                throw new ArgumentNullException(nameof(crypto));
            }

            this.vendorCertificate     = vendorCertificate;
            this.certificatePrivateKey = certificatePrivateKey;
            this.keyPairGenerator      = keyPairGenerator;
            this.keyHandleGenerator    = keyHandleGenerator;
            this.dataStore             = dataStore;
            this.userPresenceVerifier  = userPresenceVerifier;
            this.crypto = crypto;
        }
예제 #7
0
        private static ECDsa ConvertToSingKeyFormat(AsymmetricCipherKeyPair key)
        {
            ECPublicKeyParameters  pubAsyKey  = (ECPublicKeyParameters)key.Public;
            ECPrivateKeyParameters privAsyKey = (ECPrivateKeyParameters)key.Private;

            var signParam = new ECParameters
            {
                Curve = ECCurve.NamedCurves.nistP384,
                Q     =
                {
                    X = pubAsyKey.Q.AffineXCoord.GetEncoded(),
                    Y = pubAsyKey.Q.AffineYCoord.GetEncoded()
                }
            };

            signParam.D = CryptoUtils.FixDSize(privAsyKey.D.ToByteArrayUnsigned(), signParam.Q.X.Length);
            signParam.Validate();

            return(ECDsa.Create(signParam));
        }
예제 #8
0
        private static string Sign(string data)
        {
            var certBytes = File.ReadAllBytes("certificate.pfx");
            var cert      = new X509Certificate2(certBytes, ConvertToSecureString(Password));
            var bytes     = File.ReadAllBytes(@"private.key");

            var key           = new BigInteger(bytes);
            var keyParameters = new ECPrivateKeyParameters(KeyAlgorithm, key, PublicKeyParamSet);

            var signature = SignData(data, keyParameters);
            var parser    = new X509CertificateParser();
            var bcCert    = parser.ReadCertificate(cert.GetRawCertData());

            if (!VerifySignature(bcCert.GetPublicKey(), signature, data))
            {
                throw new Exception("sign error");
            }

            return(Convert.ToBase64String(signature));
        }
예제 #9
0
        public static Ecdsa Generate()
        {
            X9ECParameters     ecParams         = Org.BouncyCastle.Asn1.Sec.SecNamedCurves.GetByName("secp256k1");
            ECDomainParameters domainParameters = new ECDomainParameters(ecParams.Curve,
                                                                         ecParams.G, ecParams.N, ecParams.H,
                                                                         ecParams.GetSeed());
            ECKeyGenerationParameters keyGenParams =
                new ECKeyGenerationParameters(domainParameters, new SecureRandom());

            AsymmetricCipherKeyPair keyPair;
            ECKeyPairGenerator      generator = new ECKeyPairGenerator();

            generator.Init(keyGenParams);
            keyPair = generator.GenerateKeyPair();

            ECPrivateKeyParameters privateKey = (ECPrivateKeyParameters)keyPair.Private;
            ECPublicKeyParameters  publicKey  = (ECPublicKeyParameters)keyPair.Public;

            return(new Ecdsa(publicKey.Q.GetEncoded(), privateKey.D.ToByteArrayUnsigned()));
        }
예제 #10
0
        /// <summary>
        /// Used to load keypair from string provided from Save function.
        /// </summary>
        /// <param name="keyContents">Data from Save function</param>
        public void LoadFrom(string keyContents)
        {
            var split = keyContents.Split(' ');

            if (split.Length != 2)
            {
                throw new FormatException("Keys file doesn't contain proper data.");
            }

            var ecp = GetParams();

            var q         = Convert.FromBase64String(split[1]);
            var point     = ecp.Curve.DecodePoint(q);
            var pubParams = new ECPublicKeyParameters(point, ecp);

            var d = new BigInteger(Convert.FromBase64String(split[0]));
            var privateKeyParameters = new ECPrivateKeyParameters(d, ecp);

            _bcKeyPair = new AsymmetricCipherKeyPair(pubParams, privateKeyParameters);
        }
예제 #11
0
        public static byte[] Sign(byte[] input, Org.BouncyCastle.Math.BigInteger privateKey, ECDomainParameters EcParameters)
        {
            var signer = new ECDsaSigner();
            var privateKeyParameters = new ECPrivateKeyParameters(privateKey, EcParameters);

            signer.Init(true, privateKeyParameters);
            var signatures = signer.GenerateSignature(input);

            // What we get back from the signer are the two components of a signature, r and s. To get a flat byte stream
            // of the type used by BitCoin we have to encode them using DER encoding, which is just a way to pack the two
            // components into a structure.
            using (var byteOutputStream = new MemoryStream())
            {
                var derSequenceGenerator = new DerSequenceGenerator(byteOutputStream);
                derSequenceGenerator.AddObject(new DerInteger(signatures[0]));
                derSequenceGenerator.AddObject(new DerInteger(signatures[1]));
                derSequenceGenerator.Close();
                return(byteOutputStream.ToArray());
            }
        }
예제 #12
0
        internal void CertifyExistingForJava(int chainLen)
        {
            DeviceBundle bundle = new DeviceBundle();

            bundle.AliasCert      = (X509Certificate)Helpers.ReadPemObject(ToPath(Program.AliasCert));
            bundle.DeviceIDPublic = (AsymmetricKeyParameter)Helpers.ReadPemObject(ToPath(Program.DeviceIDPublic));

            // The current Java implementation stores the public and provate keys separately.  Put them back
            // together
            ECPrivateKeyParameters  opriv = (ECPrivateKeyParameters)Helpers.ReadPemObject(ToPath("AliasPrivate.PEM"));
            ECPublicKeyParameters   opub  = (ECPublicKeyParameters)Helpers.ReadPemObject(ToPath("AliasPublic.PEM"));
            AsymmetricCipherKeyPair kpx   = new AsymmetricCipherKeyPair(opub, opriv);

            Helpers.WritePEMObject(ToPath(Program.AliasKey), kpx);

            bundle.AliasKeyPair = (AsymmetricCipherKeyPair)Helpers.ReadPemObject(ToPath(Program.AliasKey));


            MakeCertChain(bundle, chainLen, 0);
        }
예제 #13
0
        public override Signature Sign(byte[] msg, byte[] prvKey)
        {
            var curve      = SecNamedCurves.GetByName("secp256k1");
            var parameters = new ECDomainParameters(curve.Curve, curve.G, curve.N, curve.H, curve.GetSeed());
            var privateKey = new ECPrivateKeyParameters(new BigInteger(1, prvKey), parameters);
            var signer     = new ECDsaSigner(new HMacDsaKCalculator(new Blake2bDigest(256)));

            signer.Init(true, privateKey);
            var rs = signer.GenerateSignature(Blake2b.GetDigest(msg));

            if (rs[1].CompareTo(curve.N.Divide(BigInteger.Two)) > 0)
            {
                rs[1] = curve.N.Subtract(rs[1]);
            }

            var r = rs[0].ToByteArrayUnsigned().Align(32);
            var s = rs[1].ToByteArrayUnsigned().Align(32);

            return(new Signature(r.Concat(s), SignaturePrefix));
        }
예제 #14
0
        public static string GeneratePrivateKey()
        {
            ECKeyPairGenerator gen = new ECKeyPairGenerator();
            var secureRandom       = new SecureRandom(new byte[] { 1, 2, 3, 4, 6 });

            var ps          = Org.BouncyCastle.Asn1.Sec.SecNamedCurves.GetByName("secp256k1");
            var ecParams    = new ECDomainParameters(ps.Curve, ps.G, ps.N, ps.H);
            var keyGenParam = new ECKeyGenerationParameters(ecParams, secureRandom);

            gen.Init(keyGenParam);

            AsymmetricCipherKeyPair kp = gen.GenerateKeyPair();

            ECPrivateKeyParameters priv = (ECPrivateKeyParameters)kp.Private;

            byte[] hexpriv    = priv.D.ToByteArrayUnsigned();
            var    privateKey = ByteArrayToString(hexpriv);

            return(privateKey);
        }
예제 #15
0
        /// <summary>
        /// Calculates an ECDSA signature in DER format for the given input hash. Note that the input is expected to be
        /// 32 bytes long.
        /// </summary>
        public byte[] Sign(byte[] input)
        {
            var signer  = new ECDsaSigner();
            var privKey = new ECPrivateKeyParameters(_priv, _ecParams);

            signer.Init(true, privKey);
            var sigs = signer.GenerateSignature(input);

            // What we get back from the signer are the two components of a signature, r and s. To get a flat byte stream
            // of the type used by BitCoin we have to encode them using DER encoding, which is just a way to pack the two
            // components into a structure.
            using (var bos = new MemoryStream())
            {
                var seq = new DerSequenceGenerator(bos);
                seq.AddObject(new DerInteger(sigs[0]));
                seq.AddObject(new DerInteger(sigs[1]));
                seq.Close();
                return(bos.ToArray());
            }
        }
예제 #16
0
        public virtual ECPoint Init_enc(SM2 sm2, ECPoint userKey)
        {
            BigInteger k  = null;
            ECPoint    c1 = null;


            AsymmetricCipherKeyPair key    = sm2.ecc_key_pair_generator.GenerateKeyPair();
            ECPrivateKeyParameters  ecpriv = (ECPrivateKeyParameters)key.Private;
            ECPublicKeyParameters   ecpub  = (ECPublicKeyParameters)key.Public;

            k  = ecpriv.D;
            c1 = ecpub.Q;


            p2 = userKey.Multiply(k);
            Reset();


            return(c1);
        }
예제 #17
0
        protected override TlsSignerCredentials GetECDsaSignerCredentials()
        {
#if SUPPORT_RPK
            foreach (OneKey k in _serverKeys)
            {
                if (k.HasKeyType((int)COSE.GeneralValuesInt.KeyType_EC2) &&
                    k.HasAlgorithm(COSE.AlgorithmValues.ECDSA_256))
                {
                    X9ECParameters         p          = k.GetCurve();
                    ECDomainParameters     parameters = new ECDomainParameters(p.Curve, p.G, p.N, p.H);
                    ECPrivateKeyParameters privKey    = new ECPrivateKeyParameters("ECDSA", ConvertBigNum(k[CoseKeyParameterKeys.EC_D]), parameters);

                    ECPoint point = k.GetPoint();
                    ECPublicKeyParameters param = new ECPublicKeyParameters(point, parameters);

                    SubjectPublicKeyInfo spi = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(param);

                    return(new DefaultTlsSignerCredentials(mContext, new RawPublicKey(spi), privKey, new SignatureAndHashAlgorithm(HashAlgorithm.sha256, SignatureAlgorithm.ecdsa)));
                }
            }
#endif

            // If we did not fine appropriate signer credientials - ask for help

            TlsEvent e = new TlsEvent(TlsEvent.EventCode.SignCredentials)
            {
                CipherSuite = KeyExchangeAlgorithm.ECDHE_ECDSA
            };

            EventHandler <TlsEvent> handler = TlsEventHandler;
            if (handler != null)
            {
                handler(this, e);
            }

            if (e.SignerCredentials != null)
            {
                return(e.SignerCredentials);
            }
            throw new TlsFatalAlert(AlertDescription.internal_error);
        }
예제 #18
0
        /// <summary>
        /// 建立本機公私密鑰並儲存
        /// </summary>
        /// <param name="path">儲存檔案路徑,若為空值則採用預設路徑(See: KeyPair_FilePath)</param>
        public void CreateLocalHostKeyPair(String path = "")
        {
            //儲存檔路徑若為空值則採用預設路徑
            path = (path == "" || path == null) ? KeyPair_FilePath : path;

            //建立儲存檔路徑之父資料夾
            if (!Directory.Exists(Path.GetDirectoryName(path)))
            {
                Directory.CreateDirectory(Path.GetDirectoryName(path));
            }

            //建立公鑰與私鑰
            _ecLocalKeyPair = _ecKeyGenerator.GenerateKeyPair();
            ECPublicKeyParameters  pubKey  = _ecLocalKeyPair.Public as ECPublicKeyParameters;
            ECPrivateKeyParameters privKey = _ecLocalKeyPair.Private as ECPrivateKeyParameters;

            byte[] pubKeyBytes  = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(pubKey).GetEncoded();
            byte[] privKeyBytes = PrivateKeyInfoFactory.CreatePrivateKeyInfo(privKey).GetEncoded();

            //儲存至指定檔案
            FileStream ecKeyFs = File.Create(path);

            //寫入公鑰資訊
            foreach (byte b in pubKeyBytes)
            {
                ecKeyFs.WriteByte(b);
            }
            //寫入私鑰資訊
            foreach (byte b in privKeyBytes)
            {
                ecKeyFs.WriteByte(b);
            }

            ecKeyFs.Flush();
            ecKeyFs.Close();

            //清除舊資料
            _pubKeyHeaderBytes = null;
            _pubKeyInfoBytes   = null;
            _pubKeyBytes       = null;
        }
        async void GetOrGenerateKey(IProgress <string> progress)
        {
            try {
                var key = await SecureStorage.GetAsync("key");

                if (key is null)
                {
                    KeyPair = GenerateKeyPair();
                    var pubkeyBytes  = ((ECPublicKeyParameters)KeyPair.Public).Q.GetEncoded();
                    var privkeyBytes = ((ECPrivateKeyParameters)KeyPair.Private).D.ToByteArray();
                    await SecureStorage.SetAsync("key",
                                                 $"{Convert.ToBase64String(pubkeyBytes)}:{Convert.ToBase64String(privkeyBytes)}");
                }
                else
                {
                    var pubkeyBytes  = Convert.FromBase64String(key.Split(':')[0]);
                    var privkeyBytes = Convert.FromBase64String(key.Split(':')[1]);
                    var curve        = ECNamedCurveTable.GetByName("P-256");
                    var pubKey       = new ECPublicKeyParameters(curve.Curve.DecodePoint(pubkeyBytes), DomainParams);
                    var privKey      = new ECPrivateKeyParameters(new BigInteger(privkeyBytes), DomainParams);
                    KeyPair = new AsymmetricCipherKeyPair(pubKey, privKey);
                }

                var signer = SignerUtilities.GetSigner("SHA-256withECDSA");
                var msg    = Encoding.ASCII.GetBytes("Hello World");
                signer.Init(true, KeyPair.Private);
                signer.BlockUpdate(msg, 0, msg.Length);
                var signature = signer.GenerateSignature();

                signer.Init(false, KeyPair.Public);
                signer.BlockUpdate(msg, 0, msg.Length);
                var verified = signer.VerifySignature(signature);

                var pubkey = Convert.ToBase64String(((ECPublicKeyParameters)KeyPair.Public).Q.GetEncoded());
                progress.Report($"Public key: {pubkey}"
                                + $"\nSignature: {Convert.ToBase64String(signature)}"
                                + $"\nVerified: {verified}");
            } catch (Exception e) {
                System.Console.WriteLine("Failed: " + e.Message + "\n" + e.StackTrace);
            }
        }
예제 #20
0
        public void TestEC()
        {
            IBigInteger ECParraGX = new BigInteger(Base64.Decode("D/qWPNyogWzMM7hkK+35BcPTWFc9Pyf7vTs8uaqv"));
            IBigInteger ECParraGY = new BigInteger(Base64.Decode("AhQXGxb1olGRv6s1LPRfuatMF+cx3ZTGgzSE/Q5R"));
            IBigInteger ECParraH  = new BigInteger(Base64.Decode("AQ=="));
            IBigInteger ECParraN  = new BigInteger(Base64.Decode("f///////////////f///nl6an12QcfvRUiaIkJ0L"));
            IBigInteger ECPubQX   = new BigInteger(Base64.Decode("HWWi17Yb+Bm3PYr/DMjLOYNFhyOwX1QY7ZvqqM+l"));
            IBigInteger ECPubQY   = new BigInteger(Base64.Decode("JrlJfxu3WGhqwtL/55BOs/wsUeiDFsvXcGhB8DGx"));
            IBigInteger ECPrivD   = new BigInteger(Base64.Decode("GYQmd/NF1B+He1iMkWt3by2Az6Eu07t0ynJ4YCAo"));

            FPCurve curve = new FPCurve(
                new BigInteger("883423532389192164791648750360308885314476597252960362792450860609699839"),         // q
                new BigInteger("7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc", 16),                 // a
                new BigInteger("6b016c3bdcf18941d0d654921475ca71a9db2fb27d1d37796185c2942c0a", 16));                // b

            ECDomainParameters ecDomain =
                new ECDomainParameters(
                    curve,
                    new FPPoint(curve,
                                curve.FromBigInteger(ECParraGX),
                                curve.FromBigInteger(ECParraGY)),
                    ECParraN);

            ECPublicKeyParameters ecPub = new ECPublicKeyParameters(
                new FPPoint(
                    curve,
                    curve.FromBigInteger(ECPubQX),
                    curve.FromBigInteger(ECPubQY)),
                ecDomain);

            ECPrivateKeyParameters ecPriv = new ECPrivateKeyParameters(ECPrivD, ecDomain);

            SubjectPublicKeyInfo subinfo  = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(ecPub);
            PrivateKeyInfo       privInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(ecPriv);

            ECPublicKeyParameters  tecPub  = (ECPublicKeyParameters)PublicKeyFactory.CreateKey(subinfo);
            ECPrivateKeyParameters tecPriv = (ECPrivateKeyParameters)PrivateKeyFactory.CreateKey(privInfo);

            Assert.IsTrue(tecPub.Equals(ecPub), "EC: public key to info back to public key");
            Assert.IsTrue(tecPriv.Equals(ecPriv), "EC: private key to info back to private key");
        }
예제 #21
0
        public static byte[] DoSignEcDsa(
            IEnumerable <BufLen> bufs,
            I2PSigningPrivateKey key,
            IDigest digest,
            X9ECParameters ecparam,
            int sigsize)
        {
            foreach (var buf in bufs)
            {
                digest.BlockUpdate(buf.BaseArray, buf.BaseArrayOffset, buf.Length);
            }
            var hash = new byte[digest.GetDigestSize()];

            digest.DoFinal(hash, 0);

            var param = new ECDomainParameters(ecparam.Curve, ecparam.G, ecparam.N, ecparam.H);
            var pk    = new ECPrivateKeyParameters(key.ToBigInteger(), param);

            var s = new Org.BouncyCastle.Crypto.Signers.ECDsaSigner();

            s.Init(true, new ParametersWithRandom(pk));

            var sig    = s.GenerateSignature(hash);
            var result = new byte[sigsize];

            var b1 = sig[0].ToByteArrayUnsigned();
            var b2 = sig[1].ToByteArrayUnsigned();

            // https://geti2p.net/en/docs/spec/common-structures#type_Signature
            // When a signature is composed of two elements (for example values R,S),
            // it is serialized by padding each element to length/2 with leading zeros if necessary.
            // All types are Big Endian, except for EdDSA, which is stored and transmitted in a Little Endian format.

            // Pad msb. Big endian.
            Array.Copy(b1, 0, result, sigsize / 2 - b1.Length, b1.Length);
            Array.Copy(b2, 0, result, sigsize - b2.Length, b2.Length);

            DebugUtils.LogDebug("DoSignEcDsa: " + digest.ToString() + ": Used.");

            return(result);
        }
예제 #22
0
        public static CryptoSettings GenerateCryptoSettings()
        {
            ECKeyPairGenerator gen = new ECKeyPairGenerator("ECDH");

            gen.Init(eckgparameters);
            AsymmetricCipherKeyPair eckp = gen.GenerateKeyPair();

            ECPublicKeyParameters  ecPub = (ECPublicKeyParameters)eckp.Public;
            ECPrivateKeyParameters ecPri = (ECPrivateKeyParameters)eckp.Private;

            var authSecret = new byte[16];

            secureRandom.NextBytes(authSecret);

            return(new CryptoSettings
            {
                PublicKey = ecPub.Q.GetEncoded(),
                PrivateKey = ecPri.D.ToByteArrayUnsigned(),
                AuthSecret = authSecret,
            });
        }
예제 #23
0
        /// <summary>
        /// Sets the private key.
        /// </summary>
        /// <param name="fs">The fs.</param>
        /// <param name="passWord">The pass word.</param>
        private void SetPrivateKey(Stream fs, string passWord)
        {
            Pkcs12Store store = new Pkcs12Store(fs, passWord.ToCharArray());

            foreach (string n in store.Aliases)
            {
                if (store.IsKeyEntry(n))
                {
                    AsymmetricKeyEntry asymmetricKey = store.GetKey(n);

                    if (asymmetricKey.Key.IsPrivate)
                    {
                        _ecPrivateKeyParameters = asymmetricKey.Key as ECPrivateKeyParameters;
                    }
                    else
                    {
                        _ecPublicKeyParameters = asymmetricKey.Key as ECPublicKeyParameters;
                    }
                }
            }
        }
예제 #24
0
        private byte[] Decrypt(PublicKey ephemeralPublicKey, PrivateKey privateKey, byte[] iv, byte[] ciphertextBody, byte[] macData)
        {
            AesEngine aesFastEngine = new AesEngine();

            EthereumIesEngine iesEngine = new EthereumIesEngine(
                new ECDHBasicAgreement(),
                new ConcatKdfBytesGenerator(new Sha256Digest()),
                new HMac(new Sha256Digest()),
                new Sha256Digest(),
                new BufferedBlockCipher(new SicBlockCipher(aesFastEngine)));

            IesParameters    iesParameters    = new IesWithCipherParameters(new byte[] { }, new byte[] { }, KeySize, KeySize);
            ParametersWithIV parametersWithIV = new ParametersWithIV(iesParameters, iv);

            ECPrivateKeyParameters privateKeyParameters = BouncyCrypto.WrapPrivateKey(privateKey);
            ECPublicKeyParameters  publicKeyParameters  = BouncyCrypto.WrapPublicKey(ephemeralPublicKey);

            iesEngine.Init(false, privateKeyParameters, publicKeyParameters, parametersWithIV);

            return(iesEngine.ProcessBlock(ciphertextBody, 0, ciphertextBody.Length, macData));
        }
예제 #25
0
        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);
        }
예제 #26
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());
        }
예제 #27
0
        private void GenerateKeys(string curveName)
        {
            this.logger?.Debug($"ECDHE: Creating ephemeral ecc domain parameters and keys for curve {curveName}...");
            X9ECParameters ecParams = SecNamedCurves.GetByName(curveName);

            this.domainParameters = new ECDomainParameters(
                ecParams.Curve,
                ecParams.G,
                ecParams.N,
                ecParams.H,
                ecParams.GetSeed());
            var keyGenParams = new ECKeyGenerationParameters(this.domainParameters, new SecureRandom());

            var generator = new ECKeyPairGenerator();

            generator.Init(keyGenParams);
            var keyPair = generator.GenerateKeyPair();

            this.privateKey = (ECPrivateKeyParameters)keyPair.Private;
            this.publicKey  = (ECPublicKeyParameters)keyPair.Public;
        }
예제 #28
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));
            }
        }
        static byte[] DeriveKey(IDictionary <string, object> header, int cekSizeBits, ECPublicKeyParameters externalPublicKey,
                                ECPrivateKeyParameters ephemeralPrvKey)
        {
            var z = EcdhKeyAgreementZ(externalPublicKey, ephemeralPrvKey);

            var kdfGen = new ConcatenationKdfGenerator(new Sha256Digest());

            byte[] algId = Encoding.ASCII.GetBytes(header["enc"].ToString());
            byte[] apu   = header.ContainsKey("apu") ? Base64Url.Decode((string)header["apu"]) : Arrays.Empty;
            byte[] apv   = header.ContainsKey("apv") ? Base64Url.Decode((string)header["apv"]) : Arrays.Empty;
            byte[] kdl   = CalcBeLengthArray(cekSizeBits);

            var otherInfo = Arrays.Concat(PrependLength(algId), PrependLength(apu), PrependLength(apv), kdl);

            //Console.Out.WriteLine($"otherInfo={VAU.ByteArrayToHexString(otherInfo)}");

            kdfGen.Init(new KdfParameters(z, otherInfo));
            byte[] secretKeyBytes = new byte[32];
            kdfGen.GenerateBytes(secretKeyBytes, 0, secretKeyBytes.Length);
            return(secretKeyBytes);
        }
예제 #30
0
        /**
         * sm2签名
         * @param userId ID值,若无约定,使用默认:1234567812345678
         * @param privateKey 私钥,二进制数据
         * @param sourceData 待签名数据
         * @return 返回der编码的签名值
         * @throws CryptoException
         */
        public static byte[] Sign(byte[] userId, byte[] privateKey, byte[] sourceData)
        {
            X9ECParameters         sm2p256v1        = GMNamedCurves.GetByName("sm2p256v1");
            ECDomainParameters     parameters       = new ECDomainParameters(sm2p256v1.Curve, sm2p256v1.G, sm2p256v1.N);
            ECPrivateKeyParameters priKeyParameters = new ECPrivateKeyParameters(new BigInteger(1, privateKey), parameters);
            SM2Signer            signer             = new SM2Signer();
            ICipherParameters    param = null;
            ParametersWithRandom pwr   = new ParametersWithRandom(priKeyParameters, new SecureRandom());

            if (userId != null)
            {
                param = new ParametersWithID(pwr, userId);
            }
            else
            {
                param = pwr;
            }
            signer.Init(true, param);
            signer.BlockUpdate(sourceData, 0, sourceData.Length);
            return(signer.GenerateSignature());
        }
예제 #31
0
 private void InitSigner(BigInteger priv)
 {
     _signer = new ECDSASigner(new HMacDsaKCalculator(new Sha256Digest()));
     ECPrivateKeyParameters privKey = new ECPrivateKeyParameters(priv, Secp256K1.Parameters());
     _signer.Init(true, privKey);
 }