Beispiel #1
0
        protected virtual void Dispose(bool disposing)
        {
            if (!Disposed)
            {
                Server.RemoveClient(this);
                if (disposing)
                {
                    // dispose managed state (managed objects).
                    foreach (var http in RemoteClients)
                    {
                        http.Value.Dispose();
                    }
                    _taskScheduler.Dispose();
                    RemoteClients.Clear();
                    _timer.Dispose();
                    Authenticator.Dispose();
                    Cryptor.Dispose();
                }

                // free unmanaged resources (unmanaged objects) and override a finalizer below.
                // set large fields to null.

                _taskScheduler = null;
                _taskFactory   = null;
                _timer         = null;
                RemoteClients  = null;
                Disposed       = true;
            }
        }
        public string CheckForCookies()
        {
            Cryptor cryptor = new Cryptor();

            if (Request.Cookies["Guest"] == null)
            {
                HttpCookie GuestCookie   = new HttpCookie("Guest");
                Random     rnd           = new Random();
                int        randomNumber1 = rnd.Next(1, 10);
                int        randomNumber2 = rnd.Next(11, 200);
                string     GuestValue    = cryptor.Encrypt(DateTime.Now.ToString() + randomNumber1 + randomNumber2, true);
                GuestCookie.Value   = GuestValue;
                GuestCookie.Expires = DateTime.Now.AddHours(1);
                Response.Cookies.Add(GuestCookie);
                try
                {
                    CookieCart cookieCart = new CookieCart();
                    cookieCart.CookieId       = GuestValue;
                    cookieCart.ProductsInCart = new List <ProductInCart>();
                    cookieCart.WholePrice     = 0;
                    CookieCartService.CreateCookieCart(cookieCart);
                    CookieCartService.SaveCookieCart();
                    return(GuestValue);
                }
                catch (Exception E)
                {
                    throw new Exception(E.ToString());
                }
            }
            else
            {
                return(Request.Cookies["Guest"].Value);
            }
        }
Beispiel #3
0
 public IClient Create(Socket s)
 {
     var cryptor = new Cryptor();
     var packetReceiver = new AsyncWorldPaketReceiver(s, cryptor);
     var packetSender = new WorldPacketSender(s, cryptor);
     return new AsyncClient(packetReceiver, new WorldPacketProcessor(new Session(packetSender), cryptor));
 }
Beispiel #4
0
 public void DecryptBlock(ref BlockData block)
 {
     if (block.IsValid)
     {
         block.Data = Cryptor?.Decrypt(block.Data.Span) ?? block.Data;
     }
 }
Beispiel #5
0
        public void SmallCryptoSignTest()
        {
            var correctSignature = new Dictionary <string, string>
            {
                ["RSA/SHA1"]   = "iilrLSxFCe/SYFoNKDjeomjE/zJoJzrU433NSPJ85TKzFNahbthbhsjijfTfq16shXQabEr5V3IWMQ702dk+GtWx7dgK5qUVr8mXGi3A9ZzGdKxghbY6a308vEC+tr4JD2HUQOY9gW5cQdPxZt7Jkm/9A5W70vdYtE+2h5/X+qs=",
                ["RSA/SHA256"] = "YrCf/Qwj3UltmL7XYqIVLC+9xyxiHUy5p4YfSKjl3GKcROPqp4gLsuAE+/vpXIGxr8NBp1bCGWRTAApK0ckBmsyVyzQC/MPEXliXj6qXr/aodLRuWU1m9/oYOttSLg6r4DqEWQbfJjBAdy1GIA3sPhLYRgfz4Sa1VH0IHkSE0so=",
                ["RSA/SHA512"] = "dmhEcGFugupRADBMGP8iDaMxwl6e+X3f5Wge3LaJqJVHZDyPP0Mh+mimGgkVGF8hFKcXQTvlAxDBB4Wwia8qNcWkzMoyVhWgUS7DwXzzfplFcp1rvb3PPXFCVFo80j5LYLbWB2TCDL+FP8GhuaLCrR4kSWb5feQUyQ6wCqoW9g4=",
                ["RSA/MD5"]    = "IilgnaFfbhLhE6u9c6nUPnIpRpiYG0nz9OH3IP1UPEd8AmggrWF2tQx6lwlN6nAEkHoKfW+qwFjXZeANKgPLFiuYygzu3gC97nBuyZEj7kXcSr/5oPstf+g8tzyPSvPUOp7+i4PhfYoDdvIusBMcbeDm1OdN2H57j7kCBYoIT1w=",
            };

            foreach (var type in Helpers.GetValues <Cryptor.Type>())
            {
                if ((type == Cryptor.Type.None) || (type == Cryptor.Type.RSAAES) || (type.IsSymmetric()))
                {
                    continue;
                }

                var hashes = type.SigningHashes();
                foreach (var hash in hashes)
                {
                    var signature = Cryptor.Sign(SmallTestData, type, privKeys[type], hash);
                    if (type != Cryptor.Type.DSA)                     // DSA generates a new one every time.
                    {
                        Assert.AreEqual(signature, correctSignature[$"{type}/{hash}"]);
                    }
                    Assert.IsTrue(Cryptor.Verify(SmallTestData, type, pubKeys[type], hash, signature));
                }
            }
        }
