private void DistortImage(int height, int width, Bitmap pic)
 {
     using (var copy = (Bitmap)pic.Clone())
     {
         double distort = _randomNumberProvider.Next(1, 6) * (_randomNumberProvider.Next(10) == 1 ? 1 : -1);
         for (int y = 0; y < height; y++)
         {
             for (int x = 0; x < width; x++)
             {
                 // Adds a simple wave
                 int newX = (int)(x + (distort * Math.Sin(Math.PI * y / 84.0)));
                 int newY = (int)(y + (distort * Math.Cos(Math.PI * x / 44.0)));
                 if (newX < 0 || newX >= width)
                 {
                     newX = 0;
                 }
                 if (newY < 0 || newY >= height)
                 {
                     newY = 0;
                 }
                 pic.SetPixel(x, y, copy.GetPixel(newX, newY));
             }
         }
     }
 }
        /// <summary>
        /// Process the taghelper and generate the output.
        /// </summary>
        public void Process(TagHelperContext context, TagHelperOutput output)
        {
            context.CheckArgumentNull(nameof(context));
            output.CheckArgumentNull(nameof(output));

            setUrlHelper();

            output.TagName = "div";
            output.Attributes.Add("class", "dntCaptcha");
            var captchaDivId = $"dntCaptcha{context.UniqueId}{_randomNumberProvider.Next(Min, Max)}";

            output.Attributes.Add("id", captchaDivId);
            output.TagMode = TagMode.StartTagAndEndTag;

            var number        = _randomNumberProvider.Next(Min, Max);
            var randomText    = _humanReadableIntegerProvider.NumberToText(number, Language);
            var encryptedText = _captchaProtectionProvider.Encrypt(randomText);

            var captchaImage = getCaptchaImageTagBuilder(encryptedText);

            output.Content.AppendHtml(captchaImage);

            var cookieToken   = $".{captchaDivId}";
            var refreshButton = getRefreshButtonTagBuilder(captchaDivId, cookieToken);

            output.Content.AppendHtml(refreshButton);

            var hiddenInput = getHiddenInputTagBuilder(encryptedText);

            output.Content.AppendHtml(hiddenInput);

            var textInput = getTextInputTagBuilder();

            output.Content.AppendHtml($"{string.Format(TextBoxTemplate, textInput.GetString())}");

            var validationMessage = getValidationMessageTagBuilder();

            output.Content.AppendHtml(validationMessage);

            var hiddenInputToken = getHiddenInputTokenTagBuilder(_captchaProtectionProvider.Encrypt(cookieToken));

            output.Content.AppendHtml(hiddenInputToken);

            var dataAjaxBeginScript = getOnRefreshButtonDataAjaxBegin();

            output.Content.AppendHtml(dataAjaxBeginScript);

            _captchaStorageProvider.Add(ViewContext.HttpContext, cookieToken, randomText);
        }
 /// <summary>
 /// SumOfTwoNumbersToWords Provider
 /// </summary>
 public SumOfTwoNumbersToWordsProvider(
     IRandomNumberProvider randomNumberProvider,
     HumanReadableIntegerProvider humanReadableIntegerProvider)
 {
     _randomNumber = randomNumberProvider.Next(1, 7);
     _humanReadableIntegerProvider = humanReadableIntegerProvider;
 }
        public async Task SendTemporaryCodeAsync(string subjectId)
        {
            var randomCode = _randomNumberProvider.Next();

            await saveTwoFactorCodeClaimsAsync(subjectId, randomCode);
            await sendCodeToUserAsync(subjectId, randomCode);
        }
        private int GenerateRandomNumber()
        {
            int min = 1000;
            int max = 10000;

            return(_randomNumberProvider.Next(min, max));
        }
