private async Task <CaptchaResponse> Solve(CaptchaService service, CaptchaType captchaType) { var proxy = MakeProxy(Proxy, ProxyType); switch (captchaType) { case CaptchaType.TextCaptcha: var textOptions = new TextCaptchaOptions() { CaptchaLanguageGroup = CaptchaLanguageGroup, CaptchaLanguage = CaptchaLanguage }; return(await service.SolveTextCaptchaAsync(Text, textOptions)); case CaptchaType.ImageCaptcha: if (CaptchaImage == null) { throw new ArgumentNullException("You must download an image first!"); } var imageOptions = new ImageCaptchaOptions() { IsPhrase = IsPhrase, CaseSensitive = CaseSensitive, CharacterSet = CharacterSet, RequiresCalculation = RequiresCalculation, MinLength = int.Parse(MinLength), MaxLength = int.Parse(MaxLength), CaptchaLanguageGroup = CaptchaLanguageGroup, CaptchaLanguage = CaptchaLanguage, TextInstructions = TextInstructions }; return(await service.SolveImageCaptchaAsync(CaptchaImage.ToBase64(ImageFormat.Jpeg), imageOptions)); case CaptchaType.ReCaptchaV2: return(await service.SolveRecaptchaV2Async(SiteKey, SiteUrl, SData, Enterprise, Invisible, proxy)); case CaptchaType.ReCaptchaV3: return(await service.SolveRecaptchaV3Async(SiteKey, SiteUrl, Action, float.Parse(MinScore, CultureInfo.InvariantCulture), Enterprise, proxy)); case CaptchaType.FunCaptcha: return(await service.SolveFuncaptchaAsync(PublicKey, ServiceUrl, SiteUrl, NoJS, proxy)); case CaptchaType.HCaptcha: return(await service.SolveHCaptchaAsync(SiteKey, SiteUrl, proxy)); case CaptchaType.KeyCaptcha: return(await service.SolveKeyCaptchaAsync(UserId, SessionId, WebServerSign1, WebServerSign2, SiteUrl, proxy)); case CaptchaType.GeeTest: return(await service.SolveGeeTestAsync(GT, Challenge, ApiServer, SiteUrl, proxy)); case CaptchaType.Capy: return(await service.SolveCapyAsync(SiteKey, SiteUrl, proxy)); } throw new NotSupportedException($"Captcha type {captchaType} is not supported by the tester yet!"); }
public void Execute(CaptchaType captchaType, int?width = default(int?), int?height = default(int?)) { Content.LoadAsync(delegate(string path, GameObject prefab) { onCaptchaUILoaded(prefab, captchaType, width, height); }, captchaUIContentKey); }
/// <summary> /// 检查图形验证码功能 /// </summary> /// <param name="type">图形验证码的类型</param> /// <param name="code">待验证的code</param> protected async Task <bool> VerifyImgCodeAsync(CaptchaType type, string code) { if (string.IsNullOrWhiteSpace(code)) { throw new UserFriendlyException("验证码不能为空!"); } //租户Id var tenantId = AbpSession.TenantId; // 分租户获取缓存 var cacheKey = CaptchaHelper.CreateCacheKey(type, tenantId); //图形验证码缓存管理器 var captchaCacheManager = CacheManager.GetCache(cacheKey); var sessionId = HttpContext.Request.Cookies[cacheKey]; //获取缓存中的值 var cacheCode = await captchaCacheManager.GetOrDefaultAsync(sessionId); if (cacheCode != null && code == cacheCode.ToString()) { await captchaCacheManager.RemoveAsync(sessionId); return(true); } await captchaCacheManager.RemoveAsync(sessionId); throw new UserFriendlyException("验证码错误!"); }
private void onCaptchaUILoaded(GameObject captchaPrefab, CaptchaType captchaType, int?width = default(int?), int?height = default(int?)) { GameObject gameObject = Object.Instantiate(captchaPrefab); CaptchaController component = gameObject.GetComponent <CaptchaController>(); component.SetupCaptcha(captchaType, width, height); }
public CaptchaLogInfo(CaptchaType t, SocketGuildUser user, string code, string given = null, int attempts = 0) { this.t = t; this.user = user; this.code = code; this.given = given; this.attempts = attempts; }
public void PostCaptchaSolution(CaptchaType type, CaptchaSolution solution) { APICall <PostCaptchaSolutionOperation> aPICall = clubPenguinClient.CaptchaApi.PostCaptchaSolution(type, solution); aPICall.OnResponse += onPostCaptchaSolutionSuccess; aPICall.OnError += onPostCaptchaSolutionFailed; aPICall.Execute(); }
public void GetCaptcha(CaptchaType type, int?width = default(int?), int?height = default(int?)) { APICall <GetCaptchaOperation> captcha = clubPenguinClient.CaptchaApi.GetCaptcha(type, width, height); captcha.OnResponse += onGetCaptcha; captcha.OnError += handleCPResponseError; captcha.Execute(); }
public static async Task SendToCaptchaLogAsync(CaptchaType t, SocketGuildUser user, string code, string given = null, int attempts = 0) { CaptchaLogInfo info = new(t, user, code, given, attempts); CAPTCHATypeSwitch(ref info); await SendToCaptchaLogAsync(info); }
public ActionResult CheckCodeImage(string captcha, CaptchaType type) { var pass = this.CheckImageCode(captcha, type); if (pass) return Json(new { valid = true }); else return Json(new { Valid = false, message = "验证码错误" }); }
public ActionResult CheckCodeImage(CaptchaType type) { var captchaCode = new CheckCode(); var code = captchaCode.GetRandomString(4); var imgBytes = captchaCode.CreateImage(code); var key = "CaptchaCode" + type.ToString(); Session[key] = code; return File(imgBytes, @"image/jpeg"); }
private async Task <CaptchaResponse> TryGetResult (NameValueCollection response, CaptchaType type, CancellationToken cancellationToken = default) { if (IsError(response)) { throw new TaskCreationException(GetErrorMessage(response)); } var task = new CaptchaTask(response["captcha"], type); return(await TryGetResult(task, cancellationToken).ConfigureAwait(false)); }
public CaptchaInfo NewCaptcha(CaptchaType captchaType) { var captchaBitmap = new Bitmap(_captchaInitializer.BackroundImage); var graphic = Graphics.FromImage(captchaBitmap); graphic.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias; int charXPosition = 50; string randomFirstString = GenerateRandomString(captchaType, _captchaInitializer.CaptchaLength); string randomSecondString = GenerateRandomString(captchaType, _captchaInitializer.CaptchaLength); for (int charIndex = 0; charIndex < _captchaInitializer.CaptchaLength; charIndex++) { // Draw first string string firstCharStr = randomFirstString[charIndex].ToString(CultureInfo.InvariantCulture); DrawCharOnGraphic(new CharOnGraphicInfo { Graphic = graphic, Char = firstCharStr, CharXPos = charXPosition, CharYPos = 20, CharMaxRotateDegree = -50, CharMinRotateDegree = 50, Color = _captchaInitializer.FirstCaptchaFontColor }); // Draw second string if (captchaType == CaptchaType.CtDifficult) { string secondCharStr = randomSecondString[charIndex].ToString(CultureInfo.InvariantCulture); DrawCharOnGraphic(new CharOnGraphicInfo { Graphic = graphic, Char = secondCharStr, CharXPos = charXPosition, CharYPos = 50, CharMaxRotateDegree = -90, CharMinRotateDegree = 90, Color = _captchaInitializer.SecondCaptchaFontColor }); } charXPosition += 40; } // Convert generated captcha image to byte array return new CaptchaInfo { CaptchaImage = captchaBitmap, FirstCaptcha = randomFirstString.ToLower(), SecondCaptcha = randomSecondString.ToLower() }; }
private async Task <CaptchaResponse> TryGetResult (TaskCreationResponse response, CaptchaType type, CancellationToken cancellationToken = default) { if (response.IsError) { throw new TaskCreationException($"{response.ErrorCode}: {response.ErrorDescription}"); } var task = new CaptchaTask(response.TaskId, type); return(await TryGetResult(task, cancellationToken).ConfigureAwait(false)); }
private async Task <CaptchaResponse> TryGetResult (string response, CaptchaType type, CancellationToken cancellationToken = default) { if (IsError(response)) { throw new TaskCreationException(response); } var task = new CaptchaTask(response, type); return(await TryGetResult(task, cancellationToken).ConfigureAwait(false)); }
internal async Task <CaptchaResponse> TryGetResult (Response response, CaptchaType type, CancellationToken cancellationToken = default) { if (response.IsErrorCode) { throw new TaskCreationException(response.Request); } var task = new CaptchaTask(response.Request, type); return(await TryGetResult(task, cancellationToken).ConfigureAwait(false)); }
public RecaptchaHtmlHelper(string publicKey, string hl, CaptchaTheme theme, CaptchaType type, string callback, string expiredCallback) { PublicKey = RecaptchaKeyHelper.ParseKey(publicKey); Hl = hl; Theme = theme; Type = type; Callback = callback; ExpiredCallback = expiredCallback; if (string.IsNullOrEmpty(publicKey)) { throw new InvalidOperationException("Public key cannot be null or empty."); } }
public APICall <GetCaptchaOperation> GetCaptcha(CaptchaType type, int?width, int?height) { GetCaptchaOperation getCaptchaOperation = new GetCaptchaOperation(type); if (width.HasValue) { getCaptchaOperation.Width = width; } if (height.HasValue) { getCaptchaOperation.Height = height; } return(new APICall <GetCaptchaOperation>(clubPenguinClient, getCaptchaOperation)); }
/// <summary> /// 创建验证码缓存Key /// </summary> /// <param name="type">验证码类型</param> /// <param name="tenantId">租户id(可空)</param> /// <returns>缓存Key</returns> public static string CreateCacheKey(CaptchaType type, int?tenantId = null) { var res = tenantId.HasValue ? $"T:{tenantId.Value}" : null; switch (type) { case CaptchaType.HostTenantRegister: res = HostCacheKeys.TenantRegistrationCaptchaCache; break; case CaptchaType.HostUserLogin: res = HostCacheKeys.HostUserLoginCaptchaCache; break; case CaptchaType.Defulat: res = $"T:{res}-{HostCacheKeys.Default}"; break; case CaptchaType.TenantUserRegister: res = $"T:{res}-{TenantCacheKeys.UserRegistrationCaptchaCache}"; break; case CaptchaType.TenantUserLogin: res = $"T:{res}-{TenantCacheKeys.UserLoginCaptchaCache}"; break; case CaptchaType.TenantUserRegisterActiveEmail: res = $"T:{res}-{TenantCacheKeys.TenantUserRegisterActiveEmail}"; break; case CaptchaType.TenantUserForotPassword: res = $"T:{res}-{TenantCacheKeys.TenantUserForotPassword}"; break; case CaptchaType.TenantUserResetPassword: res = $"T:{res}-{TenantCacheKeys.TenantUserResetPassword}"; break; default: throw new UserFriendlyException("创建验证码CacheKey错误!验证码类型正确"); } return(res); }
/// <inheritdoc/> public async override Task ReportSolution (long id, CaptchaType type, bool correct = false, CancellationToken cancellationToken = default) { (int major, int minor) = LongToInts(id); await httpClient.PostMultipartToStringAsync("", GetAuthPair() .Add("function", "picture_bad2") .Add("major_id", major) .Add("minor_id", minor) .ToMultipartFormDataContent(), cancellationToken) .ConfigureAwait(false); // TODO: Find a way to check if the api accepted the report or not }
/// <summary> /// 获取指定长度的验证码图片 /// </summary> /// <param name="length">长度</param> /// <param name="code">验证码</param> /// <param name="captchaType">验证码类型</param> public Bitmap CreateImage(int length, out string code, CaptchaType captchaType = CaptchaType.NumberAndLetter) { if (length <= 0) { throw new ArgumentOutOfRangeException(nameof(length)); } length = length < 1 ? 1 : length; code = GetCode(length, captchaType); if (code.Length > length) { code = code.Substring(0, length); } return(CreateImage(code)); }
/// <summary> /// Session 校验验证码,不正确将抛出异常 /// </summary> /// <param name="type"></param> /// <param name="code"></param> protected void ValuedationCode(CaptchaType type, string code) { var key = type.ToString(); var value = HttpContext.Session.GetString(key); if (value.IsNullOrWhiteSpace()) { throw new UserFriendlyException("验证码不能为空!"); } if (value != code?.ToLower()) { throw new UserFriendlyException("验证码错误!"); } HttpContext.Session.Remove(key); }
/// <summary> /// 获取指定长度的验证码字符串 /// </summary> /// <param name="length">长度</param> /// <param name="captchaType">验证码类型</param> public string GetCode(int length, CaptchaType captchaType = CaptchaType.NumberAndLetter) { if (length <= 0) { throw new ArgumentOutOfRangeException(nameof(length)); } switch (captchaType) { case CaptchaType.Number: return(GetRandomNumbers(length)); case CaptchaType.ChineseChar: return(GetRandomChinese(length)); default: return(GetRandomNumbersAndLetters(length)); } }
public void SetupCaptcha(CaptchaType captchaType, int?width = default(int?), int?height = default(int?)) { this.captchaType = captchaType; localizer = Service.Get <Localizer>(); eventDispatcher = Service.Get <EventDispatcher>(); imageToggles = GetComponentsInChildren <ToggleInspector>(); for (int i = 0; i < imageToggles.Length; i++) { imageToggles[i].ToggleClicked += onToggleOnClickedPosition; } setLoadingSpinnerVisibility(show: true); Service.Get <EventDispatcher>().DispatchEvent(new PopupEvents.ShowTopPopup(base.gameObject)); guiCamera = base.gameObject.GetComponentInParent <Canvas>().GetComponent <Camera>(); eventDispatcher.AddListener <CaptchaServiceEvents.CaptchaLoaded>(onCaptchaLoaded); eventDispatcher.AddListener <CaptchaServiceEvents.CaptchaSolutionAccepted>(onCaptchaSolutionAccepted); eventDispatcher.AddListener <CaptchaServiceEvents.CaptchaSolutionDeclined>(onCaptchaSolutionDeclined); Service.Get <INetworkServicesManager>().CaptchaService.GetCaptcha(captchaType, width, height); }
/// <summary> /// Displays reCAPTCHA widget /// </summary> /// <param name="helper">HTML helper</param> /// <param name="siteKey">Your sitekey.</param> /// <param name="theme">The color theme of the widget.</param> /// <param name="type">The type of CAPTCHA to serve.</param> /// <param name="tabIndex">The tabindex of the widget and challenge. If other elements in your page use tabindex, it should be set to make user navigation easier.</param> /// <param name="callback">Your callback function that's executed when the user submits a successful CAPTCHA response. The user's response, g-recaptcha-response, will be the input for your callback function.</param> /// <param name="expiredCallback">Your callback function that's executed when the recaptcha response expires and the user needs to solve a new CAPTCHA.</param> /// <returns>Widget tag HTML</returns> public static IHtmlString NRecaptcha2( this HtmlHelper helper, string siteKey, Theme theme = Theme.Light, CaptchaType type = CaptchaType.Image, int tabIndex = 0, string callback = "", string expiredCallback = "") { var tag = new Recaptcha2Tag( siteKey, theme, type, tabIndex, callback, expiredCallback); return(tag); }
//保存验证码 public static string SaveImage(string base64String, CaptchaType captchaType, string imgName) { var path = Path.GetDirectoryName(Assembly.GetAssembly(typeof(Program)).Location); //Path path = Path.Combine(path ?? throw new WechatSogouFileException(), $"captcha/{captchaType}"); //Check if directory exist if (!Directory.Exists(path)) { Directory.CreateDirectory(path); //Create directory if it doesn't exist } //set the image path string imgPath = Path.Combine(path, imgName); byte[] imageBytes = Convert.FromBase64String(base64String); File.WriteAllBytes(imgPath, imageBytes); return(imgPath); }
/// <summary> /// 创建验证码缓存Key /// </summary> /// <param name="type">验证码类型</param> /// <param name="tenantId">租户id(可空)</param> /// <returns>缓存Key</returns> public static string CreateCacheKey(CaptchaType type, int?tenantId = null) { var res = string.Empty; switch (type) { case CaptchaType.HostTenantRegister: res = HostCacheKeys.TenantRegistrationCaptchaCache; break; case CaptchaType.HostUserLogin: res = HostCacheKeys.HostUserLoginCaptchaCache; break; case CaptchaType.TenantUserRegister: if (tenantId.HasValue) { res = TenantCacheKeys.UserRegistrationCaptchaCache; } else { res = $"T:{tenantId.Value}-{TenantCacheKeys.UserRegistrationCaptchaCache}"; } break; case CaptchaType.TenantUserLogin: if (tenantId.HasValue) { res = TenantCacheKeys.UserLoginCaptchaCache; } else { res = $"T:{tenantId.Value}-{TenantCacheKeys.UserLoginCaptchaCache}"; } break; default: throw new ArgumentException("创建验证码CacheKey错误!验证码类型正确"); } return(res); }
public Recaptcha2Tag( string siteKey, Theme theme = Theme.Light, CaptchaType type = CaptchaType.Image, int tabIndex = 0, string callback = "", string expiredCallback = "") { if (string.IsNullOrEmpty(siteKey)) { throw new InvalidOperationException("SiteKey is required"); } SiteKey = siteKey; Theme = theme; Type = type; TabIndex = tabIndex; Callback = callback; ExpiredCallback = expiredCallback; }
/// <summary> /// 产生验证码(随机产生5-7位). /// </summary> /// <param name="type">验证码类型:数字,字符,符合.</param> /// <returns></returns> public string CreateVerifyCode(CaptchaType type) { string verifyCode = string.Empty; Random random = new Random(); int length = random.Next(5, 7); switch (type) { case CaptchaType.Digital: verifyCode = GetSingleton().CreateDigitalCaptcha(length); break; case CaptchaType.Alpha: verifyCode = GetSingleton().CreateAlphaCaptcha(length); break; case CaptchaType.Mixture: verifyCode = GetSingleton().CreateMixtureCaptcha(length); break; } return(verifyCode); }
/// <summary> /// /// </summary> /// <param name="key"></param> /// <param name="type"></param> /// <param name="len"></param> /// <param name="timeout"></param> /// <returns></returns> public string NewCaptcha(string key, CaptchaType type = CaptchaType.PureNumber, int len = 6, int timeout = 900) { Random rand = new Random(); string s; StringBuilder ret_str = new StringBuilder(); switch (type) { case CaptchaType.Character: { s = character + number; break; } case CaptchaType.PureNumber: { s = number; break; } default: { s = character + number; break; } } for (int i = 0; i < len; i++) { int idx = rand.Next(0, s.Length - 1); ret_str.Append(s[idx]); } this.RedisIns.SetAsync(key, ret_str.ToString(), timeout); return(ret_str.ToString()); }
/// <summary> /// 校验验证码 /// </summary> /// <param name="cacheManager">缓存管理器</param> /// <param name="settingManager">设置管理器</param> /// <param name="captchaType">验证码类型</param> /// <param name="key">验证码缓存Key</param> /// <param name="verificationCode">输入的验证码</param> /// <param name="tenantId">租户id</param> /// <returns></returns> public static async Task CheckVerificationCode(this ICacheManager cacheManager, ISettingManager settingManager, CaptchaType captchaType, string key, string verificationCode, int?tenantId = null) { // 获取对应验证码配置 var captchaConfig = await settingManager.GetCaptchaConfig(captchaType, tenantId); // 是否启用验证码 if (captchaConfig.Enabled) { if (verificationCode.IsNullOrWhiteSpace()) { throw s_captchaInputNullException; } // 分租户获取验证码缓存 var cacheKey = CaptchaHelper.CreateCacheKey(captchaType, tenantId); // 从缓存验证码值 var cacheValue = await cacheManager.GetValue <string>(cacheKey, key, true); if (cacheValue.IsNullOrWhiteSpace()) { throw s_captchaExpireException; } // 对比验证码 if (verificationCode.ToLower() != cacheValue) { throw s_captchaNoMatchException; } } }
public static string RandomCode(CaptchaType ctype, int numberOfChars) { string s = ""; string alphas = "ABCDEFGHIJKLMNPQRSTUVWXYZ"; //if you want to add other charaters add it here - zero and O are removed to avoid confusion string alphanumeric = "123456789ABCDEFGHIJKLMNPQRSTUVWXYZ"; Random rnd = new Random(); for (int i = 0; i < numberOfChars; i++) { if (ctype == CaptchaType.Numeric) { s = String.Concat(s, rnd.Next(10).ToString()); } else if (ctype == CaptchaType.Alpha) { s = String.Concat(s, alphas.Substring(rnd.Next(24), 1)); } else { s = String.Concat(s, alphanumeric.Substring(rnd.Next(33), 1)); } } return(s); }
/// <summary> /// Define a type for captcha. /// </summary> public Captcha Type(CaptchaType type) { _type = type; return this; }
/// <summary> /// Получить URI капчи. /// </summary> /// <param name="captchaType">Тип капчи.</param> /// <param name="forThread">Для треда.</param> /// <returns>URI капчи.</returns> public Uri GetCaptchaUri(CaptchaType captchaType, bool forThread) { if (captchaType == CaptchaType.Yandex) { return new Uri(BaseUri, CaptchaUri); } if (captchaType == CaptchaType.Recaptcha) { return new Uri(BaseUri, CaptchaUri + "?type=recaptcha"); } if (captchaType == CaptchaType.GoogleRecaptcha2СhV1) { return new Uri(BaseUri, CaptchaUri + "?type=recaptchav1&mobile=1"); } if (captchaType == CaptchaType.GoogleRecaptcha2СhV2) { return new Uri(BaseUri, CaptchaUri + "?type=recaptcha&mobile=1"); } if (captchaType == CaptchaType.DvachCaptcha) { if (forThread) { return new Uri(BaseUri, CaptchaUri + "?type=2chaptcha&action=thread"); } return new Uri(BaseUri, CaptchaUri + "?type=2chaptcha"); } return null; }
public PostCaptchaSolutionOperation(CaptchaType type, CaptchaSolution captchaSolution) { Type = type; CaptchaSolution = captchaSolution; }
private string GenerateRandomString(CaptchaType captchaType = CaptchaType.CtMedium, int captchaLength = 5) { // Make a gap to change CPU cycle Thread.Sleep(1); string baseChars = String.Empty; switch (captchaType) { case CaptchaType.CtSimple: baseChars = "AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz"; break; case CaptchaType.CtMedium: baseChars = "AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz01234578"; break; case CaptchaType.CtDifficult: baseChars = "AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz0123456789!@#$%&*+"; break; } var randomGenerator = new Random(DateTime.Now.Millisecond); var generatedRandomString = new String( Enumerable.Repeat(baseChars, captchaLength) .Select(s => s[randomGenerator.Next(s.Length)]) .ToArray()); return generatedRandomString; }
/// <summary> /// Получить URI капчи (V2). /// </summary> /// <param name="captchaType">Тип капчи.</param> /// <param name="board">Борда.</param> /// <param name="thread">Тред.</param> /// <returns>URI капчи.</returns> public Uri GetCaptchaUriV2(CaptchaType captchaType, string board, int? thread) { if (captchaType == CaptchaType.DvachCaptcha) { if (thread != null) { return new Uri(BaseUri, CaptchaUriV2 + "2chaptcha/id?board=" + board + "&thread=" + thread.Value); } return new Uri(BaseUri, CaptchaUriV2 + "2chaptcha/id?board=" + board); } return null; }
/// <summary> /// Получить URI изображения капчи V2. /// </summary> /// <param name="captchaType">Тип капчи.</param> /// <param name="id">Идентификатор.</param> /// <returns>URI изображения.</returns> public Uri GetCaptchaV2ImageUri(CaptchaType captchaType, string id) { if (captchaType == CaptchaType.DvachCaptcha) { return new Uri(BaseUri, CaptchaUriV2 + "2chaptcha/image/" + id); } return null; }
private static void AddCaptchaId(BotData data, long id, CaptchaType type) { data.Objects["lastCaptchaId"] = id; data.Objects["lastCaptchaType"] = type; }
/// <summary> /// Получить ключи для капчи. /// </summary> /// <param name="link">Ссылка.</param> /// <param name="captchaType">Тип капчи.</param> /// <returns>Ключи для капчи.</returns> public IEngineOperationsWithProgress<ICaptchaResult, EngineProgress> GetCaptchaKeys(BoardLinkBase link, CaptchaType captchaType) { return new MakabaGetCaptchaOperationV2(new MakabaGetCaptchaArgument() { Link = link, CaptchaType = captchaType }, Services); }
public static string GenerateRandomCode(CaptchaType ctype, int numberOfChars) { string s = ""; string alphas = "ABCDEFGHIJKLMNPQRSTUVWXYZ"; //if you want to add other charaters add it here - zero and O are removed to avoid confusion string alphanumeric = "123456789ABCDEFGHIJKLMNPQRSTUVWXYZ"; Random rnd = new Random(); for (int i = 0; i < numberOfChars; i++) { if (ctype == CaptchaType.Numeric) { s = String.Concat(s, rnd.Next(10).ToString()); } else if (ctype == CaptchaType.Alpha) { s = String.Concat(s, alphas.Substring(rnd.Next(24), 1)); } else { s = String.Concat(s, alphanumeric.Substring(rnd.Next(33), 1)); } } return s; }
/// <summary> /// Generate Captcha image /// </summary> /// <param name="CaptchaString">String for display captcha</param> /// <param name="FileType">Image file type </param> /// <param name="noisy">True value for noising </param> /// <returns>byte[]</returns> public byte[] getCaptcha(string CaptchaString, CaptchaType FileType, int CaptchaWidth, int CaptchaHeight, bool noisy) { //string fileformat; byte[] ResultByte; Random rand = new Random((int)DateTime.Now.Ticks); using (var mem = new MemoryStream()) using (var bmp = new Bitmap(CaptchaWidth, CaptchaHeight)) using (var gfx = Graphics.FromImage((Image)bmp)) { gfx.TextRenderingHint = TextRenderingHint.ClearTypeGridFit; gfx.SmoothingMode = SmoothingMode.AntiAlias; gfx.FillRectangle(Brushes.White, new Rectangle(0, 0, bmp.Width, bmp.Height)); //add noise if (noisy) { int i, r, x, y; var pen = new Pen(Color.Yellow); for (i = 1; i < 10; i++) { pen.Color = Color.FromArgb( (rand.Next(0, 255)), (rand.Next(0, 255)), (rand.Next(0, 255))); r = rand.Next(0, (130 / 3)); x = rand.Next(0, 130); y = rand.Next(0, 30); gfx.DrawEllipse(pen, x - r, y - r, r, r); } } //add question gfx.DrawString(CaptchaString, new Font("Tahoma", 15), Brushes.Gray, 2, 3); #region Renderer switch (FileType) { case CaptchaType.Bmp: bmp.Save(mem, System.Drawing.Imaging.ImageFormat.Bmp); break; case CaptchaType.Gif: bmp.Save(mem, System.Drawing.Imaging.ImageFormat.Gif); break; case CaptchaType.Jpeg: bmp.Save(mem, System.Drawing.Imaging.ImageFormat.Jpeg); break; case CaptchaType.Png: bmp.Save(mem, System.Drawing.Imaging.ImageFormat.Png); break; } #endregion ResultByte = mem.GetBuffer(); } return ResultByte; }