Beispiel #6
0
 public async void DecryptioInvalidPublicKeyInPairTestAsync()
 {
     const string PRIVATE_KEY = "863df54207c285feac2c22235c336869fee8dba6605b8e1bc45cc8aa5e1be3fd7e53781865717d686cb3fee427823ffd8c71ea6a4d8f79c0b410457c9f881fa3";
     const string PUBLIC_KEY  = "1158b1ea7d45919968b87dab6cab27eff5871304ea9856588e9ec02a6d93c42e";
     var          testKeyPair = new KeyPair(Utilities.HexToBinary(PUBLIC_KEY), Utilities.HexToBinary(PRIVATE_KEY));
     await Cryptor.DecryptFileWithStreamAsync(testKeyPair, "badfile", Path.Combine("Testfiles", "decrypted"));
 }
Beispiel #7
0
        public async void DecryptionCancellationTestAsync()
        {
            var cancellationTokenSource = new CancellationTokenSource();
            var progressEncrypt         = new Progress <StreamCryptorTaskAsyncProgress>();
            var progressDecrypt         = new Progress <StreamCryptorTaskAsyncProgress>();

            progressEncrypt.ProgressChanged +=
                (s, e) => { Console.WriteLine("Encrypting: " + e.ProgressPercentage + "%\n"); };
            progressDecrypt.ProgressChanged +=
                (s, e) =>
            {
                if (e.ProgressPercentage > 10)
                {
                    cancellationTokenSource.Cancel();
                }
                Console.WriteLine("Decrypting: " + e.ProgressPercentage + "%\n");
            };
            var          RAW_FILE         = Path.Combine("Testfiles", "MyAwesomeChipmunkKiller.jpg");
            var          OUTPUT_DIRECTORY = Path.Combine("Testfiles", "decrypted");
            const string PRIVATE_KEY      = "31d9040b00a170532929b37db0afcb989e4175f96e5f9667ee8cbf5706679a71";
            const string PUBLIC_KEY       = "6d0deec730700f9f60687a4e6e8755157ca22ea2f3815b9bf14b1fe9ae6a0b4d";
            var          keyPair          = new KeyPair(Utilities.HexToBinary(PUBLIC_KEY), Utilities.HexToBinary(PRIVATE_KEY));

            Console.Write("Encrypting testfile . . .\n");
            var encryptedFile =
                await
                Cryptor.EncryptFileWithStreamAsync(keyPair.PrivateKey, keyPair.PublicKey,
                                                   Utilities.HexToBinary(PUBLIC_KEY), RAW_FILE, progressEncrypt, OUTPUT_DIRECTORY, ".test", true, cancellationTokenSource.Token);

            Console.Write("Decrypting testfile . . .\n");
            var decryptedFile =
                await
                Cryptor.DecryptFileWithStreamAsync(keyPair.PrivateKey, Path.Combine(OUTPUT_DIRECTORY, encryptedFile),
                                                   OUTPUT_DIRECTORY, progressDecrypt, cancellationToken : cancellationTokenSource.Token);
        }