Exemple #6
0
        /// <summary>
        /// Process the taghelper and generate the output.
        /// </summary>
        public void Process(TagHelperContext context, TagHelperOutput output)
        {
            context.CheckArgumentNull(nameof(context));
            output.CheckArgumentNull(nameof(output));

            output.TagName = "div";
            output.Attributes.Add("class", "captcha");
            var captchaDivId = $"captcha{context.UniqueId}{_randomNumberProvider.Next(Min, Max)}";

            output.Attributes.Add("id", captchaDivId);
            output.TagMode = TagMode.StartTagAndEndTag;

            var number     = _randomNumberProvider.Next(Min, Max);
            var randomText = "";

            randomText = OutputType == OutputType.InDigits ? DNTPersianUtils.Core.PersianNumbersUtils.ToPersianNumbers(number) : _humanReadableIntegerProvider.NumberToText(number, Language);

            var encryptedText = _captchaProtectionProvider.Encrypt(randomText);

            var captchaImage = GetCaptchaImageTagBuilder(encryptedText);

            output.Content.AppendHtml(captchaImage);

            var cookieToken   = $".{captchaDivId}";
            var refreshButton = GetRefreshButtonTagBuilder(captchaDivId, cookieToken);

            output.Content.AppendHtml(refreshButton);

            var hiddenInput = GetHiddenInputTagBuilder(encryptedText);

            output.Content.AppendHtml(hiddenInput);
            if (!ImageOnly)
            {
                var textInput = GetTextInputTagBuilder();
                output.Content.AppendHtml($"{string.Format(TextBoxTemplate, textInput.GetString())}");
            }

            var validationMessage = GetValidationMessageTagBuilder();

            output.Content.AppendHtml(validationMessage);

            var hiddenInputToken = GetHiddenInputTokenTagBuilder(_captchaProtectionProvider.Encrypt(cookieToken));

            output.Content.AppendHtml(hiddenInputToken);

            _captchaStorageProvider.Add(ViewContext.HttpContext, cookieToken, randomText);
        }
Exemple #7
0
 /// <summary>
 /// The default captcha protection provider
 /// </summary>
 public CaptchaCryptoProvider(
     IOptions <DNTCaptchaOptions> options,
     IRandomNumberProvider randomNumberProvider,
     ILogger <CaptchaCryptoProvider> logger)
 {
     _logger   = logger;
     _keyBytes = getDesKey(options.Value.EncryptionKey, randomNumberProvider.Next().ToString());
 }
Exemple #8
0
        /// <summary>
        /// Creates DNTCaptcha
        /// </summary>
        /// <param name="captchaAttributes">captcha attributes</param>
        public DNTCaptchaApiResponse CreateDNTCaptcha(DNTCaptchaTagHelperHtmlAttributes captchaAttributes)
        {
            var number           = _randomNumberProvider.Next(captchaAttributes.Min, captchaAttributes.Max);
            var randomText       = _captchaTextProvider(captchaAttributes.DisplayMode).GetText(number, captchaAttributes.Language);
            var encryptedText    = _captchaProtectionProvider.Encrypt(randomText);
            var captchaImageUrl  = getCaptchaImageUrl(captchaAttributes, encryptedText);
            var captchaDivId     = $"dntCaptcha{Guid.NewGuid():N}{_randomNumberProvider.Next(captchaAttributes.Min, captchaAttributes.Max)}";
            var cookieToken      = $".{captchaDivId}";
            var hiddenInputToken = _captchaProtectionProvider.Encrypt(cookieToken);

            _captchaStorageProvider.Add(_httpContextAccessor.HttpContext, cookieToken, randomText);

            return(new DNTCaptchaApiResponse
            {
                DntCaptchaImgUrl = captchaImageUrl,
                DntCaptchaId = captchaDivId,
                DntCaptchaTextValue = encryptedText,
                DntCaptchaTokenValue = hiddenInputToken
            });
        }
        public IActionResult CreateDNTCaptcha([FromBody] DNTCaptchaTagHelperHtmlAttributes captchaAttributes)
        {
            var number           = _randomNumberProvider.Next(captchaAttributes.Min, captchaAttributes.Max);
            var randomText       = _humanReadableIntegerProvider.NumberToText(number, captchaAttributes.Language);
            var encryptedText    = _captchaProtectionProvider.Encrypt(randomText);
            var captchaImageUrl  = getCaptchaImageUrl(captchaAttributes, encryptedText);
            var captchaDivId     = $"dntCaptcha{Guid.NewGuid().ToString("N")}{_randomNumberProvider.Next(captchaAttributes.Min, captchaAttributes.Max)}";
            var cookieToken      = $".{captchaDivId}";
            var hiddenInputToken = _captchaProtectionProvider.Encrypt(cookieToken);

            _captchaStorageProvider.Add(HttpContext, cookieToken, randomText);

            return(Json(new
            {
                dntCaptchaImgUrl = captchaImageUrl,
                dntCaptchaId = captchaDivId,
                dntCaptchaTextValue = encryptedText,
                dntCaptchaTokenValue = hiddenInputToken
            }));
        }
