private static IEnumerable <IEnumerable <byte> > DecryptInternal(ICrypter crypter, IEnumerable <byte> source, byte[] initializingVector)
        {
            foreach (var block in source.Batch(crypter.BlockSize))
            {
                var blockArray    = block.ToArray();
                var decryptOutput = crypter.Decrypt(blockArray);
                var decrypt       = decryptOutput.Xor(initializingVector);
                yield return(decrypt);

                initializingVector = blockArray.Xor(decrypt);
            }
        }
Example #2
0
 private void DecryptButton_Click(object sender, EventArgs e)
 {
     InputText.Text = _crypter.Decrypt(
         EncryptedText.Text,
         new ComplexKey
     {
         Key        = secretKey,
         Encrypting = false
     },
         _language
         );
 }
 private void p_OnMessageSend(P2PClient sender, ulong userId, Memory <byte> msg)
 {
     if (crypter.IsConnectionSafe(userId, msg))
     {
         Memory <byte> deMsg = crypter.Decrypt(userId, msg);
         if (deMsg.Length > 0)
         {
             dynamic json = JsonConvert.DeserializeObject(Encoding.UTF8.GetString(deMsg.Span));
             messages.Push(new PackageInfo(json, userId));
             OnMessageSend?.Invoke(this, userId, messages.Peek());
         }
     }
 }
Example #4
0
        private object ReadNonCached(Type baseType, string path, object defaultValue, bool decrypt)
        {
            string rawValue = ReadFirstValue(path);

            if (decrypt)
            {
                if (_crypter == null)
                {
                    throw new InvalidOperationException($"path: {path} has encryption specified but no encryption provider");
                }
                rawValue = _crypter.Decrypt(rawValue);
            }

            return(_valueHandler.ParseValue(baseType, rawValue, defaultValue));
        }
Example #5
0
 private void ChangeLetterButton_Click(object sender, EventArgs e)
 {
     try
     {
         EncryptedText.Text = _crypter.Decrypt(EncryptedText.Text,
                                               new ComplexKey
         {
             OriginalLetter = Convert.ToChar(originalLetterTextBox.Text),
             TargetLetter   = Convert.ToChar(targetLetterTextBox.Text)
         },
                                               _language);
     }
     catch (ArgumentException ex)
     {
         MessageBox.Show(ex.Message);
     }
 }