Beispiel #8
0
        public void LargeCryptoSignTest()
        {
            var correctSignature = new Dictionary <string, string>
            {
                ["RSA/SHA1"]   = "Gdx77jzSC6LWUpEPUORd/3srsIJKLd7DLlwigA28bHsrrA1xgrXRpXzgjGZ8K8m4Y0BuhSg+WpCoQAv7hnutlWiHeFHtSVlVR8DQXyHwQEA1uxdEXHcoISGGY0+W0kNizWuqTysMjL8CNcz06/uMGbHanDAiFeq5MUmIBNhGtso=",
                ["RSA/SHA256"] = "nt9rbYhDU3svyVf5RioGmDS+R+muXhopC3H8o/ovjLxIZBmSQ5Q5aMkE04h4vsEcTaIgQUiCfFCrGraSx+yFajjGO2I9yEsFU+BHWTqdMSllF6eNfJU1Jiu5gV0CNNwEBiPzPdwmcZ1kZpw1W0Fhr1/dfHPX66iS3TFVsfLh9lo=",
                ["RSA/SHA512"] = "L6hHPvnZC5AmCDOAMZMEezVcJB1TG+f2TERIDDdsGvF24bX2dhPYz2hoZL7U9+XlEnXmXX+8chlCndj9/aKx9qL2ia23YOhyk6plKID7aPXiHi5j246/l4wUEMyUUnJ4C3xLVElhzS90hEJqknsCWLgokbDDzoP0SDLVP514b4c=",
                ["RSA/MD5"]    = "wXJS8uJA98fo/J17HIp1OgvO8PSU7sTHFZKgG/i/9m1hISrZY8p8AlZC7CbxNI9BgP9I1kTHtj6ZnUUU5Kcqi6stKurYQLJiIgCd/2uUd+qy56/XA8ydkYT6TFZ4z7nD1N1VnuAQqWH+/42yeX8x1tV132Kf8ApnSsXnQgY53t8=",
            };

            foreach (var type in Helpers.GetValues <Cryptor.Type>())
            {
                if ((type == Cryptor.Type.None) || (type == Cryptor.Type.RSAAES) || (type.IsSymmetric()))
                {
                    continue;
                }

                var hashes = type.SigningHashes();
                foreach (var hash in hashes)
                {
                    var signature = Cryptor.Sign(LargeTestData, type, privKeys[type], hash);
                    if (type != Cryptor.Type.DSA)                     // DSA generates a new one every time.
                    {
                        Assert.AreEqual(signature, correctSignature[$"{type}/{hash}"]);
                    }
                    Assert.IsTrue(Cryptor.Verify(LargeTestData, type, pubKeys[type], hash, signature));
                }
            }
        }
Beispiel #9
0
        public async Task WorkWithImageFileByteArrayTestAsync()
        {
            var progressEncrypt = new Progress <StreamCryptorTaskAsyncProgress>();
            var progressDecrypt = new Progress <StreamCryptorTaskAsyncProgress>();

            progressEncrypt.ProgressChanged +=
                (s, e) => { Console.WriteLine("Encrypting: " + e.ProgressPercentage + "%\n"); };
            progressDecrypt.ProgressChanged +=
                (s, e) => { Console.WriteLine("Decrypting: " + e.ProgressPercentage + "%\n"); };
            var          rawFile         = Path.Combine(TestContext.CurrentContext.TestDirectory, "Testfiles", "MyAwesomeChipmunkKiller.jpg");
            var          outputDirectory = Path.Combine(TestContext.CurrentContext.TestDirectory, "Testfiles", "decrypted");
            const string privateKey      = "31d9040b00a170532929b37db0afcb989e4175f96e5f9667ee8cbf5706679a71";
            const string publicKey       = "6d0deec730700f9f60687a4e6e8755157ca22ea2f3815b9bf14b1fe9ae6a0b4d";
            var          keyPair         = new KeyPair(Utilities.HexToBinary(publicKey), Utilities.HexToBinary(privateKey));

            Console.Write("Encrypting testfile . . .\n");
            var encryptedFile =
                await
                Cryptor.EncryptFileWithStreamAsync(keyPair.PrivateKey, keyPair.PublicKey,
                                                   Utilities.HexToBinary(publicKey), rawFile, progressEncrypt, outputDirectory, ".test", true);

            Console.Write("Decrypting testfile . . .\n");
            var decryptedFileObject =
                await
                Cryptor.DecryptFileWithStreamAsync(keyPair.PrivateKey,
                                                   Path.Combine(TestContext.CurrentContext.TestDirectory, outputDirectory, encryptedFile),
                                                   progressDecrypt);

            Console.Write("Get checksum of testfiles . . .\n");
            Assert.AreEqual(Utils.GetChecksum(rawFile), Utils.GetChecksum(decryptedFileObject.FileData));
            //clear garbage
            File.Delete(Path.Combine(TestContext.CurrentContext.TestDirectory, outputDirectory, encryptedFile));
        }
