Example #1
0
        public void PrivateKeyTest()
        {
            ECDSA ecdsa = new ECDSA(ECDomainNames.secp192r1);

            byte[] hash       = RNG.GetBytes(ecdsa.KeySize >> 3);
            byte[] sign       = ecdsa.SignHash(hash);
            byte[] publicKey  = ecdsa.Parameters.PublicKey;
            byte[] privateKey = ecdsa.Parameters.PrivateKey;

            ecdsa = new ECDSA(ECDomainNames.secp192r1);
            ecdsa.Parameters.PublicKey = publicKey;
            Assert.IsTrue(ecdsa.VerifyHash(hash, sign), "Success Test #1");

            sign[0]++;
            Assert.IsFalse(ecdsa.VerifyHash(hash, sign), "Failure Test #1");

            ecdsa = new ECDSA(ECDomainNames.secp192r1);
            ecdsa.Parameters.PrivateKey = privateKey;
            hash = RNG.GetBytes(ecdsa.KeySize >> 3);
            sign = ecdsa.SignHash(hash);

            ecdsa = new ECDSA(ECDomainNames.secp192r1);
            ecdsa.Parameters.PublicKey = publicKey;
            Assert.IsTrue(ecdsa.VerifyHash(hash, sign), "Success Test #2");

            sign[0]++;
            Assert.IsFalse(ecdsa.VerifyHash(hash, sign), "Failure Test #2");
        }
Example #2
0
		public void PrivateKeyTest ()
		{
			ECDSA ecdsa = new ECDSA (ECDomainNames.secp192r1);
			byte[] hash = RNG.GetBytes (ecdsa.KeySize >> 3);
			byte[] sign = ecdsa.SignHash (hash);
			byte[] publicKey = ecdsa.Parameters.PublicKey;
			byte[] privateKey = ecdsa.Parameters.PrivateKey;

			ecdsa = new ECDSA (ECDomainNames.secp192r1);
			ecdsa.Parameters.PublicKey = publicKey;
			Assert.IsTrue (ecdsa.VerifyHash (hash, sign), "Success Test #1");

			sign[0]++;
			Assert.IsFalse (ecdsa.VerifyHash (hash, sign), "Failure Test #1");

			ecdsa = new ECDSA (ECDomainNames.secp192r1);
			ecdsa.Parameters.PrivateKey = privateKey;
			hash = RNG.GetBytes (ecdsa.KeySize >> 3);
			sign = ecdsa.SignHash (hash);

			ecdsa = new ECDSA (ECDomainNames.secp192r1);
			ecdsa.Parameters.PublicKey = publicKey;
			Assert.IsTrue (ecdsa.VerifyHash (hash, sign), "Success Test #2");

			sign[0]++;
			Assert.IsFalse (ecdsa.VerifyHash (hash, sign), "Failure Test #2");
		}
Example #3
0
        private void btnAddPublicKey_Click(object sender, EventArgs e)
        {
            string name;

            using (TextInputDialog dlg = new TextInputDialog("名前の入力", "公開鍵の名前を入力してください")) {
                if (dlg.ShowDialog() != DialogResult.OK)
                {
                    return;
                }
                name = dlg.InputText;
            }
            using (TextInputDialog dlg = new TextInputDialog(name + "の公開鍵", name + "の公開鍵を入力してください", 4)) {
                if (dlg.ShowDialog() != DialogResult.OK)
                {
                    return;
                }
                try {
                    ECDomainNames domain;
                    byte[]        publicKey = ParsePublicKey(dlg.InputText, out domain);
                    ECDSA         ecdsa     = new ECDSA(domain);
                    ecdsa.Parameters.PublicKey = publicKey;
                } catch (Exception ex) {
                    MessageBox.Show(ex.Message);
                    return;
                }
                _store.AddPublicKeyEntry(name, dlg.InputText);
            }
        }
Example #4
0
        private ECDSA CreateAccount()
        {
            var ec = new ECDSA();

            WriteText("Your mnemonic passphrase is:", false);
            WriteDanger("(remember to store this in a safe space)");
            WriteText(ec.GetWords);
            WriteText("Press any key to continue.");
            Console.ReadKey();
            CLS();
            var ws = ec.GetWords.Split(' ');

            for (int i = 0; i < 4; i++)
            {
                var index = Base.Utilities.Util.Rnd.Next(1, 13);
                WriteText($"Enter the {index}th word:", false);
                var r = Console.ReadLine();
                while (r != ws[index - 1])
                {
                    WriteErr("Wrong!!!");
                    WriteText($"Enter the {index}th word:", false);
                    r = Console.ReadLine();
                }
            }
            CLS();
            return(ec);
        }
Example #5
0
        private Payload GetPayload()
        {
            lock (_lock4GetPayload)
                if (_payload == null)
                {
                    PrivateKey myPrivkeyFrom = PrivateKey.GetPrivateKey(_bm.DB, KeyFrom);
                    if (myPrivkeyFrom == null)
                    {
                        throw new Exception("PrivateKey not found");
                    }

                    Pubkey pubkeyTo = Pubkey.Find(_bm.DB, KeyTo);                     // TODO Получать ключ, если его ещё нет
                    if (pubkeyTo == null)
                    {
                        throw new Exception("Pubkey not found");
                    }

                    var   payload = new MemoryStream(1000 + Subject.Length + Body.Length);                   // TODO realy 1000?
                    var   rnd     = new Random();
                    ulong dt      = DateTime.UtcNow.ToUnix() + (ulong)rnd.Next(600) - 300;

                    payload.Write(dt);
                    payload.WriteVarInt(Stream);

                    var dataToEncrypt = new MemoryStream(1000 + Subject.Length + Body.Length);                     // TODO realy 1000?
                    dataToEncrypt.WriteVarInt(Version);

                    byte[] publicAddress = myPrivkeyFrom.GetPayload4Broadcast();
                    dataToEncrypt.Write(publicAddress, 0, publicAddress.Length);

                    dataToEncrypt.Write(pubkeyTo.Hash, 0, 20);

                    var encodingType = (byte)EncodingType;
                    dataToEncrypt.Write(encodingType);
                    dataToEncrypt.WriteVarStr("Subject:" + Subject + "\nBody:" + Body);

                    byte[] askMsg = PayloadOfAskData().GetFullMsg();
                    dataToEncrypt.WriteVarInt((UInt64)askMsg.Length);
                    dataToEncrypt.Write(askMsg, 0, askMsg.Length);

                    byte[] signature = myPrivkeyFrom.Sign(dataToEncrypt.ToArray());

                    //Debug.WriteLine("data=" + dataToEncrypt.ToArray().ToHex());
                    //Debug.WriteLine("SigningKey=" + myPrivkeyFrom.SigningKey.ToHex());
                    //Debug.WriteLine("signature=" + signature.ToHex());

                    dataToEncrypt.WriteVarInt((UInt64)signature.Length);
                    dataToEncrypt.Write(signature, 0, signature.Length);

                    byte[] bytesToEncrypt = dataToEncrypt.ToArray();
                    byte[] encrypt        = ECDSA.Encrypt(bytesToEncrypt, pubkeyTo.EncryptionKey);

                    payload.Write(encrypt, 0, encrypt.Length);

                    _payload = new Payload("msg", ProofOfWork.AddPow(payload.ToArray()));
                }
            return(_payload);
        }
Example #6
0
		private void btnKeyGenerate_Click (object sender, EventArgs e)
		{
			ECDomainNames domain = (ECDomainNames)cbKeyType.SelectedIndex;
			ECDSA dsa = new ECDSA (domain);
			string domainName = domain.ToString ().Substring(4);
			byte[] privateKeyBytes = dsa.Parameters.PrivateKey;
			txtGeneratedKey.Text = ToPrivateKeyString (privateKeyBytes, txtGeneratedKeyPass.Text, domain);
			string publicKey = Convert.ToBase64String (dsa.Parameters.ExportPublicKey (domain != ECDomainNames.secp224r1 ? true : false));
			txtGeneratedPublicKey.Text = domainName + "=" + publicKey;
		}
Example #7
0
        public void TestKeyPairGeneration()
        {
            byte[] privateKey, publicKey;

            foreach (var compressed in new bool[] { true, false })
            {
                ECDSA.GenerateKeyPair(out privateKey, out publicKey, compressed);
                var publicKeyCheck = ECDSA.GeneratePublicKey(privateKey, compressed);

                CollectionAssert.AreEqual(publicKey, publicKeyCheck);
            }
        }
Example #8
0
        private void btnKeyGenerate_Click(object sender, EventArgs e)
        {
            ECDomainNames domain     = (ECDomainNames)cbKeyType.SelectedIndex;
            ECDSA         dsa        = new ECDSA(domain);
            string        domainName = domain.ToString().Substring(4);

            byte[] privateKeyBytes = dsa.Parameters.PrivateKey;
            txtGeneratedKey.Text = ToPrivateKeyString(privateKeyBytes, txtGeneratedKeyPass.Text, domain);
            string publicKey = Convert.ToBase64String(dsa.Parameters.ExportPublicKey(domain != ECDomainNames.secp224r1 ? true : false));

            txtGeneratedPublicKey.Text = domainName + "=" + publicKey;
        }
Example #9
0
 public Transaction(string reciepient, double amount, ECDSA ec, string message = "")
 {
     TransactionIssuer = ec.ExportPubKey;
     Reciepient        = reciepient;
     Amount            = amount;
     IsuueTime         = DateTime.UtcNow;
     TxHash            = ComputeObjectHash();
     //Signture = ec.Sign(TxHash).ToByteArray(StringEncoding.Base64).ToBase58Check();
     Signture     = ec.Sign(TxHash);
     ScriptPubKey = $"{Signture};{TransactionIssuer}";
     ScriptSig    = $"{ScriptPubKey};CheckSig;IsOne";
 }
Example #10
0
        public void TestSignature()
        {
            var input = Encoding.UTF8.GetBytes("Hello!");

            var ecdsa = new ECDSA(new DefaultRandomGenerator());

            ecdsa.Init(new ECCipherParameters(Secp256R1.Parameters, PrivateKey));

            var signature = ecdsa.Sign(input, new SHA256Digest(SHA256Digest.Mode.SHA256));
            var result    = ecdsa.Verify(input, signature, new SHA256Digest(SHA256Digest.Mode.SHA256));

            Assert.True(result);
        }
Example #11
0
 private void btnPublicKeyGenerate_Click(object sender, EventArgs e)
 {
     try {
         ECDomainNames domain;
         byte[]        privateKey = ParsePrivateKey(txtGeneratedKey.Text, txtGeneratedKeyPass.Text, out domain);
         ECDSA         ecdsa      = new ECDSA(domain);
         ecdsa.Parameters.PrivateKey = privateKey;
         string publicKey = Convert.ToBase64String(ecdsa.Parameters.ExportPublicKey(domain != ECDomainNames.secp224r1 ? true : false));
         txtGeneratedPublicKey.Text = domain.ToString().Substring(4) + "=" + publicKey;
     } catch (Exception ex) {
         MessageBox.Show(ex.Message);
     }
 }
Example #12
0
        public void TestVerify()
        {
            var input     = Encoding.UTF8.GetBytes("Hello!");
            var signature = HexConverter.FromHex("304602210098a1615b14266bb514f3829f2775e1a46eec972c1021d67dd1c35b88add5e3f6022100eb91ddd49f9ab3560d69d65b47961fb051ef72c18c3c9acd7f2fb4d1c37ce351");

            var ecdsa = new ECDSA(new DefaultRandomGenerator());

            ecdsa.Init(new ECCipherParameters(Secp256K1.Parameters, PublicKey));

            var result = ecdsa.Verify(input, signature, new SHA256Digest(SHA256Digest.Mode.SHA256));

            Assert.True(result);
        }
Example #13
0
        public void TestVerify()
        {
            var input     = Encoding.UTF8.GetBytes("Hello!");
            var signature = HexConverter.FromHex("3046022100cff2771c25049757d8a14e6f9a58b7e0928bafd33d7977fd194aeb14c64bd6ab022100f417bdbc4a9cb1f5cd719583b093a767c1c975e7ac5604ddd47827e2da05e8bb");

            var ecdsa = new ECDSA(new DefaultRandomGenerator());

            ecdsa.Init(new ECCipherParameters(Secp256R1.Parameters, PublicKey));

            var result = ecdsa.Verify(input, signature, new SHA256Digest(SHA256Digest.Mode.SHA256));

            Assert.True(result);
        }
Example #14
0
        public PrivateKey(string label, bool eighteenByteRipe = false)
        {
            var startTime = DateTime.Now;

            Label = label;

            RNGCryptoServiceProvider rnd = new RNGCryptoServiceProvider();

            byte[] potentialPrivSigningKey = new byte[32];
            rnd.GetBytes(potentialPrivSigningKey);
            SigningKey = ECDSA.PointMult(potentialPrivSigningKey);

            int numberOfAddressesWeHadToMakeBeforeWeFoundOneWithTheCorrectRipePrefix = 0;

            byte[] ripemd160;
            byte[] potentialPrivEncryptionKey = new byte[32];

            while (true)
            {
                numberOfAddressesWeHadToMakeBeforeWeFoundOneWithTheCorrectRipePrefix += 1;
                rnd.GetBytes(potentialPrivEncryptionKey);

                EncryptionKey = ECDSA.PointMult(potentialPrivEncryptionKey);

                byte[] buff = SigningKey.Concatenate(EncryptionKey);
                byte[] sha  = new SHA512Managed().ComputeHash(buff);
                ripemd160 = RIPEMD160.Create().ComputeHash(sha);

                if (eighteenByteRipe)
                {
                    if ((ripemd160[0] == 0) && (ripemd160[1] == 0))
                    {
                        break;
                    }
                }
                else
                {
                    if (ripemd160[0] == 0)
                    {
                        break;
                    }
                }
            }

            // NonceTrialsPerByte используется значение по умолчанию
            // payloadLengthExtraBytes используется значение по умолчанию
            PrivSigningKeyWif    = PrivateKey2Wif(potentialPrivSigningKey);
            PrivEncryptionKeyWif = PrivateKey2Wif(potentialPrivEncryptionKey);

            Status = Status.Valid;
        }
