Пример #1
0
        public ReadPage()
        {
            InitializeComponent();

            try
            {
                var json    = Uri.UnescapeDataString(new Uri(App.UriData).Query.Replace("?data=", string.Empty));
                var message = JsonConvert.DeserializeObject <KriptalMessage>(json);

                var aes = new AesCrypto();
                var rsa = new RsaCrypto();

                var localDataManager = new LocalDataManager(App.Password);
                var privateKey       = localDataManager.GetPrivateKey();

                var textAesKey = rsa.DecryptWithPrivate(message.TextAesKey, privateKey);
                var textAesIv  = rsa.DecryptWithPrivate(message.TextAesIv, privateKey);
                var text       = aes.Decrypt(message.TextData, textAesKey, Convert.FromBase64String(textAesIv));
                MessageText = text;

                if (!string.IsNullOrEmpty(message.BlockchainStampUrl))
                {
                    var blockchainUrl = rsa.DecryptWithPrivate(message.BlockchainStampUrl, privateKey);
                    BlockchainReciptUrl = blockchainUrl;
                }

                if (message.FileName != string.Empty)
                {
                    FileName = rsa.DecryptWithPrivate(message.FileName, privateKey);
                    var fileAesKey = rsa.DecryptWithPrivate(message.FileAesKey, privateKey);
                    var fileAesIv  = rsa.DecryptWithPrivate(message.FileAesIv, privateKey);
                    FileData      = aes.Decrypt(message.FileData, fileAesKey, Convert.FromBase64String(fileAesIv));
                    HasAttachment = true;
                }
                else
                {
                    HasAttachment = false;
                }

                var fromId = rsa.DecryptWithPrivate(message.FromId, privateKey);
                var user   = localDataManager.Get <User>(u => u.Id == fromId);
                UserName = user.Name;

                App.UriData = string.Empty;

                BindingContext = this;
            }
            catch
            {
                DisplayAlert(AppResources.Title, AppResources.CantRead, AppResources.OK);
            }
        }
Пример #2
0
        public static void TestObjectDisposed()
        {
            AesKey key = new AesKey();
            AesIV  iv  = new AesIV();

            AesCrypto crypto = new AesCrypto(key, iv, CipherMode.CBC, PaddingMode.None);

            crypto.Dispose();

            Assert.Throws <ObjectDisposedException>(() =>
            {
                crypto.Decrypt(new byte[16]);
            });

            Assert.Throws <ObjectDisposedException>(() =>
            {
                crypto.Encrypt(new byte[16]);
            });

            Assert.Throws <ObjectDisposedException>(() =>
            {
                crypto.CreateDecryptingTransform();
            });

            Assert.Throws <ObjectDisposedException>(() =>
            {
                crypto.CreateEncryptingTransform();
            });
        }
Пример #3
0
        private async void Open_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                OpenFileDialog ofd = new OpenFileDialog();
                var            p   = await ofd.ShowAsync(this);


                if (p.Length > 0)
                {
                    var pw   = new PasswordWindow();
                    var pass = await pw.ShowDialog <string>(this);

                    var txt = File.ReadAllText(p[0]);

                    string seed;
                    if (pass != null)
                    {
                        seed = AesCrypto.Decrypt(txt, pass);
                    }
                    else
                    {
                        seed = txt;
                    }

                    seedTb.Text = seed;

                    NewAddrWif();
                }
            }
            catch (Exception exception)
            {
            }
        }
Пример #4
0
        private void buttonAesDecrypt_Click(object sender, EventArgs e)
        {
            var crypto = new AesCrypto(this.textAesKey.Text, this.textAesIv.Text);

            this.textAesDecryptedOutput.Text = crypto.Decrypt(this.textAesEncryptedInput.Text);
            Clipboard.SetText(textAesDecryptedOutput.Text);
        }
Пример #5
0
        static void Main(string[] args)
        {
            Console.WriteLine("Testing...");
            string input  = Console.ReadLine();
            string output = AesCrypto.Decrypt(input);

            Console.WriteLine($"Result: {output}");
            Console.ReadLine();
        }
Пример #6
0
        private static string DecryptedCustomVariableValue(CustomVariable customVariable, bool leaveValueEncrypted)
        {
            if (!customVariable.ValueIsEncrypted || leaveValueEncrypted)
            {
                return(customVariable.Value);
            }

            return(AesCrypto.Decrypt(customVariable.Value));
        }
Пример #7
0
        public void Decryption_Test()
        {
            string    testStr   = "TIksnh/5Qf33CzOBvVeiog==";
            AesCrypto encryptor = new AesCrypto {
                KeyPhrase = "dev"
            };

            Console.WriteLine(encryptor.Decrypt(testStr));
        }