Beispiel #10
0
        private 券商 GetPageEntity()
        {
            var o = new Entity.券商();

            o.IP    = this.txtIP.Text;
            o.Port  = short.Parse(this.txtPort.Text);
            o.版本号   = this.txt版本号.Text;
            o.登录帐号  = this.txt登录帐号.Text;
            o.交易服务器 = this.txt交易服务器.Text;
            o.交易密码  = this.txt交易密码.Text.Trim();
            o.交易帐号  = this.txt交易帐号.Text;
            o.称     = this.txt名称.Text;
            o.启用    = this.ckIsEnable.IsChecked == true;
            o.通讯密码  = this.txt通讯密码.Text.Trim();

            if (ckbIsEncrypcy.IsChecked != true)
            {
                o.交易密码 = Cryptor.MD5Encrypt(this.txt交易密码.Text.Trim());
                o.通讯密码 = Cryptor.MD5Encrypt(this.txt通讯密码.Text.Trim());
            }
            if (o.通讯密码 == "")
            {
                o.通讯密码 = Cryptor.MD5Encrypt(o.通讯密码);
            }
            o.营业部代码 = short.Parse(this.txt营业部代码.Text);
            return(o);
        }
Beispiel #11
0
        public async Task WorkWithImageFileAndWrongKeyTestAsync()
        {
            var          rawFile         = Path.Combine(TestContext.CurrentContext.TestDirectory, "Testfiles", "MyAwesomeChipmunkKiller.jpg");
            var          outputDirectory = Path.Combine(TestContext.CurrentContext.TestDirectory, "Testfiles", "decrypted");
            const string privateKey      = "31d9040b00a170532929b37db0afcb989e4175f96e5f9667ee8cbf5706679a71";
            const string publicKey       = "6d0deec730700f9f60687a4e6e8755157ca22ea2f3815b9bf14b1fe9ae6a0b4d";
            var          keyPair         = new KeyPair(Utilities.HexToBinary(publicKey), Utilities.HexToBinary(privateKey));
            var          testKeyPair     = PublicKeyBox.GenerateKeyPair();

            Console.Write("Encrypting testfile . . .\n");
            //encrypt the file with an ephmeral key
            var encryptedFile =
                await
                Cryptor.EncryptFileWithStreamAsync(keyPair, testKeyPair.PublicKey, rawFile, null, outputDirectory,
                                                   ".test", true);

            Console.Write("Decrypting testfile . . .\n");
            //try to decrypt with an wrong key
            var decryptedFile =
                Assert.ThrowsAsync <CryptographicException>(
                    async() => await
                    Cryptor.DecryptFileWithStreamAsync(keyPair,
                                                       Path.Combine(TestContext.CurrentContext.TestDirectory, outputDirectory, encryptedFile),
                                                       outputDirectory));


            File.Delete(Path.Combine(TestContext.CurrentContext.TestDirectory, outputDirectory, encryptedFile));
        }
Beispiel #12
0
        private Result <UserProfile> CardLogin(string phoneNumber, string password, string code)
        {
            var user = this.db.Entity <User>().Query().Where(m => m.UserName == phoneNumber).FirstOrDefault();

            if (user == null)
            {
                return(Result <UserProfile> .Fail(ResultCode.Error));
            }
            if (Cryptor.EncryptMD5(password) == user.Password)
            {
                return(Result <UserProfile> .Success(new UserProfile()
                {
                    Id = user.Id,
                    Language = user.Language,
                    Birthday = user.Birthday,
                    City = user.City,
                    Country = user.Country,
                    Distinct = user.Distinct,
                    Gender = user.Gender,
                    IsConfirmed = user.IsConfirmed,
                    IsLocked = user.IsLocked,
                    IsLunarBirthday = user.IsLunarBirthday,
                    LockedTime = user.LockedTime,
                    Name = user.Name,
                    NickName = user.NickName,
                    Province = user.Province,
                    UserName = user.UserName,
                    Roles = user.Roles.Split(';', ',', '|'),
                }));
            }
            return(Result <UserProfile> .Fail(ResultCode.Error));
        }