Example #15
0
        private Payload GetPayload()
        {
            lock (_lock4GetPayload)
                if (_payload == null)
                {
                    if (_version == 2)
                    {
                        PrivateKey privkey = PrivateKey.GetPrivateKey(_bm.DB, Key);
                        if (privkey == null)
                        {
                            throw new Exception("PrivateKey not found");
                        }

                        MemoryStream payload = new MemoryStream(1000 + Subject.Length + Body.Length);                 // TODO realy 1000?
                        Random       rnd     = new Random();
                        ulong        dt      = DateTime.UtcNow.ToUnix() + (ulong)rnd.Next(600) - 300;

                        payload.Write(dt);
                        payload.WriteVarInt(Version);
                        payload.WriteVarInt(Stream);

                        MemoryStream dataToEncrypt = new MemoryStream(1000 + Subject.Length + Body.Length);                 // TODO realy 1000?
                        dataToEncrypt.WriteVarInt(Version);

                        byte[] publicAddress = privkey.GetPayload4Broadcast();
                        dataToEncrypt.Write(publicAddress, 0, publicAddress.Length);

                        Byte encodingType = (byte)EncodingType;
                        dataToEncrypt.Write(encodingType);
                        dataToEncrypt.WriteVarStr("Subject:" + Subject + "\nBody:" + Body);

                        byte[] signature = privkey.Sign(dataToEncrypt.ToArray());

                        dataToEncrypt.WriteVarInt((UInt64)signature.Length);
                        dataToEncrypt.Write(signature, 0, signature.Length);

                        var privEncryptionKey = privkey.Sha512VersionStreamHashFirst32();
                        var pubEncryptionKey  = ECDSA.PointMult(privEncryptionKey);

                        byte[] bytesToEncrypt = dataToEncrypt.ToArray();
                        byte[] encrypt        = ECDSA.Encrypt(bytesToEncrypt, pubEncryptionKey);

                        payload.Write(encrypt, 0, encrypt.Length);

                        _payload = new Payload("broadcast", ProofOfWork.AddPow(payload.ToArray()));
                    }
                }
            return(_payload);
        }
Example #16
0
        public SimpleCaptcha(ECDSA ecdsa, int num_of_words)
        {
            _ecdsa = ecdsa;
            _len = num_of_words;
            _hmac_key = openCrypto.RNG.GetRNGBytes (64);
            _salt = openCrypto.RNG.GetRNGBytes (32);
            _pubKey = ecdsa.Parameters.ExportPublicKey (true);

            _font = new Font (FontFamily.GenericMonospace, 28, FontStyle.Bold);
            using (Image img = new Bitmap (16, 16, PixelFormat.Format24bppRgb))
            using (Graphics g = Graphics.FromImage (img)) {
                g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
                SizeF size = g.MeasureString (new string ('Z', _len), _font);
                _size = new Size ((int)(size.Width + 10), (int)(size.Height + 10));
            }
        }
Example #17
0
        static void SignVerifyTest(ECDomainNames domainName)
        {
            int repeat = 5;

            for (int i = 0; i < repeat; i++)
            {
                ECDSA  ecdsa  = new ECDSA(domainName);
                byte[] pubKey = ecdsa.Parameters.PublicKey;
                byte[] hash   = RNG.GetBytes(ecdsa.KeySize >> 3);
                byte[] sign   = ecdsa.SignHash(hash);
                ecdsa = new ECDSA(domainName);
                ecdsa.Parameters.PublicKey = pubKey;
                Assert.IsTrue(ecdsa.VerifyHash(hash, sign), "Success Test " + domainName.ToString());
                sign[0]++;
                Assert.IsFalse(ecdsa.VerifyHash(hash, sign), "Failure Test " + domainName.ToString());
            }
        }
Example #18
0
 private void btnRegisterPrivateKey_Click(object sender, EventArgs e)
 {
     try {
         ECDomainNames domain;
         byte[]        privateKey = ParsePrivateKey(txtGeneratedKey.Text, txtGeneratedKeyPass.Text, out domain);
         ECDSA         ecdsa      = new ECDSA(domain);
         ecdsa.Parameters.PrivateKey = privateKey;
     } catch (Exception ex) {
         MessageBox.Show(ex.Message);
         return;
     }
     using (TextInputDialog dlg = new TextInputDialog("名前を入力", "秘密鍵の名前を入力してください")) {
         if (dlg.ShowDialog() == DialogResult.OK)
         {
             _store.AddPrivateKeyEntry(dlg.InputText, txtGeneratedKey.Text);
         }
     }
 }
Example #19
0
        public void Test_GEC2()
        {
            ECDSA ecdsa1 = new ECDSA(ECDomainNames.secp160r1);
            ECDSA ecdsa2 = new ECDSA(ECDomainNames.secp160r1);

            ecdsa1.Parameters.PrivateKey = new byte[] { 0xAA, 0x37, 0x4F, 0xFC, 0x3C, 0xE1, 0x44, 0xE6, 0xB0, 0x73, 0x30, 0x79, 0x72, 0xCB, 0x6D, 0x57, 0xB2, 0xA4, 0xE9, 0x82 };
            ecdsa2.Parameters.PublicKey  = ecdsa1.Parameters.PublicKey;
            byte[] k            = openCrypto.FiniteField.Number.Parse("702232148019446860144825009548118511996283736794", 10).ToByteArray(20, false);
            byte[] H            = new byte[] { 0xA9, 0x99, 0x3E, 0x36, 0x47, 0x06, 0x81, 0x6A, 0xBA, 0x3E, 0x25, 0x71, 0x78, 0x50, 0xC2, 0x6C, 0x9C, 0xD0, 0xD8, 0x9D };
            byte[] expectedSign = new byte[] {
                0xCE, 0x28, 0x73, 0xE5, 0xBE, 0x44, 0x95, 0x63, 0x39, 0x1F, 0xEB, 0x47, 0xDD, 0xCB, 0xA2, 0xDC, 0x16, 0x37, 0x91, 0x91,
                0x34, 0x80, 0xEC, 0x13, 0x71, 0xA0, 0x91, 0xA4, 0x64, 0xB3, 0x1C, 0xE4, 0x7D, 0xF0, 0xCB, 0x8A, 0xA2, 0xD9, 0x8B, 0x54,
            };

            byte[] sign = ecdsa1.SignHash(H, k);
            Assert.AreEqual(expectedSign, sign);

            Assert.IsTrue(ecdsa2.VerifyHash(H, sign));
        }
Example #20
0
		public void Test_GEC2 ()
		{
			ECDSA ecdsa1 = new ECDSA (ECDomainNames.secp160r1);
			ECDSA ecdsa2 = new ECDSA (ECDomainNames.secp160r1);

			ecdsa1.Parameters.PrivateKey = new byte[] {0xAA, 0x37, 0x4F, 0xFC, 0x3C, 0xE1, 0x44, 0xE6, 0xB0, 0x73, 0x30, 0x79, 0x72, 0xCB, 0x6D, 0x57, 0xB2, 0xA4, 0xE9, 0x82};
			ecdsa2.Parameters.PublicKey = ecdsa1.Parameters.PublicKey;
			byte[] k = openCrypto.FiniteField.Number.Parse ("702232148019446860144825009548118511996283736794", 10).ToByteArray (20, false);
			byte[] H = new byte[] {0xA9, 0x99, 0x3E, 0x36, 0x47, 0x06, 0x81, 0x6A, 0xBA, 0x3E, 0x25, 0x71, 0x78, 0x50, 0xC2, 0x6C, 0x9C, 0xD0, 0xD8, 0x9D};
			byte[] expectedSign = new byte[] {
				0xCE, 0x28, 0x73, 0xE5, 0xBE, 0x44, 0x95, 0x63, 0x39, 0x1F, 0xEB, 0x47, 0xDD, 0xCB, 0xA2, 0xDC, 0x16, 0x37, 0x91, 0x91,
				0x34, 0x80, 0xEC, 0x13, 0x71, 0xA0, 0x91, 0xA4, 0x64, 0xB3, 0x1C, 0xE4, 0x7D, 0xF0, 0xCB, 0x8A, 0xA2, 0xD9, 0x8B, 0x54,
			};

			byte[] sign = ecdsa1.SignHash (H, k);
			Assert.AreEqual (expectedSign, sign);

			Assert.IsTrue (ecdsa2.VerifyHash (H, sign));
		}
Example #21
0
        public override byte[] DoSign(byte[] ske,
                                      out int hashAlgo, out int signAlgo)
        {
            hashAlgo = this.hashAlgo;
            byte[] hv = Hash(hashAlgo, ske);
            if (skey is RSAPrivateKey)
            {
                RSAPrivateKey rk = skey as RSAPrivateKey;
                signAlgo = SSL.RSA;
                byte[] head;
                switch (hashAlgo)
                {
                case SSL.MD5SHA1: head = null; break;

                case SSL.SHA1:    head = RSA.PKCS1_SHA1; break;

                case SSL.SHA224:  head = RSA.PKCS1_SHA224; break;

                case SSL.SHA256:  head = RSA.PKCS1_SHA256; break;

                case SSL.SHA384:  head = RSA.PKCS1_SHA384; break;

                case SSL.SHA512:  head = RSA.PKCS1_SHA512; break;

                default:
                    throw new Exception();
                }
                return(RSA.Sign(rk, head, hv));
            }
            else if (skey is ECPrivateKey)
            {
                ECPrivateKey ek = skey as ECPrivateKey;
                signAlgo = SSL.ECDSA;
                return(ECDSA.Sign(ek, null, hv));
            }
            else
            {
                throw new Exception("NYI");
            }
        }
Example #22
0
		private void btnAddPublicKey_Click (object sender, EventArgs e)
		{
			string name;
			using (TextInputDialog dlg = new TextInputDialog ("名前の入力", "公開鍵の名前を入力してください")) {
				if (dlg.ShowDialog () != DialogResult.OK)
					return;
				name = dlg.InputText;
			}
			using (TextInputDialog dlg = new TextInputDialog (name + "の公開鍵", name + "の公開鍵を入力してください", 4)) {
				if (dlg.ShowDialog () != DialogResult.OK)
					return;
				try {
					ECDomainNames domain;
					byte[] publicKey = ParsePublicKey (dlg.InputText, out domain);
					ECDSA ecdsa = new ECDSA (domain);
					ecdsa.Parameters.PublicKey = publicKey;
				} catch (Exception ex) {
					MessageBox.Show (ex.Message);
					return;
				}
				_store.AddPublicKeyEntry (name, dlg.InputText);
			}
		}
Example #23
0
        public PUnite()
        {
            Codes = new List <Commands>();
            _one  = new byte[64];
            for (int i = 0; i < 64; i++)
            {
                _one[i] = 1;
            }
            _zero = new byte[64];
            for (int i = 0; i < 64; i++)
            {
                _zero[i] = 0;
            }
            _stack   = new Stack();
            _actions = new Dictionary <Commands, Func <bool?> >();
            _actions.Add(Commands.Zero, () =>
            {
                _stack.Push(_zero);
                return(null);
            });
            _actions.Add(Commands.One, () =>
            {
                _stack.Push(_one);
                return(null);
            });
            _actions.Add(Commands.MD5, () =>
            {
                _stack.Pop(out string data);
                var data2 = data.ComputeHash(HashAlgorithms.MD5);
                //var data3 = new byte[64];
                //for (int i = 0; i < data2.Length; i++)
                //{
                //    data3[i] = data2[i];
                //}
                _stack.Push(data2);
                return(null);
            });
            _actions.Add(Commands.SHA256, () =>
            {
                _stack.Pop(out string data);
                var data2 = data.ComputeHash(HashAlgorithms.SHA256);
                //var data3 = new byte[64];
                //for (int i = 0; i < data2.Length; i++)
                //{
                //    data3[i] = data2[i];
                //}
                _stack.Push(data2);
                return(null);
            });
            _actions.Add(Commands.DoubleSHA256, () =>
            {
                _stack.Pop(out string data);
                var data2 = data.ComputeHash(HashAlgorithms.DoubleSHA256);
                //var data3 = new byte[64];
                //for (int i = 0; i < data2.Length; i++)
                //{
                //    data3[i] = data2[i];
                //}
                _stack.Push(data2);
                return(null);
            });
            _actions.Add(Commands.SHA512, () =>
            {
                _stack.Pop(out string data);
                var data2 = data.ComputeHash(HashAlgorithms.SHA512);
                _stack.Push(data2);
                return(null);
            });
            _actions.Add(Commands.DoubleSHA512, () =>
            {
                _stack.Pop(out string data);
                var data2 = data.ComputeHash(HashAlgorithms.DoubleSHA512);
                _stack.Push(data2);
                return(null);
            });

            _actions.Add(Commands.Dup, () =>
            {
                _stack.Pop(out string data);
                _stack.Push(data);
                return(null);
            });
            _actions.Add(Commands.CheckSig, () =>
            {
                _stack.Pop(out string PubKey);
                _stack.Pop(out string Sig);
                _stack.Pop(out string Message);
                //var MessageHash = Message.ComputeHashString(HashAlgorithms.DoubleSHA512);
                var ecdsa = new ECDSA(PubKey);
                var res   = ecdsa.Verify(Sig, Message);
                if (res)
                {
                    _stack.Push(_one);
                }
                else
                {
                    _stack.Push(_zero);
                }
                return(null);
            });
            _actions.Add(Commands.IsOne, () =>
            {
                var data = _stack.Peek;
                var res  = true;
                foreach (var item in data)
                {
                    if (item != 1)
                    {
                        res = false;
                        break;
                    }
                }
                return(res);
            });
            _actions.Add(Commands.IsZero, () =>
            {
                var data = _stack.Peek;
                var res  = true;
                foreach (var item in data)
                {
                    if (item != 0)
                    {
                        res = false;
                        break;
                    }
                }
                return(res);
            });
            _actions.Add(Commands.Eq, () =>
            {
                _stack.Pop(out string data1);
                _stack.Pop(out string data2);
                var res = data1.Equals(data2);
                if (res)
                {
                    _stack.Push(_one);
                }
                else
                {
                    _stack.Push(_zero);
                }
                return(null);
            });
        }