Пример #8
0
        public void Decrypt_should_decrypt_cipherText(string cipherText, string key)
        {
            var aesCrypto = new AesCrypto();

            var encodedKey = Encoding.UTF8.GetBytes(Guid.Parse(key).ToString("N"));
            var decrypted  = aesCrypto.Decrypt(cipherText, encodedKey);

            decrypted.Should().NotBeNullOrWhiteSpace();
            decrypted.Should().Be(_plainText);
        }
Пример #9
0
        public void Should_Entrypt_Decrypt()
        {
            var person    = "HassanHashemi";
            var salt      = Encoding.UTF8.GetBytes("*****@*****.**");
            var aes       = new AesCrypto(salt, "pass");
            var encrypted = aes.Encrypt(person);
            var result    = aes.Decrypt(encrypted);

            Assert.True(person == result);
        }
Пример #10
0
        public void TestDecrypt()
        {
            String encryptBody = AesCrypto.Encrypt(body, Key, Iv);
            String decryptBody = AesCrypto.Decrypt(encryptBody, Key, Iv);

            Assert.IsNotNull(decryptBody);
            Assert.IsTrue(decryptBody.Length > 0);
            Console.WriteLine("密文:{0}", encryptBody);
            Console.WriteLine("明文:{0}", decryptBody);
            Assert.IsTrue(decryptBody.Equals(body));
        }
Пример #11
0
        public void TestDecryptNoIv()
        {
            var    key         = AesCrypto.CreateKey();
            String encryptBody = AesCrypto.Encrypt(body, Encoding.UTF8.GetBytes(key));

            Console.WriteLine("密文:{0}", encryptBody);

            String decryptBody = AesCrypto.Decrypt(encryptBody, Encoding.UTF8.GetBytes(key));

            Assert.IsNotNull(decryptBody);
            Assert.IsTrue(decryptBody.Length > 0);
            Console.WriteLine("明文:{0}", decryptBody);
            Assert.IsTrue(decryptBody.Equals(body));
        }
Пример #12
0
        public void Encrypt_should_encrypt_plainText()
        {
            var aesCrypto = new AesCrypto();

            var key       = Encoding.UTF8.GetBytes(Guid.NewGuid().ToString("N"));
            var encrypted = aesCrypto.Encrypt(_plainText, key);

            encrypted.Should().NotBeNullOrWhiteSpace();
            encrypted.Should().NotBe(_plainText);


            var decrypted = aesCrypto.Decrypt(encrypted, key);

            decrypted.Should().NotBeNullOrWhiteSpace();
            decrypted.Should().Be(_plainText);
        }
Пример #13
0
        private static void InitializeAllowedRoles()
        {
            AllowedRoles = new List <string>();

            // It's possible that security hasn't been set up yet, so no AdInfo will exist. Set all roles to allowed.
            if (AdInfo == null || AdInfo.SecurityEnabled == false)
            {
                foreach (var groupWithRoles in AdGroupRolesList)
                {
                    groupWithRoles.PrestoRoles.ForEach(x => AllowedRoles.Add(x.ToString()));
                    UserIsPrestoAdmin = true;
                }
                return;
            }

            string domainConnection = string.Format(CultureInfo.InvariantCulture, "{0}.{1}:{2}", AdInfo.Domain, AdInfo.DomainSuffix, AdInfo.DomainPort);
            string container        = string.Format(CultureInfo.InvariantCulture, "dc={0},dc={1}", AdInfo.Domain, AdInfo.DomainSuffix);
            string adQueryUser      = AdInfo.ActiveDirectoryAccountUser;
            string adQueryPassword  = AesCrypto.Decrypt(AdInfo.ActiveDirectoryAccountPassword);

            using (var principalContext = new PrincipalContext(ContextType.Domain, domainConnection, container, adQueryUser, adQueryPassword))
                using (var userPrincipal = UserPrincipal.FindByIdentity(principalContext, IdentityType.SamAccountName, PrestoUser.Identity.Name))
                {
                    foreach (var groupWithRoles in AdGroupRolesList)
                    {
                        if (!userPrincipal.IsMemberOf(principalContext, IdentityType.SamAccountName, groupWithRoles.AdGroupName))
                        {
                            continue;
                        }

                        // If we reach here, the user is in the group passed into this method.

                        groupWithRoles.PrestoRoles.ForEach(x => AllowedRoles.Add(x.ToString()));

                        if (groupWithRoles.PrestoRoles.Exists(r => r == PrestoRole.Admin))
                        {
                            UserIsPrestoAdmin = true;
                        }
                    }
                }
        }