Beispiel #13
0
        public void WorkWithImageFileExternalTest()
        {
            var          rawFile             = Path.Combine(TestContext.CurrentContext.TestDirectory, "Testfiles", "MyAwesomeChipmunkKiller.jpg");
            var          outputDirectory     = Path.Combine(TestContext.CurrentContext.TestDirectory, "Testfiles", "decrypted");
            const string privateKeyRecipient = "31d9040b00a170532929b37db0afcb989e4175f96e5f9667ee8cbf5706679a71";
            const string publicKeyRecipient  = "6d0deec730700f9f60687a4e6e8755157ca22ea2f3815b9bf14b1fe9ae6a0b4d";
            const string privateKeySender    = "da9e790389c2d94d165d60369e0945e3fe50451a55989b80b576ce69f08a24f1";
            const string publicKeySender     = "385bb72a7e4ca582b4eb59a364516d885659e753d4b2230c2f03f2e495b21c42";

            Console.Write("Encrypting testfile . . .\n");
            var encryptedFile = Cryptor.EncryptFileWithStream(
                Utilities.HexToBinary(privateKeySender),
                Utilities.HexToBinary(publicKeySender),
                Utilities.HexToBinary(publicKeyRecipient),
                rawFile, outputDirectory, ".whatever", true);

            Console.Write("Decrypting testfile (" + encryptedFile + ") . . .\n");
            var decryptedFile = Cryptor.DecryptFileWithStream(
                Utilities.HexToBinary(privateKeyRecipient),
                Path.Combine(outputDirectory, encryptedFile),
                outputDirectory);

            Console.Write("Get checksum of testfiles . . .\n");
            Assert.AreEqual(Utils.GetChecksum(rawFile),
                            Utils.GetChecksum(Path.Combine(outputDirectory, decryptedFile)));
            //clear garbage
            File.Delete(Path.Combine(outputDirectory, encryptedFile));
            File.Delete(Path.Combine(outputDirectory, decryptedFile));
        }
Beispiel #14
0
        public void WorkWithSmallFileTest()
        {
            var          testfileRaw                      = Path.Combine(TestContext.CurrentContext.TestDirectory, "Testfiles", "verysmallfile.dat");
            var          testfileDecryptedFile            = Path.Combine(TestContext.CurrentContext.TestDirectory, "Testfiles", "decrypted", "verysmallfile.dat");
            var          testfileDecryptedOutputDirectory = Path.Combine(TestContext.CurrentContext.TestDirectory, "Testfiles", "decrypted");
            const string outputDirectory                  = "Testfiles";
            const long   testfileSizeKb                   = 1024;
            const string privateKey = "31d9040b00a170532929b37db0afcb989e4175f96e5f9667ee8cbf5706679a71";
            const string publicKey  = "6d0deec730700f9f60687a4e6e8755157ca22ea2f3815b9bf14b1fe9ae6a0b4d";
            var          keyPair    = new KeyPair(Utilities.HexToBinary(publicKey), Utilities.HexToBinary(privateKey));

            Console.Write("Generating {0} KB testfile . . .\n", testfileSizeKb);
            var fs = new FileStream(testfileRaw, FileMode.CreateNew);

            fs.Seek((testfileSizeKb * 1024), SeekOrigin.Begin);
            fs.WriteByte(0);
            fs.Close();
            Console.Write("Encrypting testfile . . .\n");
            var encryptedFile = Cryptor.EncryptFileWithStream(keyPair, testfileRaw);

            Console.Write("Decrypting testfile . . .\n");
            Cryptor.DecryptFileWithStream(keyPair, Path.Combine(TestContext.CurrentContext.TestDirectory, outputDirectory, encryptedFile),
                                          testfileDecryptedOutputDirectory);
            Console.Write("Get checksum of testfiles . . .\n");
            Assert.AreEqual(Utils.GetChecksum(testfileRaw), Utils.GetChecksum(testfileDecryptedFile));
            //clear garbage
            File.Delete(testfileRaw);
            File.Delete(Path.Combine(TestContext.CurrentContext.TestDirectory, outputDirectory, encryptedFile));
            File.Delete(testfileDecryptedFile);
        }
Beispiel #15
0
        private void TestCryptor(Cryptor c)
        {
            String cipher = c.encrypt("Password");
            Console.Out.WriteLine(cipher);
            Assert.False(String.IsNullOrEmpty(cipher));

            String clear = c.decrypt(cipher);
            Console.Out.WriteLine(clear);
            Assert.False(String.IsNullOrEmpty(clear));
            Assert.AreEqual(clear, "Password");
        }