Example #24
0
		private void btnStartECDSA_Click (object sender, EventArgs e)
		{
			byte[] hash = new byte[160 >> 3];
			Stopwatch sw = new Stopwatch ();
			double ocSignTime, ocVerifyTime, bcSignTime, bcVerifyTime;
			{
				ECDSA ecdsa = new ECDSA (ECDomainNames.secp192r1);
				ecdsa.ToXmlString (false);
				sw.Reset ();
				sw.Start ();
				byte[] ecdsaSign = ecdsa.SignHash (hash);
				sw.Stop ();
				ocSignTime = sw.Elapsed.TotalSeconds;
				sw.Reset ();
				sw.Start ();
				ecdsa.VerifyHash (hash, ecdsaSign);
				sw.Stop ();
				ocVerifyTime = sw.Elapsed.TotalSeconds;
			}

			{
				ECDsaSigner ecdsa = new ECDsaSigner ();
				X9ECParameters SEC_P192r1 = SecNamedCurves.GetByName ("secp192r1");
				BigInteger key = new BigInteger (SEC_P192r1.N.BitCount, new Random ());
				ECDomainParameters domain = new ECDomainParameters (SEC_P192r1.Curve, SEC_P192r1.G, SEC_P192r1.N);
				ECPrivateKeyParameters privateKey = new ECPrivateKeyParameters (key, domain);
				ECPoint publicKeyPoint = SEC_P192r1.G.Multiply (key);
				ECPublicKeyParameters publicKey = new ECPublicKeyParameters (publicKeyPoint, domain);
				ecdsa.Init (true, privateKey);

				sw.Reset ();
				sw.Start ();
				BigInteger[] sign = ecdsa.GenerateSignature (hash);
				sw.Stop ();
				bcSignTime = sw.Elapsed.TotalSeconds;

				ecdsa.Init (false, publicKey);
				sw.Reset ();
				sw.Start ();
				ecdsa.VerifySignature (hash, sign[0], sign[1]);
				sw.Stop ();
				bcVerifyTime = sw.Elapsed.TotalSeconds;
			}

			double scale = 1000;
			bcSignTime *= scale;
			bcVerifyTime *= scale;
			ocSignTime *= scale;
			ocVerifyTime *= scale;

			lblBCSign.Text = "Sign (" + bcSignTime.ToString ("f2") + "ms)";
			lblBCVerify.Text = "Verify (" + bcVerifyTime.ToString ("f2") + "ms)";
			lblOCSign.Text = "Sign (" + ocSignTime.ToString ("f2") + "ms)";
			lblOCVerify.Text = "Verify (" + ocVerifyTime.ToString ("f2") + "ms)";

			double max = Math.Max (ocSignTime, Math.Max (ocVerifyTime, Math.Max (bcSignTime, bcVerifyTime)));			
			max *= 1.1;

			pbEcdsaSignBC.Maximum = pbEcdsaVerifyBC.Maximum = pbEcdsaSignOC.Maximum = pbEcdsaVerifyOC.Maximum = (int)max;
			pbEcdsaSignBC.Value = (int)bcSignTime;
			pbEcdsaVerifyBC.Value = (int)bcVerifyTime;
			pbEcdsaSignOC.Value = (int)ocSignTime;
			pbEcdsaVerifyOC.Value = (int)ocVerifyTime;
		}