Exemple #10
0
        public IList <Product> GetData()
        {
            var productList = new List <Product>();

            for (int i = 0; i < 10; i++)
            {
                productList.Add(new Product {
                    Id = i + 1, Title = $"Product {i + 1}", Price = _random.Next(5000, 100000)
                });
            }

            return(productList);
        }
        public string RandomItem(IEnumerable <string> options)
        {
            List <KeyValuePair <string, int> > validProbabilities;

            lock (_probabilities)
            {
                validProbabilities = _probabilities.Where(kvp => options.Contains(kvp.Key)).ToList();
            }

            var upperBound = validProbabilities
                             .Sum(kvp => kvp.Value);

            var cumulativeProbabilities = validProbabilities.GetCumulativeTotals();

            var number = _random.Next(0, upperBound);

            return(cumulativeProbabilities.SkipWhile(p => number >= p.Value).First().Key);
        }
Exemple #12
0
        public List <AlgorithmPackage> NextPool()
        {
            var poolSize = (int)PoolSizeProvider.Next();
            var result   = new List <AlgorithmPackage>(poolSize);

            while (poolSize > 0)
            {
                var package = new AlgorithmPackage()
                {
                    Id     = ++LastAssignedId,
                    MassKg = MassProvider.Next(),
                    Income = IncomeProvider.Next(),
                    DeadlineInTimeUnits = (int)DeadlineProvider.Next(),
                };

                poolSize--;
                result.Add(package);
            }

            return(result);
        }
Exemple #13
0
 /// <summary>
 /// SumOfTwoNumbers Provider
 /// </summary>
 public SumOfTwoNumbersProvider(IRandomNumberProvider randomNumberProvider)
 {
     _randomNumber = randomNumberProvider.Next(1, 7);
 }
        /// <summary>
        /// Creates the captcha image with noise.
        /// </summary>
        public byte[] DrawCaptcha(string message, float fontSize, string fontName)
        {
            message = message.Replace(",", string.Empty);
            const int margin      = 8;
            var       captchaFont = new Font(fontName, fontSize, FontStyle.Bold, GraphicsUnit.Pixel);
            var       captchaSize = measureString(message, captchaFont);
            var       height      = (int)captchaSize.Height + margin;
            var       width       = (int)captchaSize.Width + margin;

            using (var pic = new Bitmap(width, height, PixelFormat.Format24bppRgb))
            {
                using (var graphics = Graphics.FromImage(pic))
                {
                    using (var backgroundBrush = new System.Drawing.Drawing2D.HatchBrush(System.Drawing.Drawing2D.HatchStyle.SmallCheckerBoard, Color.DimGray, Color.WhiteSmoke))
                        graphics.FillRectangle(backgroundBrush, 0, 0, width, height);

                    var horizontalPosition = 0;
                    var characterSpacing   = (width / message.Length) - 1;
                    foreach (var item in message)
                    {
                        var brush = new SolidBrush(ColorTranslator.FromHtml(colors[_randomNumberProvider.Next(0, colors.Count - 1)]));
                        var maxVerticalPosition = height - Convert.ToInt32(graphics.MeasureString(item.ToString(), captchaFont).Height);
                        graphics.DrawString(item.ToString(), captchaFont, brush, horizontalPosition, _randomNumberProvider.Next(0, maxVerticalPosition));
                        horizontalPosition += characterSpacing + _randomNumberProvider.Next(-1, 1);
                    }

                    for (var i = 0; i < 30; i++)
                    {
                        var start = _randomNumberProvider.Next(1, 4);
                        var brush = new SolidBrush(ColorTranslator.FromHtml(colors[_randomNumberProvider.Next(0, colors.Count - 1)]));
                        graphics.FillEllipse(brush, _randomNumberProvider.Next(start, width), _randomNumberProvider.Next(1, height), _randomNumberProvider.Next(1, 4), _randomNumberProvider.Next(2, 5));

                        var x0 = _randomNumberProvider.Next(0, width);
                        var y0 = _randomNumberProvider.Next(0, height);
                        var x1 = _randomNumberProvider.Next(0, width);
                        var y1 = _randomNumberProvider.Next(0, height);
                        graphics.DrawLine(Pens.Black, x0, y0, x1, x1);
                    }
                }

                using (var stream = new MemoryStream())
                {
                    distortImage(height, width, pic);
                    pic.Save(stream, ImageFormat.Png);
                    return(stream.ToArray());
                }
            }
        }