Example #6
0
        public void Extract()
        {
            //long sizeDestInBlocks = ((unpackedData.Length - 1) / BlockSize) + 1;
            //SizeDestInBlocks = sizeDestInBlocks;

            if (_crypter != null)
            {
                _crypter.Decrypt(containerData);
            }
            containerData.Position = 0;
            unpackedData.Position  = 0;
            byte[] sizeVariable = new byte[8];
            containerData.Read(sizeVariable, 0, 8);
            long unpackedDataSize = ArrayToLong(sizeVariable);

            for (long i = 0; i < unpackedDataSize; i++)
            {
                int buf = containerData.ReadByte();

                unpackedData.WriteByte((byte)buf);
            }
        }
        /// <summary>Creates the HTTP client.</summary>
        /// <param name="domain">The domain.</param>
        /// <param name="login">The login.</param>
        /// <param name="cryptedPassword">The crypted password.</param>
        /// <returns>The <see cref="HttpClient"/>.</returns>
        public static HttpClient CreateHttpClient(string domain, string login, string cryptedPassword)
        {
            var handler = new HttpClientHandler();

            // on premise TFS authentication
            if (!string.IsNullOrEmpty(login))
            {
                handler.Credentials = new NetworkCredential(login, Crypter.Decrypt(cryptedPassword), domain);
            }

            var client = new HttpClient(handler)
            {
                Timeout = TimeSpan.FromSeconds(15)
            };

            // VSTS authentication with personal access token
            if (string.IsNullOrEmpty(login))
            {
                var authorization = Convert.ToBase64String(Encoding.ASCII.GetBytes(string.Format(":{0}", Crypter.Decrypt(cryptedPassword))));
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", authorization);
            }

            return(client);
        }
        public async Task Invoke(HttpContext context)
        {
            if (context.Request.Headers.ContainsKey("Authorization"))
            {
                string[] values = context.Request.Headers["Authorization"].ToString().Split(' ');

                if (values.Length != 2)
                {
                    context.Response.StatusCode  = StatusCodes.Status400BadRequest;
                    context.Response.ContentType = "application/json;charset=utf-8";
                    await context.Response.WriteAsync($"[\"{ResourceServerMessages.InvalidAuthorizationHeader}\"]");

                    return;
                }

                if (values.First() != "Bearer")
                {
                    context.Response.StatusCode  = StatusCodes.Status400BadRequest;
                    context.Response.ContentType = "application/json;charset=utf-8";
                    await context.Response.WriteAsync($"[\"{ResourceServerMessages.AuthorizationBearerRequired}\"]");

                    return;
                }

                try
                {
                    string   webTokenJsonString = _crypter.Decrypt(values[1], _resourceServerOptions.CryptionKey);
                    WebToken webToken           = JsonConvert.DeserializeObject <WebToken>(webTokenJsonString);

                    if (webToken.Issuer != _resourceServerOptions.Issuer)
                    {
                        context.Response.StatusCode  = StatusCodes.Status401Unauthorized;
                        context.Response.ContentType = "application/json;charset=utf-8";
                        await context.Response.WriteAsync($"[\"{ResourceServerMessages.IssuersDoNotMatch}\"]");

                        return;
                    }

                    DateTime tokenExpiration = webToken.CreatedDate.AddDays(_resourceServerOptions?.TokenDurationInDays ?? 14);

                    if (DateTime.Now > tokenExpiration)
                    {
                        context.Response.StatusCode  = StatusCodes.Status401Unauthorized;
                        context.Response.ContentType = "application/json;charset=utf-8";
                        await context.Response.WriteAsync($"[\"{ResourceServerMessages.TokenExpired}\"]");

                        return;
                    }

                    // Now, we have to write the claims to the ClaimsPrincipal!
                    context.User = webToken.ConvertToClaimsPrincipal();
                }
                catch (Exception e)
                {
                    context.Response.StatusCode  = StatusCodes.Status401Unauthorized;
                    context.Response.ContentType = "application/json;charset=utf-8";
                    await context.Response.WriteAsync($"[\"{e.Message}\"]");
                }
            }

            await _next.Invoke(context);
        }
        public async Task <string> ProcessAsync(DiscordMessage message)
        {
            if (_expletiveCommandText.Length + 2 > message.Content.Length)
            {
                return("Are you stupid?");
            }
            string nonCommand = message.Content.Substring(_expletiveCommandText.Length + 2);

            string[] words       = nonCommand.Split(' ');
            string[] subCommands = { "add", "confirm", "delete", "status" };
            if (IsMention(words[0]))
            {
                if (words.Length > 1)
                {
                    return("What are you doing?");
                }
                else
                {
                    if (_lastUseTime.Keys.Contains(message.Author.Id))
                    {
                        var diff    = DateTime.UtcNow - _lastUseTime[message.Author.Id];
                        int seconds = (int)Math.Ceiling(diff.TotalSeconds);
                        if (seconds < _timeLimitSecs)
                        {
                            return($"{message.Author.Mention} You can abuse again in {_timeLimitSecs - seconds} seconds.");
                        }
                    }
                    _lastUseTime[message.Author.Id] = DateTime.UtcNow;
                    return(GetRandomAbuse(message.MentionedUsers.First().Id));
                }
            }
            else
            {
                switch (words[0].ToLowerInvariant())
                {
                case "add":
                    await message.DeleteAsync();

                    if (UserAlreadyProcessing(message.Author.Id))
                    {
                        return("You cannot submit another expletive until your first one is processed.");
                    }
                    if (words.Where(x => x.IndexOf(":user:"******"There must be a `:user:` mentioned in the abuse.");
                    }
                    string encryptedExpletive = _crypter.Encrypt(string.Join(' ', words.Skip(1)));
                    string toStore            = $"{message.Author.Id}|{encryptedExpletive}";
                    FileOperations.AppendLine(ExpletiveConfig.UnconfiremedExpletivesFile, toStore);
                    return($"{message.Author.Mention}, your abuse has been submitted for processing.");

                case "status":
                    DiscordMember messageAuthor = IsMemberAuthorized(message.Author.Id, _members);
                    if (messageAuthor == null)
                    {
                        return("You are not authorized to use this command.");
                    }
                    using (StreamReader reader = new StreamReader(ExpletiveConfig.UnconfiremedExpletivesFile))
                    {
                        string line = null;
                        await messageAuthor.SendMessageAsync("Vote Status:");

                        while ((line = reader.ReadLine()) != null)
                        {
                            var    splitLine  = line.Split('|');
                            string actualLine = $"{GetNameFromId(splitLine[0], _members)} - {_crypter.Decrypt(splitLine[1])}";
                            await messageAuthor.SendMessageAsync(actualLine);
                        }
                    }
                    return("Status sent.");

                case "approve":
                    messageAuthor = IsMemberAuthorized(message.Author.Id, _members);
                    if (messageAuthor == null)
                    {
                        return("You are not authorized to use this command.");
                    }
                    if (words.Length != 2)
                    {
                        return("Usage: `approve @user`");
                    }
                    var    approvedUser = message.MentionedUsers.First();
                    int    lineNo       = -1;
                    string expletive    = null;
                    string submitter    = null;
                    using (StreamReader reader = new StreamReader(ExpletiveConfig.UnconfiremedExpletivesFile))
                    {
                        string line = null;
                        for (int i = 0; (line = reader.ReadLine()) != null; i++)
                        {
                            words = line.Split('|');
                            if (words[0].Equals(approvedUser.Id.ToString()))
                            {
                                lineNo    = i;
                                expletive = words[1];
                                submitter = words[0];
                                break;
                            }
                        }
                    }
                    if (lineNo < 0)
                    {
                        return("Submission not found for the user.");
                    }
                    FileOperations.AppendLine(ExpletiveConfig.StoredExpletivesFile, expletive);
                    FileOperations.DeleteLine(ExpletiveConfig.UnconfiremedExpletivesFile, lineNo);
                    return($"<@{submitter}>, your abuse has been approved.");

                case "reject":
                    messageAuthor = IsMemberAuthorized(message.Author.Id, _members);
                    if (messageAuthor == null)
                    {
                        return("You are not authorized to use this command.");
                    }
                    if (words.Length != 2)
                    {
                        return("Usage: `reject @user`");
                    }
                    approvedUser = message.MentionedUsers.First();
                    lineNo       = -1;
                    expletive    = null;
                    submitter    = null;
                    using (StreamReader reader = new StreamReader(ExpletiveConfig.UnconfiremedExpletivesFile))
                    {
                        string line = null;
                        for (int i = 0; (line = reader.ReadLine()) != null; i++)
                        {
                            words = line.Split('|');
                            if (words[0].Equals(approvedUser.Id.ToString()))
                            {
                                lineNo    = i;
                                expletive = line.Split('|')[1];
                                submitter = line.Split('|')[0];
                                break;
                            }
                        }
                    }
                    if (lineNo < 0)
                    {
                        return("Submission not found for the user.");
                    }
                    FileOperations.DeleteLine(ExpletiveConfig.UnconfiremedExpletivesFile, lineNo);
                    return($"<@{submitter}>, your abuse has been rejected.");
                }
            }
            return(string.Empty);
        }
Example #10
0
        public static WebToken DecryptToken(string tokenString, ICrypter crypter, string key)
        {
            string jsonString = crypter.Decrypt(tokenString, key);

            return(JsonConvert.DeserializeObject <WebToken>(jsonString));
        }
Example #11
0
 private void DecryptButton_Click(object sender, EventArgs e)
 {
     InputText.Text = _crypter.Decrypt(EncryptedText.Text, secretKey, _language);
 }