Пример #14
0
        private void btn_Decrypt_Click(object sender, EventArgs e)
        {
            String key  = textBox_Key.Text.Trim(),
                   iv   = textBox_IV.Text.Trim(),
                   body = textBox_Body.Text.Trim();

            if (String.IsNullOrEmpty(key))
            {
                MessageBox.Show("秘钥不能为空!", "温馨提示");
                return;
            }

            if (String.IsNullOrEmpty(iv) && isIvEncrypt())
            {
                MessageBox.Show("偏移量不能为空!", "温馨提示");
                return;
            }


            if (String.IsNullOrEmpty(body))
            {
                MessageBox.Show("待处理文本不能为空!", "温馨提示");
                return;
            }

            try
            {
                var    keyValue = KeyToBytes();
                byte[] bytes    = CiphertextsToBytes();
                textBox_Result.Text = Encoding.UTF8.GetString(AesCrypto.Decrypt(bytes, keyValue.Key, keyValue.Value));
            }
            catch (Exception ex)
            {
                MessageBox.Show("解密失败:" + ex.Message, "错误");
            }
        }
Пример #15
0
        public static void TestObjectDisposed()
        {
            AesKey key = new AesKey();
            AesIV iv = new AesIV();

            AesCrypto crypto = new AesCrypto(key, iv, CipherMode.CBC, PaddingMode.None);
            crypto.Dispose();

            Assert.Throws<ObjectDisposedException>(() =>
            {
                crypto.Decrypt(new byte[16]);
            });

            Assert.Throws<ObjectDisposedException>(() =>
            {
                crypto.Encrypt(new byte[16]);
            });

            Assert.Throws<ObjectDisposedException>(() =>
            {
                crypto.CreateDecryptingTransform();
            });

            Assert.Throws<ObjectDisposedException>(() =>
            {
                crypto.CreateEncryptingTransform();
            });
        }
Пример #16
0
 public string DeAes(string data)
 {
     return(AesCrypto.Decrypt(data, appAesKey, appAesIV));
 }
Пример #17
0
        static void Main(string[] args)
        {
            if (args.Length < 2)
            {
                Console.WriteLine("Usage: ue.exe <grpc|http|sql|mongodb|dns|tcp|udp> <service-idenitifier> [dns-type]");
                Console.WriteLine("       OR");
                Console.WriteLine("       ue.exe <enc|dec> <string> [pepper]");
                return;
            }

            try
            {
                Console.WriteLine("Service Domain = '{0}'", _generic.ServiceDomain);

                switch (args[0].ToLowerInvariant())
                {
                case "enc":
                case "dec":
                    var aes = new AesCrypto();
                    if (args.Length > 2)
                    {
                        aes.KeyPhrase = args[2];
                    }
                    Console.WriteLine("Pepper = '{0}'", aes.KeyPhrase);
                    if (args[0].ToLowerInvariant() == "enc")
                    {
                        Console.WriteLine("\nEncrypted = \"{aes:" + aes.Encrypt(args[1]) + "}\"");
                    }
                    else
                    {
                        string cipherText = args[1].Replace("{aes:", "").Replace("}", "");
                        Console.WriteLine("\nDecrypted = \"" + aes.Decrypt(cipherText) + "\"");
                    }

                    break;

                case "dns":
                    if (Enum.TryParse(args[2], out DnsRecordType recordType))
                    {
                        var        query   = new DnsQuery(args[1], recordType);
                        DnsEntry[] records = query.Resolve().Result;

                        foreach (DnsEntry rec in query.AllRecords)
                        {
                            Console.WriteLine($"({rec.Type}) {rec}");
                        }
                    }
                    break;

                case "grpc":
                    var g = _grpc.Locate(args[1]).Result;
                    foreach (GrpcEndpoint ep in g.Endpoints)
                    {
                        Console.WriteLine(ep.ToString());
                    }
                    break;

                case "http":
                    var w = _webapi.Locate(args[1]).Result;
                    foreach (Uri u in w.Uris)
                    {
                        Console.WriteLine(u.ToString());
                    }
                    break;

                case "sql":
                    var sql = _database.Locate(args[1], DatabaseProtocol.Sql).Result;
                    foreach (string sqlConnectionString in sql.ConnectionStrings)
                    {
                        Console.WriteLine(sqlConnectionString);
                    }
                    break;

                case "mongodb":
                    var mongo = _database.Locate(args[1], DatabaseProtocol.MongoDb).Result;
                    foreach (string mConnectionString in mongo.ConnectionStrings)
                    {
                        Console.WriteLine(mConnectionString);
                    }
                    break;

                case "tcp":
                    var tcp = _generic.Locate(args[1], IpProtocol.TCP).Result;
                    foreach (ServiceEndpoint ep in tcp.Endpoints)
                    {
                        Console.WriteLine(ep.ToString());
                    }
                    break;

                case "udp":
                    var udp = _generic.Locate(args[1], IpProtocol.UDP).Result;
                    foreach (ServiceEndpoint ep in udp.Endpoints)
                    {
                        Console.WriteLine(ep.ToString());
                    }
                    break;

                case "long-test":
                    LongTest.RunTest(args[1]);
                    break;
                }
            }
            catch (Exception ex)
            {
                BreakdownExcception(ex);
            }
        }