Example #25
0
        private static void HandleConnection(ConnectionRequest request)
        {
            NetDataWriter rejectData = new NetDataWriter();

            try
            {
                byte result1;
                byte result2;
                int  position = request.Data.Position;
                if (!request.Data.TryGetByte(out result1) || !request.Data.TryGetByte(out result2) || result1 != CustomNetworkManager.Major || result2 != CustomNetworkManager.Minor)
                {
                    rejectData.Reset();
                    rejectData.Put(3);
                    request.Reject(rejectData);
                }
                else
                {
                    if (CustomLiteNetLib4MirrorTransport.IpRateLimiting)
                    {
                        if (CustomLiteNetLib4MirrorTransport.IpRateLimit.Contains(request.RemoteEndPoint.Address.ToString()))
                        {
                            ServerConsole.AddLog(string.Format("Incoming connection from endpoint {0} rejected due to exceeding the rate limit.", request.RemoteEndPoint));
                            ServerLogs.AddLog(ServerLogs.Modules.Networking, string.Format("Incoming connection from endpoint {0} rejected due to exceeding the rate limit.", request.RemoteEndPoint), ServerLogs.ServerLogType.RateLimit);
                            rejectData.Reset();
                            rejectData.Put(12);
                            request.Reject(rejectData);
                            return;
                        }
                        CustomLiteNetLib4MirrorTransport.IpRateLimit.Add(request.RemoteEndPoint.Address.ToString());
                    }
                    if (!CharacterClassManager.OnlineMode)
                    {
                        KeyValuePair <BanDetails, BanDetails> keyValuePair = BanHandler.QueryBan(null, request.RemoteEndPoint.Address.ToString());
                        if (keyValuePair.Value != null)
                        {
                            ServerConsole.AddLog(string.Format("Player tried to connect from banned endpoint {0}.", request.RemoteEndPoint));
                            rejectData.Reset();
                            rejectData.Put(6);
                            rejectData.Put(keyValuePair.Value.Expires);
                            rejectData.Put(keyValuePair.Value?.Reason ?? string.Empty);
                            request.Reject(rejectData);
                        }
                        else
                        {
                            request.Accept();
                        }
                    }
                    else
                    {
                        string result3;
                        if (!request.Data.TryGetString(out result3) || result3 == string.Empty)
                        {
                            rejectData.Reset();
                            rejectData.Put(5);
                            request.Reject(rejectData);
                        }
                        else
                        {
                            ulong  result4;
                            byte   result5;
                            string result6;
                            byte[] result7;
                            if (!request.Data.TryGetULong(out result4) || !request.Data.TryGetByte(out result5) || !request.Data.TryGetString(out result6) || !request.Data.TryGetBytesWithLength(out result7))
                            {
                                rejectData.Reset();
                                rejectData.Put(4);
                                request.Reject(rejectData);
                            }
                            else
                            {
                                CentralAuthPreauthFlags flags = (CentralAuthPreauthFlags)result5;
                                try
                                {
                                    if (!ECDSA.VerifyBytes(string.Format("{0};{1};{2};{3}", result3, result5, result6, result4), result7, ServerConsole.PublicKey))
                                    {
                                        ServerConsole.AddLog(string.Format("Player from endpoint {0} sent preauthentication token with invalid digital signature.", request.RemoteEndPoint));
                                        rejectData.Reset();
                                        rejectData.Put(2);
                                        request.Reject(rejectData);
                                    }
                                    else if (TimeBehaviour.CurrentUnixTimestamp > result4)
                                    {
                                        ServerConsole.AddLog(string.Format("Player from endpoint {0} sent expired preauthentication token.", request.RemoteEndPoint));
                                        ServerConsole.AddLog("Make sure that time and timezone set on server is correct. We recommend synchronizing the time.");
                                        rejectData.Reset();
                                        rejectData.Put(11);
                                        request.Reject(rejectData);
                                    }
                                    else
                                    {
                                        if (CustomLiteNetLib4MirrorTransport.UserRateLimiting)
                                        {
                                            if (CustomLiteNetLib4MirrorTransport.UserRateLimit.Contains(result3))
                                            {
                                                ServerConsole.AddLog(string.Format("Incoming connection from {0} ({1}) rejected due to exceeding the rate limit.", result3, request.RemoteEndPoint));
                                                ServerLogs.AddLog(ServerLogs.Modules.Networking, string.Format("Incoming connection from endpoint {0} ({1}) rejected due to exceeding the rate limit.", result3, request.RemoteEndPoint), ServerLogs.ServerLogType.RateLimit);
                                                rejectData.Reset();
                                                rejectData.Put(12);
                                                request.Reject(rejectData);
                                                return;
                                            }
                                            CustomLiteNetLib4MirrorTransport.UserRateLimit.Add(result3);
                                        }
                                        if (!flags.HasFlagFast(CentralAuthPreauthFlags.IgnoreBans) || !ServerStatic.GetPermissionsHandler().IsVerified)
                                        {
                                            KeyValuePair <BanDetails, BanDetails> keyValuePair = BanHandler.QueryBan(result3, request.RemoteEndPoint.Address.ToString());
                                            if (keyValuePair.Key != null || keyValuePair.Value != null)
                                            {
                                                ServerConsole.AddLog(string.Format("{0} {1} tried to connect from {2} endpoint {3}.", keyValuePair.Key == null ? "Player" : "Banned player", result3, keyValuePair.Value == null ? "" : "banned ", request.RemoteEndPoint));
                                                ServerLogs.AddLog(ServerLogs.Modules.Networking, string.Format("{0} {1} tried to connect from {2} endpoint {3}.", keyValuePair.Key == null ? "Player" : "Banned player", result3, keyValuePair.Value == null ? "" : "banned ", request.RemoteEndPoint), ServerLogs.ServerLogType.ConnectionUpdate);
                                                rejectData.Reset();
                                                rejectData.Put(6);
                                                NetDataWriter netDataWriter1 = rejectData;
                                                BanDetails    key            = keyValuePair.Key;
                                                netDataWriter1.Put(key != null ? key.Expires : keyValuePair.Value.Expires);
                                                NetDataWriter netDataWriter2 = rejectData;
                                                string        str;
                                                if ((str = keyValuePair.Key?.Reason) == null)
                                                {
                                                    str = keyValuePair.Value?.Reason ?? string.Empty;
                                                }
                                                netDataWriter2.Put(str);
                                                request.Reject(rejectData);
                                                return;
                                            }
                                        }
                                        if (flags.HasFlagFast(CentralAuthPreauthFlags.GloballyBanned) && !ServerStatic.GetPermissionsHandler().IsVerified)
                                        {
                                            bool useGlobalBans = CustomLiteNetLib4MirrorTransport.UseGlobalBans;
                                        }
                                        if ((!flags.HasFlagFast(CentralAuthPreauthFlags.IgnoreWhitelist) || !ServerStatic.GetPermissionsHandler().IsVerified) && !WhiteList.IsWhitelisted(result3))
                                        {
                                            ServerConsole.AddLog(string.Format("Player {0} tried joined from endpoint {1}, but is not whitelisted.", result3, request.RemoteEndPoint));
                                            rejectData.Reset();
                                            rejectData.Put(7);
                                            request.Reject(rejectData);
                                        }
                                        else if (CustomLiteNetLib4MirrorTransport.Geoblocking != GeoblockingMode.None && (!flags.HasFlagFast(CentralAuthPreauthFlags.IgnoreGeoblock) || !ServerStatic.GetPermissionsHandler().BanTeamBypassGeo) && (!CustomLiteNetLib4MirrorTransport.GeoblockIgnoreWhitelisted || !WhiteList.IsOnWhitelist(result3)) && (CustomLiteNetLib4MirrorTransport.Geoblocking == GeoblockingMode.Whitelist && !CustomLiteNetLib4MirrorTransport.GeoblockingList.Contains(result6.ToUpper()) || CustomLiteNetLib4MirrorTransport.Geoblocking == GeoblockingMode.Blacklist && CustomLiteNetLib4MirrorTransport.GeoblockingList.Contains(result6.ToUpper())))
                                        {
                                            ServerConsole.AddLog(string.Format("Player {0} ({1}) tried joined from blocked country {2}.", result3, request.RemoteEndPoint, result6.ToUpper()));
                                            rejectData.Reset();
                                            rejectData.Put(9);
                                            request.Reject(rejectData);
                                        }
                                        else
                                        {
                                            int num = CustomNetworkManager.slots;
                                            if (flags.HasFlagFast(CentralAuthPreauthFlags.ReservedSlot) && ServerStatic.GetPermissionsHandler().BanTeamSlots)
                                            {
                                                num = LiteNetLib4MirrorNetworkManager.singleton.maxConnections;
                                            }
                                            else if (ConfigFile.ServerConfig.GetBool("use_reserved_slots", true) && ReservedSlot.HasReservedSlot(result3))
                                            {
                                                num += CustomNetworkManager.reservedSlots;
                                            }
                                            if (LiteNetLib4MirrorCore.Host.PeersCount < num)
                                            {
                                                if (CustomLiteNetLib4MirrorTransport.UserIds.ContainsKey(request.RemoteEndPoint))
                                                {
                                                    CustomLiteNetLib4MirrorTransport.UserIds[request.RemoteEndPoint].SetUserId(result3);
                                                }
                                                else
                                                {
                                                    CustomLiteNetLib4MirrorTransport.UserIds.Add(request.RemoteEndPoint, new PreauthItem(result3));
                                                }
                                                bool allow = true;
                                                Events.InvokePreAuth(result3, request, position, result5, result6, ref allow);
                                                if (allow)
                                                {
                                                    request.Accept();
                                                    ServerConsole.AddLog(string.Format("Player {0} preauthenticated from endpoint {1}.", result3, request.RemoteEndPoint));
                                                    ServerLogs.AddLog(ServerLogs.Modules.Networking, string.Format("{0} preauthenticated from endpoint {1}.", result3, request.RemoteEndPoint), ServerLogs.ServerLogType.ConnectionUpdate);
                                                }
                                                else
                                                {
                                                    ServerConsole.AddLog(string.Format("Player {0} tried to preauthenticate from endpoint {1}, but the request has been rejected by a plugin.", result3, request.RemoteEndPoint));
                                                    ServerLogs.AddLog(ServerLogs.Modules.Networking, string.Format("{0} tried to preauthenticate from endpoint {1}, but the request has been rejected by a plugin.", result3, request.RemoteEndPoint), ServerLogs.ServerLogType.ConnectionUpdate);
                                                }
                                            }
                                            else
                                            {
                                                rejectData.Reset();
                                                rejectData.Put(1);
                                                request.Reject(rejectData);
                                            }
                                        }
                                    }
                                }
                                catch (Exception exception)
                                {
                                    ServerConsole.AddLog(string.Format("Player from endpoint {0} sent an invalid preauthentication token. {1}", request.RemoteEndPoint, exception.Message));
                                    rejectData.Reset();
                                    rejectData.Put(2);
                                    request.Reject(rejectData);
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                ServerConsole.AddLog(string.Format("Player from endpoint {0} failed to preauthenticate: {1}", request.RemoteEndPoint, exception.Message));
                rejectData.Reset();
                rejectData.Put(4);
                request.Reject(rejectData);
            }
        }
Example #26
0
 public byte[] Sign(byte[] data)
 {
     return(ECDSA.ECDSASign(data, Wif2PrivateKey(PrivSigningKeyWif)));
 }
Example #27
0
        static void Main()
        {
            AsymmetricAlgorithm signAlgo;

#if ECC
            X509Certificate cert  = new X509Certificate("localhost.x509");
            ECDSA           ecdsa = new ECDSA(openCrypto.EllipticCurve.ECDomainNames.secp256r1);
            ecdsa.Parameters.PrivateKey = new byte[] { 0x31, 0xfe, 0xa8, 0xf8, 0xdb, 0x32, 0x57, 0x79, 0xb2, 0xaf, 0xb6, 0x34, 0xef, 0xe6, 0x60,
                                                       0x00, 0x75, 0xa5, 0xd3, 0xa6, 0xba, 0x7a, 0x07, 0xc1, 0x5b, 0x8f, 0x81, 0xe1, 0xce, 0x48,
                                                       0xb2, 0x9a };
            signAlgo = ecdsa;
#elif DSS
            X509Certificate          cert     = new X509Certificate("localhost.dss.x509");
            DSACryptoServiceProvider dsa      = new DSACryptoServiceProvider();
            DSAParameters            dsaParam = new DSAParameters();
            dsaParam.G = new byte[] { 0x86, 0x41, 0x6a, 0x6f, 0xec, 0xdd, 0xaf, 0x20, 0x23, 0xd6, 0x01, 0x10, 0xb7, 0xd0, 0xc7, 0x1d, 0xfe, 0xfc, 0x16, 0x9d, 0xba, 0x82, 0xf2, 0xb0, 0x9e, 0x7e, 0x40, 0x0e, 0xb5, 0x0c, 0x04, 0x01, 0xdf, 0xe1, 0xc3, 0x3a, 0x45, 0xe2, 0xf1, 0x47, 0x4f, 0xd1, 0x35, 0x5b, 0x2e, 0x59, 0x91, 0xdb, 0x1d, 0xeb, 0xa0, 0xa8, 0x7c, 0xd3, 0x56, 0x32, 0xd7, 0xd4, 0x52, 0x86, 0xfc, 0xc5, 0xba, 0x60, 0xbe, 0x70, 0x45, 0x23, 0x8b, 0xdc, 0x27, 0x3c, 0x06, 0xb1, 0x23, 0xf1, 0x7f, 0xc2, 0x2a, 0x15, 0xb6, 0x2f, 0xbd, 0x9e, 0x0b, 0x6f, 0x57, 0xa3, 0xb3, 0x31, 0x0e, 0xd2, 0xd5, 0xdc, 0xf8, 0x6f, 0x51, 0xd7, 0x3d, 0x03, 0x9a, 0x1e, 0xf8, 0xf0, 0xbd, 0x57, 0x36, 0xe4, 0x95, 0xcf, 0x09, 0xdb, 0x49, 0x7e, 0x96, 0x45, 0x12, 0x6d, 0xfd, 0xff, 0xba, 0x2f, 0xd6, 0x55, 0xc3, 0x76, 0x2b, 0x9a };
            dsaParam.P = new byte[] { 0xc7, 0x8c, 0x4d, 0x21, 0x12, 0x1f, 0x84, 0x3d, 0x43, 0xc1, 0xd7, 0xba, 0xf9, 0xd8, 0x97, 0x56, 0x7a, 0xc4, 0xed, 0x3a, 0xff, 0x53, 0x9d, 0x2c, 0x97, 0xf9, 0x25, 0x38, 0xb6, 0xdc, 0x54, 0xb4, 0x86, 0xd1, 0x55, 0xf9, 0x43, 0xd1, 0xd1, 0x1a, 0x21, 0x7e, 0x89, 0x49, 0xea, 0xa2, 0x7b, 0x15, 0x46, 0x60, 0x1b, 0xa4, 0x69, 0x9f, 0xe1, 0x63, 0x27, 0xc6, 0x00, 0x90, 0x7a, 0x9e, 0x7e, 0x20, 0x95, 0xfe, 0xa0, 0x08, 0xef, 0xc5, 0x73, 0x38, 0x8d, 0xc9, 0x04, 0xb7, 0x8d, 0xe6, 0x44, 0xd7, 0x2b, 0x37, 0x74, 0x81, 0x84, 0x62, 0x09, 0x84, 0xa9, 0xf2, 0x60, 0x32, 0x02, 0xa5, 0xc7, 0x90, 0xce, 0xdc, 0x32, 0x94, 0x15, 0x6b, 0x7e, 0x90, 0xc8, 0x14, 0xb4, 0x06, 0x6f, 0x44, 0xee, 0x35, 0xe0, 0x40, 0xcd, 0xe0, 0x76, 0x48, 0x79, 0x9d, 0x72, 0xf6, 0xc8, 0xef, 0x86, 0x5e, 0x45, 0xcf };
            dsaParam.Q = new byte[] { 0x91, 0x66, 0x17, 0xd0, 0xb0, 0xb7, 0xfd, 0xff, 0xef, 0xfd, 0x31, 0x9b, 0x37, 0xd2, 0x5a, 0x2a, 0xbb, 0x99, 0xa0, 0x79 };
            dsaParam.X = new byte[] { 0x0a, 0x2e, 0xc0, 0x41, 0x1f, 0xdc, 0x08, 0x64, 0x24, 0xd2, 0xde, 0x64, 0x05, 0x56, 0xe6, 0x63, 0xfd, 0x52, 0x56, 0x99 };
            dsa.ImportParameters(dsaParam);
            signAlgo = dsa;
#elif RSA
            X509Certificate          cert      = new X509Certificate("localhost.rsa.x509");
            RSACryptoServiceProvider rsa       = new RSACryptoServiceProvider();
            RSAParameters            rsaParams = new RSAParameters();
            rsaParams.Exponent = new byte[] { 1, 0, 1 };
            rsaParams.Modulus  = new byte[] { 0xdb, 0x48, 0x27, 0xb7, 0x61, 0xa0, 0xb9, 0x28, 0x60, 0xb3, 0x7e, 0x3e, 0x59, 0x9f, 0x02, 0x9c, 0x9f, 0x4a, 0xa6, 0x1e, 0xba, 0xc7, 0x97, 0x55, 0xb7, 0x9c, 0x68, 0xaf, 0x37, 0x23, 0xc0, 0x78, 0x9d, 0xab, 0x2a, 0x63, 0xaf, 0x44, 0xb6, 0x1f, 0x30, 0x4c, 0x3b, 0x03, 0x85, 0x44, 0x20, 0xc5, 0xfc, 0x00, 0x76, 0x82, 0x48, 0x85, 0xc8, 0x53, 0x24, 0x55, 0x29, 0xd5, 0xce, 0x13, 0xd1, 0xb6, 0x89, 0x63, 0x9b, 0x42, 0x63, 0x26, 0x76, 0x47, 0xed, 0x95, 0xe2, 0x76, 0x59, 0xf2, 0x99, 0xdf, 0xb2, 0xb7, 0x86, 0xf5, 0x02, 0xbb, 0x81, 0x8f, 0xa0, 0x20, 0xd3, 0x8f, 0x1d, 0x92, 0x4e, 0x76, 0x7b, 0x8a, 0x31, 0xc7, 0x66, 0xc3, 0xff, 0x9f, 0xa5, 0x9d, 0xfd, 0xc2, 0x93, 0x55, 0x37, 0x7b, 0x68, 0x30, 0xca, 0xb7, 0x39, 0xd6, 0x21, 0x00, 0x69, 0x79, 0x2d, 0x9f, 0x24, 0x08, 0x5c, 0xb7 };
            rsaParams.D        = new byte[] { 0x5b, 0x84, 0x89, 0xce, 0xe7, 0x58, 0x04, 0xee, 0xed, 0x2c, 0xfc, 0x8b, 0x59, 0x2c, 0x1c, 0x12, 0xf2, 0x08, 0x5d, 0xbc, 0x85, 0x87, 0xb7, 0x89, 0x76, 0xd0, 0x38, 0x80, 0xa8, 0x2a, 0xab, 0xb1, 0xab, 0x5c, 0x3c, 0x9c, 0xce, 0x11, 0x87, 0x51, 0x0c, 0xff, 0x43, 0xc1, 0xfc, 0x64, 0xaa, 0xa8, 0xf6, 0xbb, 0xda, 0xba, 0x15, 0x3a, 0x80, 0x98, 0xf2, 0x98, 0xf8, 0x94, 0xdb, 0x25, 0x3a, 0x68, 0x86, 0x44, 0xda, 0x44, 0xa5, 0xd8, 0xce, 0x7b, 0xdb, 0xd7, 0x65, 0x31, 0x44, 0xdb, 0x57, 0xe3, 0x92, 0xca, 0xb2, 0xca, 0x5f, 0x48, 0x2c, 0x6c, 0xbe, 0x81, 0x7f, 0x3e, 0x88, 0x04, 0x8e, 0x3b, 0x39, 0xb5, 0x59, 0xda, 0x36, 0x6e, 0x97, 0x63, 0x3d, 0xb2, 0x0e, 0xb7, 0x4a, 0xfd, 0x9e, 0xa8, 0x68, 0x84, 0x0f, 0x59, 0xf1, 0xd9, 0x3c, 0x22, 0xbe, 0x8a, 0x61, 0x32, 0x00, 0x38, 0xe7, 0x41 };
            rsaParams.P        = new byte[] { 0xfd, 0x91, 0xeb, 0xe6, 0x03, 0xe0, 0x54, 0x98, 0xbc, 0x84, 0x99, 0xc1, 0x32, 0xf0, 0xae, 0x2c, 0x97, 0x21, 0xf6, 0xee, 0xe6, 0x88, 0xa9, 0x37, 0x86, 0xb0, 0x09, 0xb1, 0x11, 0x01, 0x01, 0x46, 0x25, 0xa7, 0x64, 0x2f, 0x7e, 0x86, 0x50, 0xe8, 0xc1, 0x05, 0x51, 0xb5, 0x38, 0x0f, 0xcd, 0x21, 0xcc, 0x0d, 0xea, 0xd7, 0x56, 0x24, 0xe2, 0xd7, 0xb9, 0x41, 0xf5, 0x6e, 0x66, 0x4d, 0xd4, 0xa3 };
            rsaParams.Q        = new byte[] { 0xdd, 0x62, 0x1d, 0x7d, 0x2a, 0xa9, 0x00, 0x78, 0x82, 0xb9, 0xf8, 0x22, 0x99, 0xf9, 0x30, 0xd1, 0xee, 0x73, 0x4a, 0xca, 0x90, 0x88, 0x18, 0x04, 0x6f, 0x90, 0x68, 0x3a, 0xad, 0x5f, 0x26, 0xb4, 0x6a, 0xb2, 0x2c, 0xea, 0x0b, 0x0c, 0xf5, 0x74, 0x6e, 0x3e, 0x41, 0x7d, 0xcd, 0xc8, 0xf4, 0xe3, 0x76, 0xbb, 0x3f, 0x6f, 0x43, 0xe0, 0xbb, 0x9d, 0x05, 0x26, 0xd2, 0xfe, 0x09, 0x79, 0xc4, 0xdd };
            rsaParams.DP       = new byte[] { 0xcf, 0x4b, 0xa0, 0xe7, 0x6c, 0xd9, 0xd3, 0x2e, 0xfe, 0x47, 0x05, 0x0f, 0x8d, 0x9e, 0x77, 0x35, 0x9a, 0xe4, 0x38, 0x64, 0x3b, 0xf1, 0x13, 0x2d, 0x82, 0x9d, 0x9d, 0x7e, 0xb4, 0xe0, 0xf6, 0x72, 0xab, 0x4b, 0xba, 0x3a, 0x9d, 0x9c, 0x1e, 0xbe, 0xf9, 0x35, 0x69, 0x03, 0xd6, 0x6e, 0x0c, 0x8c, 0x09, 0xae, 0x83, 0x03, 0x41, 0xb8, 0x6b, 0xfe, 0x61, 0xc4, 0x4b, 0x69, 0xd2, 0x96, 0xe4, 0x33 };
            rsaParams.DQ       = new byte[] { 0xaf, 0x30, 0x73, 0x91, 0x97, 0x6e, 0xc1, 0xf6, 0x9b, 0xcc, 0xba, 0xf5, 0xf6, 0xce, 0xe1, 0xb9, 0x5f, 0x6f, 0x51, 0x22, 0x57, 0x99, 0xbb, 0x17, 0xd7, 0x89, 0x79, 0x51, 0xe5, 0xdc, 0xc4, 0x6e, 0x45, 0x78, 0xd6, 0x5e, 0x27, 0x7c, 0x8b, 0xc9, 0x25, 0x6c, 0x92, 0xbb, 0x11, 0x5c, 0x13, 0x9e, 0xe5, 0x58, 0x6c, 0x6c, 0x8a, 0x54, 0x8f, 0x63, 0x44, 0xae, 0x62, 0x8d, 0xb1, 0xc5, 0xf0, 0xe9 };
            rsaParams.InverseQ = new byte[] { 0xbe, 0x61, 0x44, 0x09, 0xf5, 0x29, 0xfb, 0xf1, 0x0b, 0x1a, 0x44, 0xf6, 0x01, 0xc4, 0xb1, 0x99, 0xd3, 0xb3, 0x3f, 0x69, 0x2a, 0x70, 0xa0, 0x70, 0x94, 0xf2, 0x4c, 0x5f, 0x60, 0x38, 0x65, 0x0e, 0xda, 0xaa, 0xad, 0x65, 0x46, 0xa0, 0x5c, 0x3b, 0xff, 0x6a, 0x8c, 0x3f, 0x0f, 0x33, 0xc3, 0xa1, 0xb0, 0x2b, 0xc5, 0x0c, 0x09, 0x32, 0xd5, 0x2f, 0x08, 0x95, 0xda, 0xa5, 0x5b, 0xf8, 0x1a, 0xb2 };
            rsa.ImportParameters(rsaParams);
            signAlgo = rsa;
#endif

            CipherSuiteSelector selector = new CipherSuiteSelector(cert);
            X509Certificate[]   certs    = new X509Certificate[] { cert };
            Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            server.Bind(new IPEndPoint(IPAddress.Any, 443));
            server.Listen(8);

            while (true)
            {
                Socket client = null;
                try {
                    client = server.Accept();
                    using (NetworkStream nstrm = new NetworkStream(client, FileAccess.ReadWrite, true))
                        using (TLSServerStream strm = new TLSServerStream(nstrm, true, certs, signAlgo, selector)) {
                            byte[] raw     = new byte[8192];
                            int    recvLen = strm.Read(raw, 0, 4);
                            while (true)
                            {
                                if (raw[recvLen - 4] == '\r' && raw[recvLen - 3] == '\n' && raw[recvLen - 2] == '\r' && raw[recvLen - 1] == '\n')
                                {
                                    break;
                                }
                                raw[recvLen++] = (byte)strm.ReadByte();
                            }
                            Console.WriteLine(System.Text.Encoding.ASCII.GetString(raw, 0, recvLen - 2));
                            raw = System.Text.Encoding.UTF8.GetBytes("HTTP/1.0 200 OK\r\nContent-Type: text/html; charset=utf-8\r\nConnection: close\r\n\r\n" +
                                                                     "<html><body><h1>Hello ECC World !</h1><p>楕円曲線暗号の世界へようこそ!</p>" +
                                                                     "<p>このメッセージはECDSA(secp256r1)によってサーバを検証後、<br />" +
                                                                     "ECDH(secp256r1)によって共有した鍵を利用して、<br />" +
                                                                     "AES 256bitで暗号化されています</p></body></html>\r\n");
                            strm.Write(raw, 0, raw.Length);
                        }
                } catch (IOException) {
                } catch {}
            }
        }
Example #28
0
 public AccountView()
 {
     keys = ECDSA.GenerateKeys();
 }
Example #29
0
 public bool Verify()
 {
     using (ECDSA ecdsa = new ECDSA (_key.ToECPublicKey ())) {
         return ecdsa.VerifyHash (ComputeHash (), _sign);
     }
 }
Example #30
0
        public void TestPublicKeyGeneration()
        {
            var generatedPublicKey = ECDSA.GeneratePublicKey(privateKey, false);

            CollectionAssert.AreEqual(generatedPublicKey, publicKey);
        }
Example #31
0
        byte[] ParseServerKeyExchange(out ECCurve curve, IPublicKey pkey)
        {
            byte[] msg = ReadHandshakeMessageExpected(
                SSL.SERVER_KEY_EXCHANGE);
            if (msg.Length < 4)
            {
                throw new SSLException(
                          "Invalid ServerKeyExchange message");
            }
            if (msg[0] != 0x03)
            {
                throw new SSLException("Unsupported unnamed curve");
            }
            curve = SSL.GetCurveByID(IO.Dec16be(msg, 1));
            int plen = msg[3];
            int off  = 4;

            if (msg.Length - off < plen)
            {
                throw new SSLException(
                          "Invalid ServerKeyExchange message");
            }
            byte[] point = new byte[plen];
            Array.Copy(msg, off, point, 0, plen);
            off += plen;
            int slen = off;

            int hashId, sigId;

            if (Version >= SSL.TLS12)
            {
                if (msg.Length - off < 2)
                {
                    throw new SSLException(
                              "Invalid ServerKeyExchange message");
                }
                hashId = msg[off++];
                if (hashId == 0)
                {
                    throw new SSLException(
                              "Invalid hash identifier");
                }
                sigId = msg[off++];
            }
            else
            {
                if (pkey is RSAPublicKey)
                {
                    hashId = 0;
                    sigId  = 1;
                }
                else if (pkey is ECPublicKey)
                {
                    hashId = 2;
                    sigId  = 3;
                }
                else
                {
                    throw new SSLException(
                              "Unsupported signature key type");
                }
            }

            if (msg.Length - off < 2)
            {
                throw new SSLException(
                          "Invalid ServerKeyExchange message");
            }
            int sigLen = IO.Dec16be(msg, off);

            off += 2;
            if (sigLen != msg.Length - off)
            {
                throw new SSLException(
                          "Invalid ServerKeyExchange message");
            }
            byte[] sig = new byte[sigLen];
            Array.Copy(msg, off, sig, 0, sigLen);

            byte[] hv;
            if (hashId == 0)
            {
                MD5  md5  = new MD5();
                SHA1 sha1 = new SHA1();
                md5.Update(clientRandom);
                md5.Update(serverRandom);
                md5.Update(msg, 0, slen);
                sha1.Update(clientRandom);
                sha1.Update(serverRandom);
                sha1.Update(msg, 0, slen);
                hv = new byte[36];
                md5.DoFinal(hv, 0);
                sha1.DoFinal(hv, 16);
            }
            else
            {
                IDigest h = SSL.GetHashByID(hashId);
                h.Update(clientRandom);
                h.Update(serverRandom);
                h.Update(msg, 0, slen);
                hv = h.DoFinal();
            }

            bool ok;

            if (sigId == 1)
            {
                RSAPublicKey rpk = pkey as RSAPublicKey;
                if (rpk == null)
                {
                    throw new SSLException(
                              "Wrong public key type for RSA");
                }
                if (hashId == 0)
                {
                    ok = RSA.VerifyND(rpk, hv, sig);
                }
                else
                {
                    byte[] head1, head2;

                    switch (hashId)
                    {
                    case 1:
                        head1 = RSA.PKCS1_MD5;
                        head2 = RSA.PKCS1_MD5_ALT;
                        break;

                    case 2:
                        head1 = RSA.PKCS1_SHA1;
                        head2 = RSA.PKCS1_SHA1_ALT;
                        break;

                    case 3:
                        head1 = RSA.PKCS1_SHA224;
                        head2 = RSA.PKCS1_SHA224_ALT;
                        break;

                    case 4:
                        head1 = RSA.PKCS1_SHA256;
                        head2 = RSA.PKCS1_SHA256_ALT;
                        break;

                    case 5:
                        head1 = RSA.PKCS1_SHA384;
                        head2 = RSA.PKCS1_SHA384_ALT;
                        break;

                    case 6:
                        head1 = RSA.PKCS1_SHA512;
                        head2 = RSA.PKCS1_SHA512_ALT;
                        break;

                    default:
                        throw new SSLException(
                                  "Unsupported hash algorithm: "
                                  + hashId);
                    }
                    ok = RSA.Verify(rpk, head1, head2, hv, sig);
                }
            }
            else if (sigId == 3)
            {
                ECPublicKey epk = pkey as ECPublicKey;
                if (epk == null)
                {
                    throw new SSLException(
                              "Wrong public key type for ECDSA");
                }
                ok = ECDSA.Verify(epk, hv, sig);
            }
            else
            {
                throw new SSLException(
                          "Unsupported signature type: " + sigId);
            }

            if (!ok)
            {
                throw new SSLException(
                          "Invalid signature on ServerKeyExchange");
            }
            return(point);
        }
Example #32
0
		private void btnRegisterPrivateKey_Click (object sender, EventArgs e)
		{
			try {
				ECDomainNames domain;
				byte[] privateKey = ParsePrivateKey (txtGeneratedKey.Text, txtGeneratedKeyPass.Text, out domain);
				ECDSA ecdsa = new ECDSA (domain);
				ecdsa.Parameters.PrivateKey = privateKey;
			} catch (Exception ex) {
				MessageBox.Show (ex.Message);
				return;
			}
			using (TextInputDialog dlg = new TextInputDialog ("名前を入力", "秘密鍵の名前を入力してください")) {
				if (dlg.ShowDialog () == DialogResult.OK) {
					_store.AddPrivateKeyEntry (dlg.InputText, txtGeneratedKey.Text);
				}
			}
		}
Example #33
0
		static void Main ()
		{
			AsymmetricAlgorithm signAlgo;
#if ECC
			X509Certificate cert = new X509Certificate ("localhost.x509");
			ECDSA ecdsa = new ECDSA (openCrypto.EllipticCurve.ECDomainNames.secp256r1);
			ecdsa.Parameters.PrivateKey = new byte[] {0x31, 0xfe, 0xa8, 0xf8, 0xdb, 0x32, 0x57, 0x79, 0xb2, 0xaf, 0xb6, 0x34, 0xef, 0xe6, 0x60,
				0x00, 0x75, 0xa5, 0xd3, 0xa6, 0xba, 0x7a, 0x07, 0xc1, 0x5b, 0x8f, 0x81, 0xe1, 0xce, 0x48,
				0xb2, 0x9a};
			signAlgo = ecdsa;
#elif DSS
			X509Certificate cert = new X509Certificate ("localhost.dss.x509");
			DSACryptoServiceProvider dsa = new DSACryptoServiceProvider ();
			DSAParameters dsaParam = new DSAParameters ();
			dsaParam.G = new byte[] {0x86, 0x41, 0x6a, 0x6f, 0xec, 0xdd, 0xaf, 0x20, 0x23, 0xd6, 0x01, 0x10, 0xb7, 0xd0, 0xc7, 0x1d, 0xfe, 0xfc, 0x16, 0x9d, 0xba, 0x82, 0xf2, 0xb0, 0x9e, 0x7e, 0x40, 0x0e, 0xb5, 0x0c, 0x04, 0x01, 0xdf, 0xe1, 0xc3, 0x3a, 0x45, 0xe2, 0xf1, 0x47, 0x4f, 0xd1, 0x35, 0x5b, 0x2e, 0x59, 0x91, 0xdb, 0x1d, 0xeb, 0xa0, 0xa8, 0x7c, 0xd3, 0x56, 0x32, 0xd7, 0xd4, 0x52, 0x86, 0xfc, 0xc5, 0xba, 0x60, 0xbe, 0x70, 0x45, 0x23, 0x8b, 0xdc, 0x27, 0x3c, 0x06, 0xb1, 0x23, 0xf1, 0x7f, 0xc2, 0x2a, 0x15, 0xb6, 0x2f, 0xbd, 0x9e, 0x0b, 0x6f, 0x57, 0xa3, 0xb3, 0x31, 0x0e, 0xd2, 0xd5, 0xdc, 0xf8, 0x6f, 0x51, 0xd7, 0x3d, 0x03, 0x9a, 0x1e, 0xf8, 0xf0, 0xbd, 0x57, 0x36, 0xe4, 0x95, 0xcf, 0x09, 0xdb, 0x49, 0x7e, 0x96, 0x45, 0x12, 0x6d, 0xfd, 0xff, 0xba, 0x2f, 0xd6, 0x55, 0xc3, 0x76, 0x2b, 0x9a};
			dsaParam.P = new byte[] {0xc7, 0x8c, 0x4d, 0x21, 0x12, 0x1f, 0x84, 0x3d, 0x43, 0xc1, 0xd7, 0xba, 0xf9, 0xd8, 0x97, 0x56, 0x7a, 0xc4, 0xed, 0x3a, 0xff, 0x53, 0x9d, 0x2c, 0x97, 0xf9, 0x25, 0x38, 0xb6, 0xdc, 0x54, 0xb4, 0x86, 0xd1, 0x55, 0xf9, 0x43, 0xd1, 0xd1, 0x1a, 0x21, 0x7e, 0x89, 0x49, 0xea, 0xa2, 0x7b, 0x15, 0x46, 0x60, 0x1b, 0xa4, 0x69, 0x9f, 0xe1, 0x63, 0x27, 0xc6, 0x00, 0x90, 0x7a, 0x9e, 0x7e, 0x20, 0x95, 0xfe, 0xa0, 0x08, 0xef, 0xc5, 0x73, 0x38, 0x8d, 0xc9, 0x04, 0xb7, 0x8d, 0xe6, 0x44, 0xd7, 0x2b, 0x37, 0x74, 0x81, 0x84, 0x62, 0x09, 0x84, 0xa9, 0xf2, 0x60, 0x32, 0x02, 0xa5, 0xc7, 0x90, 0xce, 0xdc, 0x32, 0x94, 0x15, 0x6b, 0x7e, 0x90, 0xc8, 0x14, 0xb4, 0x06, 0x6f, 0x44, 0xee, 0x35, 0xe0, 0x40, 0xcd, 0xe0, 0x76, 0x48, 0x79, 0x9d, 0x72, 0xf6, 0xc8, 0xef, 0x86, 0x5e, 0x45, 0xcf};
			dsaParam.Q = new byte[] {0x91, 0x66, 0x17, 0xd0, 0xb0, 0xb7, 0xfd, 0xff, 0xef, 0xfd, 0x31, 0x9b, 0x37, 0xd2, 0x5a, 0x2a, 0xbb, 0x99, 0xa0, 0x79};
			dsaParam.X = new byte[] {0x0a, 0x2e, 0xc0, 0x41, 0x1f, 0xdc, 0x08, 0x64, 0x24, 0xd2, 0xde, 0x64, 0x05, 0x56, 0xe6, 0x63, 0xfd, 0x52, 0x56, 0x99};
			dsa.ImportParameters (dsaParam);
			signAlgo = dsa;
#elif RSA
			X509Certificate cert = new X509Certificate ("localhost.rsa.x509");
			RSACryptoServiceProvider rsa = new RSACryptoServiceProvider ();
			RSAParameters rsaParams = new RSAParameters ();
			rsaParams.Exponent = new byte[] {1, 0, 1};
			rsaParams.Modulus = new byte[] {0xdb, 0x48, 0x27, 0xb7, 0x61, 0xa0, 0xb9, 0x28, 0x60, 0xb3, 0x7e, 0x3e, 0x59, 0x9f, 0x02, 0x9c, 0x9f, 0x4a, 0xa6, 0x1e, 0xba, 0xc7, 0x97, 0x55, 0xb7, 0x9c, 0x68, 0xaf, 0x37, 0x23, 0xc0, 0x78, 0x9d, 0xab, 0x2a, 0x63, 0xaf, 0x44, 0xb6, 0x1f, 0x30, 0x4c, 0x3b, 0x03, 0x85, 0x44, 0x20, 0xc5, 0xfc, 0x00, 0x76, 0x82, 0x48, 0x85, 0xc8, 0x53, 0x24, 0x55, 0x29, 0xd5, 0xce, 0x13, 0xd1, 0xb6, 0x89, 0x63, 0x9b, 0x42, 0x63, 0x26, 0x76, 0x47, 0xed, 0x95, 0xe2, 0x76, 0x59, 0xf2, 0x99, 0xdf, 0xb2, 0xb7, 0x86, 0xf5, 0x02, 0xbb, 0x81, 0x8f, 0xa0, 0x20, 0xd3, 0x8f, 0x1d, 0x92, 0x4e, 0x76, 0x7b, 0x8a, 0x31, 0xc7, 0x66, 0xc3, 0xff, 0x9f, 0xa5, 0x9d, 0xfd, 0xc2, 0x93, 0x55, 0x37, 0x7b, 0x68, 0x30, 0xca, 0xb7, 0x39, 0xd6, 0x21, 0x00, 0x69, 0x79, 0x2d, 0x9f, 0x24, 0x08, 0x5c, 0xb7};
			rsaParams.D = new byte[] {0x5b, 0x84, 0x89, 0xce, 0xe7, 0x58, 0x04, 0xee, 0xed, 0x2c, 0xfc, 0x8b, 0x59, 0x2c, 0x1c, 0x12, 0xf2, 0x08, 0x5d, 0xbc, 0x85, 0x87, 0xb7, 0x89, 0x76, 0xd0, 0x38, 0x80, 0xa8, 0x2a, 0xab, 0xb1, 0xab, 0x5c, 0x3c, 0x9c, 0xce, 0x11, 0x87, 0x51, 0x0c, 0xff, 0x43, 0xc1, 0xfc, 0x64, 0xaa, 0xa8, 0xf6, 0xbb, 0xda, 0xba, 0x15, 0x3a, 0x80, 0x98, 0xf2, 0x98, 0xf8, 0x94, 0xdb, 0x25, 0x3a, 0x68, 0x86, 0x44, 0xda, 0x44, 0xa5, 0xd8, 0xce, 0x7b, 0xdb, 0xd7, 0x65, 0x31, 0x44, 0xdb, 0x57, 0xe3, 0x92, 0xca, 0xb2, 0xca, 0x5f, 0x48, 0x2c, 0x6c, 0xbe, 0x81, 0x7f, 0x3e, 0x88, 0x04, 0x8e, 0x3b, 0x39, 0xb5, 0x59, 0xda, 0x36, 0x6e, 0x97, 0x63, 0x3d, 0xb2, 0x0e, 0xb7, 0x4a, 0xfd, 0x9e, 0xa8, 0x68, 0x84, 0x0f, 0x59, 0xf1, 0xd9, 0x3c, 0x22, 0xbe, 0x8a, 0x61, 0x32, 0x00, 0x38, 0xe7, 0x41};
			rsaParams.P = new byte[] {0xfd, 0x91, 0xeb, 0xe6, 0x03, 0xe0, 0x54, 0x98, 0xbc, 0x84, 0x99, 0xc1, 0x32, 0xf0, 0xae, 0x2c, 0x97, 0x21, 0xf6, 0xee, 0xe6, 0x88, 0xa9, 0x37, 0x86, 0xb0, 0x09, 0xb1, 0x11, 0x01, 0x01, 0x46, 0x25, 0xa7, 0x64, 0x2f, 0x7e, 0x86, 0x50, 0xe8, 0xc1, 0x05, 0x51, 0xb5, 0x38, 0x0f, 0xcd, 0x21, 0xcc, 0x0d, 0xea, 0xd7, 0x56, 0x24, 0xe2, 0xd7, 0xb9, 0x41, 0xf5, 0x6e, 0x66, 0x4d, 0xd4, 0xa3};
			rsaParams.Q = new byte[] {0xdd, 0x62, 0x1d, 0x7d, 0x2a, 0xa9, 0x00, 0x78, 0x82, 0xb9, 0xf8, 0x22, 0x99, 0xf9, 0x30, 0xd1, 0xee, 0x73, 0x4a, 0xca, 0x90, 0x88, 0x18, 0x04, 0x6f, 0x90, 0x68, 0x3a, 0xad, 0x5f, 0x26, 0xb4, 0x6a, 0xb2, 0x2c, 0xea, 0x0b, 0x0c, 0xf5, 0x74, 0x6e, 0x3e, 0x41, 0x7d, 0xcd, 0xc8, 0xf4, 0xe3, 0x76, 0xbb, 0x3f, 0x6f, 0x43, 0xe0, 0xbb, 0x9d, 0x05, 0x26, 0xd2, 0xfe, 0x09, 0x79, 0xc4, 0xdd};
			rsaParams.DP = new byte[] {0xcf, 0x4b, 0xa0, 0xe7, 0x6c, 0xd9, 0xd3, 0x2e, 0xfe, 0x47, 0x05, 0x0f, 0x8d, 0x9e, 0x77, 0x35, 0x9a, 0xe4, 0x38, 0x64, 0x3b, 0xf1, 0x13, 0x2d, 0x82, 0x9d, 0x9d, 0x7e, 0xb4, 0xe0, 0xf6, 0x72, 0xab, 0x4b, 0xba, 0x3a, 0x9d, 0x9c, 0x1e, 0xbe, 0xf9, 0x35, 0x69, 0x03, 0xd6, 0x6e, 0x0c, 0x8c, 0x09, 0xae, 0x83, 0x03, 0x41, 0xb8, 0x6b, 0xfe, 0x61, 0xc4, 0x4b, 0x69, 0xd2, 0x96, 0xe4, 0x33};
			rsaParams.DQ = new byte[] {0xaf, 0x30, 0x73, 0x91, 0x97, 0x6e, 0xc1, 0xf6, 0x9b, 0xcc, 0xba, 0xf5, 0xf6, 0xce, 0xe1, 0xb9, 0x5f, 0x6f, 0x51, 0x22, 0x57, 0x99, 0xbb, 0x17, 0xd7, 0x89, 0x79, 0x51, 0xe5, 0xdc, 0xc4, 0x6e, 0x45, 0x78, 0xd6, 0x5e, 0x27, 0x7c, 0x8b, 0xc9, 0x25, 0x6c, 0x92, 0xbb, 0x11, 0x5c, 0x13, 0x9e, 0xe5, 0x58, 0x6c, 0x6c, 0x8a, 0x54, 0x8f, 0x63, 0x44, 0xae, 0x62, 0x8d, 0xb1, 0xc5, 0xf0, 0xe9};
			rsaParams.InverseQ = new byte[] {0xbe, 0x61, 0x44, 0x09, 0xf5, 0x29, 0xfb, 0xf1, 0x0b, 0x1a, 0x44, 0xf6, 0x01, 0xc4, 0xb1, 0x99, 0xd3, 0xb3, 0x3f, 0x69, 0x2a, 0x70, 0xa0, 0x70, 0x94, 0xf2, 0x4c, 0x5f, 0x60, 0x38, 0x65, 0x0e, 0xda, 0xaa, 0xad, 0x65, 0x46, 0xa0, 0x5c, 0x3b, 0xff, 0x6a, 0x8c, 0x3f, 0x0f, 0x33, 0xc3, 0xa1, 0xb0, 0x2b, 0xc5, 0x0c, 0x09, 0x32, 0xd5, 0x2f, 0x08, 0x95, 0xda, 0xa5, 0x5b, 0xf8, 0x1a, 0xb2};
			rsa.ImportParameters (rsaParams);
			signAlgo = rsa;
#endif

			CipherSuiteSelector selector = new CipherSuiteSelector (cert);
			X509Certificate[] certs = new X509Certificate[] { cert };
			Socket server = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
			server.Bind (new IPEndPoint (IPAddress.Any, 443));
			server.Listen (8);

			while (true) {
				Socket client = null;
				try {
					client = server.Accept ();
					using (NetworkStream nstrm = new NetworkStream (client, FileAccess.ReadWrite, true))
					using (TLSServerStream strm = new TLSServerStream (nstrm, true, certs, signAlgo, selector)) {
						byte[] raw = new byte[8192];
						int recvLen = strm.Read (raw, 0, 4);
						while (true) {
							if (raw[recvLen - 4] == '\r' && raw[recvLen - 3] == '\n' && raw[recvLen - 2] == '\r' && raw[recvLen - 1] == '\n')
								break;
							raw[recvLen ++] = (byte)strm.ReadByte ();
						}
						Console.WriteLine (System.Text.Encoding.ASCII.GetString (raw, 0, recvLen - 2));
						raw = System.Text.Encoding.UTF8.GetBytes ("HTTP/1.0 200 OK\r\nContent-Type: text/html; charset=utf-8\r\nConnection: close\r\n\r\n" +
							"<html><body><h1>Hello ECC World !</h1><p>楕円曲線暗号の世界へようこそ!</p>" +
							"<p>このメッセージはECDSA(secp256r1)によってサーバを検証後、<br />" +
							"ECDH(secp256r1)によって共有した鍵を利用して、<br />" +
							"AES 256bitで暗号化されています</p></body></html>\r\n");
						strm.Write (raw, 0, raw.Length);
					}
				} catch (IOException) {
				} catch {}
			}
		}
Example #34
0
 public ECDHE_ECDSA(ECDSA ecdsa)
 {
     _ecdh     = new ECDiffieHellman(openCrypto.EllipticCurve.ECDomainNames.secp256r1);
     _ecdh.KDF = null;
     _ecdsa    = ecdsa;
 }
Example #35
0
        private static void HandleConnection(ConnectionRequest request)
        {
            NetDataWriter rejectData = new NetDataWriter();

            try
            {
                byte result1;
                byte result2;
                if (!request.Data.TryGetByte(out result1) || !request.Data.TryGetByte(out result2) || result1 != CustomNetworkManager.Major || result2 != CustomNetworkManager.Minor)
                {
                    rejectData.Reset();
                    rejectData.Put(3);
                    request.Reject(rejectData);
                }
                else
                {
                    if (CustomLiteNetLib4MirrorTransport.IpRateLimiting)
                    {
                        if (CustomLiteNetLib4MirrorTransport.IpRateLimit.Contains(request.RemoteEndPoint.Address.ToString()))
                        {
                            ServerConsole.AddLog(string.Format("Connexion entrante à partir de l'IP {0} rejetée en raison d'un dépassement du taux limite.", request.RemoteEndPoint));
                            ServerLogs.AddLog(ServerLogs.Modules.Networking, string.Format("Connexion entrante à partir de l'IP {0} rejetée en raison d'un dépassement du taux limite.", request.RemoteEndPoint), ServerLogs.ServerLogType.RateLimit);
                            rejectData.Reset();
                            rejectData.Put(12);
                            request.Reject(rejectData);
                            return;
                        }
                        CustomLiteNetLib4MirrorTransport.IpRateLimit.Add(request.RemoteEndPoint.Address.ToString());
                    }

                    string result3;
                    if (!request.Data.TryGetString(out result3) || result3 == string.Empty)
                    {
                        rejectData.Reset();
                        rejectData.Put(5);
                        request.Reject(rejectData);
                    }
                    else
                    {
                        ulong  result4;
                        byte   result5;
                        string result6;
                        byte[] result7;
                        if (!request.Data.TryGetULong(out result4) || !request.Data.TryGetByte(out result5) || !request.Data.TryGetString(out result6) || !request.Data.TryGetBytesWithLength(out result7))
                        {
                            rejectData.Reset();
                            rejectData.Put(4);
                            request.Reject(rejectData);
                        }
                        else
                        {
                            CentralAuthPreauthFlags flags = (CentralAuthPreauthFlags)result5;
                            try
                            {
                                String steamID   = result3;
                                Login  LoginJSON = new Login();
                                LoginJSON.Steamid64 = steamID;
                                LoginJSON.Ip        = request.RemoteEndPoint.Address.ToString();
                                String JSON         = Serialize.ToJson(LoginJSON);
                                String JsonResponse = Methods.Post(Plugin.LoginURL, JSON);

                                try
                                {
                                    JSON.Success.SuccessResponseJSON APIResponse = AtlasUserAPI.JSON.Success.SuccessResponseJSON.FromJson(JsonResponse);

                                    if (!ECDSA.VerifyBytes(string.Format("{0};{1};{2};{3}", result3, result5, result6, result4), result7, ServerConsole.PublicKey))
                                    {
                                        ServerConsole.AddLog(string.Format("Joueur avec l'IP {0} a envoyé un jeton de préauthentification avec une signature numérique non valide.", request.RemoteEndPoint));
                                        rejectData.Reset();
                                        rejectData.Put(2);
                                        request.Reject(rejectData);
                                    }
                                    else if (TimeBehaviour.CurrentUnixTimestamp > result4)
                                    {
                                        ServerConsole.AddLog(string.Format("Joueur avec l'IP {0} a envoyé un jeton de préauthentification périmé.", request.RemoteEndPoint));
                                        ServerConsole.AddLog("Assurez-vous que l'heure et le fuseau horaire définis sur le serveur sont corrects. Nous recommandons de synchroniser l'heure.");
                                        rejectData.Reset();
                                        rejectData.Put(11);
                                        request.Reject(rejectData);
                                    }
                                    else
                                    {
                                        if (CustomLiteNetLib4MirrorTransport.UserRateLimiting)
                                        {
                                            if (CustomLiteNetLib4MirrorTransport.UserRateLimit.Contains(result3))
                                            {
                                                ServerConsole.AddLog(string.Format("Connexion entrante de {0} ({1}) rejetée en raison d'un dépassement du taux limite.", result3, request.RemoteEndPoint));
                                                ServerLogs.AddLog(ServerLogs.Modules.Networking, string.Format("Connexion entrante à partir de l'IP {0} ({1}) rejetée en raison d'un dépassement du taux limite.", result3, request.RemoteEndPoint), ServerLogs.ServerLogType.RateLimit);
                                                rejectData.Reset();
                                                rejectData.Put(12);
                                                request.Reject(rejectData);
                                                return;
                                            }
                                            CustomLiteNetLib4MirrorTransport.UserRateLimit.Add(result3);
                                        }
                                        if (!flags.HasFlagFast(CentralAuthPreauthFlags.IgnoreBans) || !ServerStatic.GetPermissionsHandler().IsVerified)
                                        {
                                            // API Check BAN.
                                            if (APIResponse.IsBanned)
                                            {
                                                ServerConsole.AddLog(string.Format("Le joueur {0} a essayé de se connecter avec l'IP {1}, mais l'API répond qu'il est banni.", result3, request.RemoteEndPoint));
                                                ServerLogs.AddLog(ServerLogs.Modules.Networking, string.Format("Le joueur {0} a essayé de se connecter avec l'IP {1}, mais l'API répond qu'il est banni.", result3, request.RemoteEndPoint), ServerLogs.ServerLogType.ConnectionUpdate);

                                                rejectData.Reset();
                                                rejectData.Put(6);
                                                request.Reject(rejectData);
                                                return;
                                            }
                                        }
                                        if (flags.HasFlagFast(CentralAuthPreauthFlags.GloballyBanned) && !ServerStatic.GetPermissionsHandler().IsVerified)
                                        {
                                            bool useGlobalBans = CustomLiteNetLib4MirrorTransport.UseGlobalBans;
                                        }
                                        if ((!flags.HasFlagFast(CentralAuthPreauthFlags.IgnoreWhitelist) || !ServerStatic.GetPermissionsHandler().IsVerified) && !WhiteList.IsWhitelisted(result3))
                                        {
                                            ServerConsole.AddLog(string.Format("Le joueur {0} a essayé de joindre à partir de l'IP {1}, mais n'est pas sur la liste blanche.", result3, request.RemoteEndPoint));
                                            rejectData.Reset();
                                            rejectData.Put(7);
                                            request.Reject(rejectData);
                                        }
                                        else if (CustomLiteNetLib4MirrorTransport.Geoblocking != GeoblockingMode.None && (!flags.HasFlagFast(CentralAuthPreauthFlags.IgnoreGeoblock) || !ServerStatic.GetPermissionsHandler().BanTeamBypassGeo) && (!CustomLiteNetLib4MirrorTransport.GeoblockIgnoreWhitelisted || !WhiteList.IsOnWhitelist(result3)) && (CustomLiteNetLib4MirrorTransport.Geoblocking == GeoblockingMode.Whitelist && !CustomLiteNetLib4MirrorTransport.GeoblockingList.Contains(result6.ToUpper()) || CustomLiteNetLib4MirrorTransport.Geoblocking == GeoblockingMode.Blacklist && CustomLiteNetLib4MirrorTransport.GeoblockingList.Contains(result6.ToUpper())))
                                        {
                                            ServerConsole.AddLog(string.Format("Le joueur {0} ({1}) a tenté de rejoindre depuis le pays bloqué {2}.", result3, request.RemoteEndPoint, result6.ToUpper()));
                                            rejectData.Reset();
                                            rejectData.Put(9);
                                            request.Reject(rejectData);
                                        }
                                        else
                                        {
                                            // API Role & Slots
                                            string role;
                                            if (Plugin.role.TryGetValue(steamID, out role))
                                            {
                                                Plugin.role.Remove(steamID);
                                            }
                                            if (!String.IsNullOrEmpty(APIResponse.Role))
                                            {
                                                Plugin.role.Add(steamID, APIResponse.Role);
                                            }
                                            else
                                            {
                                                if (ServerStatic.GetPermissionsHandler()._members.ContainsKey(steamID))
                                                {
                                                    ServerStatic.GetPermissionsHandler()._members.Remove(steamID);
                                                }
                                            }

                                            int num = CustomNetworkManager.slots;
                                            if (flags.HasFlagFast(CentralAuthPreauthFlags.ReservedSlot) && ServerStatic.GetPermissionsHandler().BanTeamSlots)
                                            {
                                                num = LiteNetLib4MirrorNetworkManager.singleton.maxConnections;
                                            }
                                            else if (ConfigFile.ServerConfig.GetBool("use_reserved_slots", true))
                                            {
                                                // API Slots
                                                if (!String.IsNullOrEmpty(APIResponse.Role))
                                                {
                                                    List <string> RoleRSRead = File.ReadAllLines(Plugin.RoleRSFilePath).ToList();
                                                    if (RoleRSRead.Contains(APIResponse.Role))
                                                    {
                                                        num = CustomNetworkManager.singleton.maxConnections;
                                                    }
                                                }
                                            }
                                            if (LiteNetLib4MirrorCore.Host.PeersCount < num)
                                            {
                                                if (CustomLiteNetLib4MirrorTransport.UserIds.ContainsKey(request.RemoteEndPoint))
                                                {
                                                    CustomLiteNetLib4MirrorTransport.UserIds[request.RemoteEndPoint].SetUserId(result3);
                                                }
                                                else
                                                {
                                                    CustomLiteNetLib4MirrorTransport.UserIds.Add(request.RemoteEndPoint, new PreauthItem(result3));
                                                }
                                                bool allow = true;
                                                Events.InvokePreAuth(ref result3, request, ref allow);
                                                if (allow)
                                                {
                                                    request.Accept();
                                                    ServerConsole.AddLog(string.Format("Le joueur {0} est préauthentifié à partir de l'IP {1}.", result3, request.RemoteEndPoint));
                                                    ServerLogs.AddLog(ServerLogs.Modules.Networking, string.Format("{0} préauthentifié à partir de l'IP {1}.", result3, request.RemoteEndPoint), ServerLogs.ServerLogType.ConnectionUpdate);
                                                }
                                            }
                                            else
                                            {
                                                ServerConsole.AddLog(string.Format("Le joueur {0} ({1}) a essayé de se connecter, mais le serveur est plein.", result3, request.RemoteEndPoint));
                                                rejectData.Reset();
                                                rejectData.Put(1);
                                                request.Reject(rejectData);
                                            }
                                        }
                                    }
                                }
                                catch (Exception exception)
                                {
                                    ServerConsole.AddLog(string.Format("Le joueur avec l'IP {0} a envoyé un jeton de préauthentification non valable. {1}", request.RemoteEndPoint, exception.Message));
                                    rejectData.Reset();
                                    rejectData.Put(2);
                                    request.Reject(rejectData);
                                }
                            }
                            catch (Exception exception)
                            {
                                ServerConsole.AddLog(string.Format("Le joueur avec l'IP {0} a subi une erreur avec l'API. {1}", request.RemoteEndPoint, exception.Message));
                                rejectData.Reset();
                                rejectData.Put(2);
                                request.Reject(rejectData);
                            }
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                ServerConsole.AddLog(string.Format("Joueur avec l'IP {0} n'a pas réussi à se préauthentifier : {1}", request.RemoteEndPoint, exception.Message));
                rejectData.Reset();
                rejectData.Put(4);
                request.Reject(rejectData);
            }
        }
Example #36
0
 public ECDHE_ECDSA(ECDSA ecdsa)
 {
     _ecdh = new ECDiffieHellman (openCrypto.EllipticCurve.ECDomainNames.secp256r1);
     _ecdh.KDF = null;
     _ecdsa = ecdsa;
 }
Example #37
0
        private void btnStartECDSA_Click(object sender, EventArgs e)
        {
            byte[]    hash = new byte[160 >> 3];
            Stopwatch sw = new Stopwatch();
            double    ocSignTime, ocVerifyTime, bcSignTime, bcVerifyTime;
            {
                ECDSA ecdsa = new ECDSA(ECDomainNames.secp192r1);
                ecdsa.ToXmlString(false);
                sw.Reset();
                sw.Start();
                byte[] ecdsaSign = ecdsa.SignHash(hash);
                sw.Stop();
                ocSignTime = sw.Elapsed.TotalSeconds;
                sw.Reset();
                sw.Start();
                ecdsa.VerifyHash(hash, ecdsaSign);
                sw.Stop();
                ocVerifyTime = sw.Elapsed.TotalSeconds;
            }

            {
                ECDsaSigner            ecdsa      = new ECDsaSigner();
                X9ECParameters         SEC_P192r1 = SecNamedCurves.GetByName("secp192r1");
                BigInteger             key        = new BigInteger(SEC_P192r1.N.BitCount, new Random());
                ECDomainParameters     domain     = new ECDomainParameters(SEC_P192r1.Curve, SEC_P192r1.G, SEC_P192r1.N);
                ECPrivateKeyParameters privateKey = new ECPrivateKeyParameters(key, domain);
                ECPoint publicKeyPoint            = SEC_P192r1.G.Multiply(key);
                ECPublicKeyParameters publicKey   = new ECPublicKeyParameters(publicKeyPoint, domain);
                ecdsa.Init(true, privateKey);

                sw.Reset();
                sw.Start();
                BigInteger[] sign = ecdsa.GenerateSignature(hash);
                sw.Stop();
                bcSignTime = sw.Elapsed.TotalSeconds;

                ecdsa.Init(false, publicKey);
                sw.Reset();
                sw.Start();
                ecdsa.VerifySignature(hash, sign[0], sign[1]);
                sw.Stop();
                bcVerifyTime = sw.Elapsed.TotalSeconds;
            }

            double scale = 1000;

            bcSignTime   *= scale;
            bcVerifyTime *= scale;
            ocSignTime   *= scale;
            ocVerifyTime *= scale;

            lblBCSign.Text   = "Sign (" + bcSignTime.ToString("f2") + "ms)";
            lblBCVerify.Text = "Verify (" + bcVerifyTime.ToString("f2") + "ms)";
            lblOCSign.Text   = "Sign (" + ocSignTime.ToString("f2") + "ms)";
            lblOCVerify.Text = "Verify (" + ocVerifyTime.ToString("f2") + "ms)";

            double max = Math.Max(ocSignTime, Math.Max(ocVerifyTime, Math.Max(bcSignTime, bcVerifyTime)));

            max *= 1.1;

            pbEcdsaSignBC.Maximum = pbEcdsaVerifyBC.Maximum = pbEcdsaSignOC.Maximum = pbEcdsaVerifyOC.Maximum = (int)max;
            pbEcdsaSignBC.Value   = (int)bcSignTime;
            pbEcdsaVerifyBC.Value = (int)bcVerifyTime;
            pbEcdsaSignOC.Value   = (int)ocSignTime;
            pbEcdsaVerifyOC.Value = (int)ocVerifyTime;
        }
Example #38
0
		private void btnPublicKeyGenerate_Click (object sender, EventArgs e)
		{
			try {
				ECDomainNames domain;
				byte[] privateKey = ParsePrivateKey (txtGeneratedKey.Text, txtGeneratedKeyPass.Text, out domain);
				ECDSA ecdsa = new ECDSA (domain);
				ecdsa.Parameters.PrivateKey = privateKey;
				string publicKey = Convert.ToBase64String (ecdsa.Parameters.ExportPublicKey (domain != ECDomainNames.secp224r1 ? true : false));
				txtGeneratedPublicKey.Text = domain.ToString ().Substring(4) + "=" + publicKey;
			} catch (Exception ex) {
				MessageBox.Show (ex.Message);
			}
		}
Example #39
0
        /// <summary>
        /// Try get algorithm from mechanism.
        /// </summary>
        /// <param name="mechanism">Algorithm mechanism.</param>
        /// <param name="algorithm">Algorithm.</param>
        /// <returns></returns>
        public static bool TryGetAlgorithm(string mechanism, out ISignatureAlgorithm algorithm)
        {
            mechanism = mechanism.Replace('_', '-').ToUpperInvariant();
            switch (mechanism)
            {
            case "SHA1WITHCVC-ECDSA":
            case "SHA-1WITHCVC-ECDSA": algorithm = SHA1withCVC_ECDSA; return(true);

            case "SHA224WITHCVC-ECDSA":
            case "SHA-224WITHCVC-ECDSA": algorithm = SHA224withCVC_ECDSA; return(true);

            case "SHA256WITHCVC-ECDSA":
            case "SHA-256WITHCVC-ECDSA": algorithm = SHA256withCVC_ECDSA; return(true);

            case "SHA384WITHCVC-ECDSA":
            case "SHA-384WITHCVC-ECDSA": algorithm = SHA384withCVC_ECDSA; return(true);

            case "SHA512WITHCVC-ECDSA":
            case "SHA-512WITHCVC-ECDSA": algorithm = SHA512withCVC_ECDSA; return(true);

            case "ED25519": algorithm = new Ed25519(); return(true);

            case "ED25519CTX": algorithm = new Ed25519ctx(); return(true);

            case "ED25519PH": algorithm = new Ed25519ph(); return(true);

            case "ED448": algorithm = new Ed448(); return(true);

            case "ED448PH": algorithm = new Ed448ph(); return(true);

            case "GOST3411WITHECGOST3410":
            case "ECGOST3410":
            case "ECGOST3410-2001":
            case "ECGOST-3410":
            case "ECGOST-3410-2001": algorithm = GOST3411withECGOST3410; return(true);

            case "GOST3411WITHGOST3410":
            case "GOST3410":
            case "GOST3410-94":
            case "GOST-3410":
            case "GOST-3410-94": algorithm = GOST3411withGOST3410; return(true);

            case "RIPEMD160WITHPLAIN-ECDSA":
            case "RIPEMD-160WITHPLAIN-ECDSA": algorithm = RIPEMD160withPLAIN_ECDSA; return(true);

            case "SHA1WITHPLAIN-ECDSA":
            case "SHA-1WITHPLAIN-ECDSA": algorithm = SHA1withPLAIN_ECDSA; return(true);

            case "SHA224WITHPLAIN-ECDSA":
            case "SHA-224WITHPLAIN-ECDSA": algorithm = SHA224withPLAIN_ECDSA; return(true);

            case "SHA256WITHPLAIN-ECDSA":
            case "SHA-256WITHPLAIN-ECDSA": algorithm = SHA256withPLAIN_ECDSA; return(true);

            case "SHA384WITHPLAIN-ECDSA":
            case "SHA-384WITHPLAIN-ECDSA": algorithm = SHA384withPLAIN_ECDSA; return(true);

            case "SHA512WITHPLAIN-ECDSA":
            case "SHA-512WITHPLAIN-ECDSA": algorithm = SHA512withPLAIN_ECDSA; return(true);

            case "PSSWITHRSA": algorithm = PSSwithRSA; return(true);

            case "SHA1WITHDSA":
            case "SHA-1WITHDSA": algorithm = SHA1withDSA; return(true);

            case "SHA224WITHDSA":
            case "SHA-224WITHDSA": algorithm = SHA224withDSA; return(true);

            case "SHA256WITHDSA":
            case "SHA-256WITHDSA": algorithm = SHA256withDSA; return(true);

            case "SHA384WITHDSA":
            case "SHA-384WITHDSA": algorithm = SHA384withDSA; return(true);

            case "SHA512WITHDSA":
            case "SHA-512WITHDSA": algorithm = SHA512withDSA; return(true);

            case "SHA3-224WITHDSA":
            case "SHA-3-224WITHDSA": algorithm = SHA3_224withDSA; return(true);

            case "SHA3-256WITHDSA":
            case "SHA-3-256WITHDSA": algorithm = SHA3_256withDSA; return(true);

            case "SHA3-384WITHDSA":
            case "SHA-3-384WITHDSA": algorithm = SHA3_384withDSA; return(true);

            case "SHA3-512WITHDSA":
            case "SHA-3-512WITHDSA": algorithm = SHA3_512withDSA; return(true);

            case "SHA1WITHECDSA":
            case "SHA-1WITHECDSA": algorithm = SHA1withECDSA; return(true);

            case "SHA224WITHECDSA":
            case "SHA-224WITHECDSA": algorithm = SHA224withECDSA; return(true);

            case "SHA256WITHECDSA":
            case "SHA-256WITHECDSA": algorithm = SHA256withECDSA; return(true);

            case "SHA384WITHECDSA":
            case "SHA-384WITHECDSA": algorithm = SHA384withECDSA; return(true);

            case "SHA512WITHECDSA":
            case "SHA-512WITHECDSA": algorithm = SHA512withECDSA; return(true);

            case "SHA3-224WITHECDSA":
            case "SHA-3-224WITHECDSA": algorithm = SHA3_224withECDSA; return(true);

            case "SHA3-256WITHECDSA":
            case "SHA-3-256WITHECDSA": algorithm = SHA3_256withECDSA; return(true);

            case "SHA3-384WITHECDSA":
            case "SHA-3-384WITHECDSA": algorithm = SHA3_384withECDSA; return(true);

            case "SHA3-512WITHECDSA":
            case "SHA-3-512WITHECDSA": algorithm = SHA3_512withECDSA; return(true);

            case "MD2WITHRSA": algorithm = MD2withRSA; return(true);

            case "MD5WITHRSA": algorithm = MD5withRSA; return(true);

            case "RIPEMD128WITHRSA":
            case "RIPEMD-128WITHRSA": algorithm = RIPEMD128withRSA; return(true);

            case "RIPEMD160WITHRSA":
            case "RIPEMD-160WITHRSA": algorithm = RIPEMD160withRSA; return(true);

            case "RIPEMD256WITHRSA":
            case "RIPEMD-256WITHRSA": algorithm = RIPEMD256withRSA; return(true);

            case "SHA1WITHRSA":
            case "SHA-1WITHRSA": algorithm = SHA1withRSA; return(true);

            case "SHA224WITHRSA":
            case "SHA-224WITHRSA": algorithm = SHA224withRSA; return(true);

            case "SHA256WITHRSA":
            case "SHA-256WITHRSA": algorithm = SHA256withRSA; return(true);

            case "SHA384WITHRSA":
            case "SHA-384WITHRSA": algorithm = SHA384withRSA; return(true);

            case "SHA512WITHRSA":
            case "SHA-512WITHRSA": algorithm = SHA512withRSA; return(true);

            case "SHA3-224WITHRSA":
            case "SHA-3-224WITHRSA": algorithm = SHA3_224withRSA; return(true);

            case "SHA3-256WITHRSA":
            case "SHA-3-256WITHRSA": algorithm = SHA3_256withRSA; return(true);

            case "SHA3-384WITHRSA":
            case "SHA-3-384WITHRSA": algorithm = SHA3_384withRSA; return(true);

            case "SHA3-512WITHRSA":
            case "SHA-3-512WITHRSA": algorithm = SHA3_512withRSA; return(true);

            case "SHA1WITHRSAANDMGF1":
            case "SHA-1WITHRSAANDMGF1": algorithm = PSSwithRSA; return(true);

            case "SHA256WITHSM2":
            case "SHA-256WITHSM2": algorithm = SHA256withSM2; return(true);

            case "SM3WITHSM2": algorithm = SM3withSM2; return(true);

            default: break;
            }
            string prefix;
            string suffix;
            int    index = mechanism.IndexOf("WITH");

            if (index >= 0)
            {
                prefix = mechanism.Substring(0, index);
                suffix = mechanism.Substring(index + 4, mechanism.Length - index - 4);
            }
            else
            {
                prefix = string.Empty;
                suffix = mechanism;
            }
            if (suffix == "ELGAMAL")
            {
                algorithm = null;
                return(false);
            }
            if (HashAlgorithmHelper.TryGetAlgorithm(prefix, out IHashAlgorithm hashAlgorithm))
            {
                switch (suffix)
                {
                case "CVC-ECDSA": algorithm = new CVC_ECDSA(hashAlgorithm); return(true);

                case "DSA": algorithm = new DSA(hashAlgorithm); return(true);

                case "ECDSA": algorithm = new ECDSA(hashAlgorithm); return(true);

                case "ECGOST3410":
                case "ECGOST3410-2001":
                case "ECGOST-3410":
                case "ECGOST-3410-2001": algorithm = new ECGOST3410(hashAlgorithm); return(true);

                case "ECNR": algorithm = new ECNR(hashAlgorithm); return(true);

                case "GOST3410":
                case "GOST3410-94":
                case "GOST-3410":
                case "GOST-3410-94": algorithm = new GOST3410(hashAlgorithm); return(true);

                case "PLAIN-ECDSA": algorithm = new PLAIN_ECDSA(hashAlgorithm); return(true);

                case "RSA": algorithm = new RSA(hashAlgorithm); return(true);

                case "ISO9796-2":
                case "RSA/ISO9796-2":
                case "RSAANDISO9796-2": algorithm = new RSAandISO9796_2(hashAlgorithm); return(true);

                case "RSAANDMGF1": algorithm = new RSAandMGF1(hashAlgorithm); return(true);

                case "RSA/X9.31":
                case "RSA/X931":
                case "RSAANDX931":
                case "RSAANDX9.31": algorithm = new RSAandX931(hashAlgorithm); return(true);

                case "SM2": algorithm = new SM2(hashAlgorithm); return(true);

                default: break;
                }
            }
            algorithm = null;
            return(false);
        }
Example #40
0
		static void SignVerifyTest (ECDomainNames domainName)
		{
			int repeat = 5;
			for (int i = 0; i < repeat; i ++) {
				ECDSA ecdsa = new ECDSA (domainName);
				byte[] pubKey = ecdsa.Parameters.PublicKey;
				byte[] hash = RNG.GetBytes (ecdsa.KeySize >> 3);
				byte[] sign = ecdsa.SignHash (hash);
				ecdsa = new ECDSA (domainName);
				ecdsa.Parameters.PublicKey = pubKey;
				Assert.IsTrue (ecdsa.VerifyHash (hash, sign), "Success Test " + domainName.ToString ());
				sign[0]++;
				Assert.IsFalse (ecdsa.VerifyHash (hash, sign), "Failure Test " + domainName.ToString ());
			}
		}
Example #41
0
 public void Sign(ECKeyPair privateKey)
 {
     _key = Key.Create (privateKey);
     using (ECDSA ecdsa = new ECDSA (privateKey)) {
         _sign = ecdsa.SignHash (ComputeHash ());
     }
 }