Пример #18
0
        // Kinda poor decision on decryption. Ideally some sort of check should be done to ensure that
        // this user has the rights to see decrypted passwords.
        // But if memory serves NOBODY except the end user should now the true password.
        // Needs clarification
        public void DisplayUserInfo(User user, bool truePassword = false)
        {
            string passwordToDisplay = truePassword ? AesCrypto.Decrypt(user._password) : user._password;

            Console.WriteLine($"User name - {user._userName}, user password - {passwordToDisplay}");
        }
Пример #19
0
        public TideResponse Login(AuthenticationModel model)
        {
            try {
                // Fetch the item from the cache, otherwise get it from the blockchain
                var fragment = _repo.GetShare(model.Username.ConvertToUint64());
                if (fragment == null)
                {
                    _logger.LogMsg("Invalid user gathering fragment", model);
                    return(new TideResponse(false, null, "That fragment does not exist"));
                }

                // Process the request. Gather correct fragment if the password checks out, otherwise return junk data
                // Alternatively reject it if too many requests have been made
                var(result, minutes) = Throttle(model.Ip);
                if (result)
                {
                    _logger.LogMsg("TideUser hit throttle", model);
                    return(new TideResponse(false, null, $"Too many requests. Try again in: {minutes} minutes."));
                }
                var validationResult = ValidationManager.ValidatePass(model.PasswordHash, AesCrypto.Decrypt(fragment.PasswordHash, _settings.Password), AesCrypto.Decrypt(fragment.CvkFragment, _settings.Password), _settings.Key).Result;

                // Convert to a transfer object
                var dto = new FragmentDto(fragment)
                {
                    CvkFragment = Cryptide.Instance.Encrypt(validationResult.Result, model.PublicKey)
                };

                _logger.LogMsg(validationResult.Success ? "Correct Fragment retrieved" : "Junk fragment retrieved", model);

                return(new TideResponse(true, new { vendorFragment = dto }, null));
            }
            catch (Exception e) {
                _logger.LogMsg("Error gathering fragment", model, e);
                return(new TideResponse(false, null, "Unable to gather fragment"));
            }
        }
Пример #20
0
        // This function runs on the ORK on every authentication request
        // epIP is the end-point IP/port address of the requester
        // Function returns the amount of minutes that requester is blocked from now - if the request failed. 0 is if the request is approved.
        private (bool success, string result, int minutes) ProcessRequest(AuthenticationModel model, Fragment fragment)
        {
            // initialize local variables
            string returnedValue = null;

            // check for current epoch time
            var epoch = (DateTime.UtcNow - _epoch).TotalSeconds;

            CleanDictionary(epoch);

            // check if record exists for that end-point
            if (!Records.ContainsKey(model.Ip))
            {
                Records.Add(model.Ip, new Tuple <int, double>(1, epoch - 1));
            }

            var(item1, item2) = Records[model.Ip];

            ValidationResult validationResult = null;
            var success = false;

            // execute the authentication check only if ban expired or if still in the first 3 bans
            if (item1 < 4 || epoch > item2)
            {
                validationResult = ValidationManager.ValidatePass(model.PasswordHash, AesCrypto.Decrypt(fragment.PasswordHash, _settings.Password), AesCrypto.Decrypt(fragment.CvkFragment, _settings.Password), _settings.Key).Result;
                returnedValue    = validationResult.Result;
                success          = validationResult.Success;
            }

            var result = 0;

            if (validationResult != null && validationResult.Success)
            {
                // if authentication confirmed, reset record
                Records[model.Ip] = new Tuple <int, double>(1, epoch - 1);
            }
            else
            {
                // increase ban exponentially
                result = (int)Math.Pow(2, item1 - 3);

                // if authentication failed:
                // increase Attempts counter for that record
                var additionalTime = epoch + 60 * result;
                Records[model.Ip] = new Tuple <int, double>(item1 + 1, additionalTime);
            }

            // return result
            return(success, returnedValue, result);
        }
Пример #21
0
 public static string DeCrypt(this string text) => AesCrypto.Decrypt(text);