-
Notifications
You must be signed in to change notification settings - Fork 1
/
Captcha.cs
60 lines (55 loc) · 2.16 KB
/
Captcha.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
using System;
using net.vieapps.Components.Utility;
namespace net.vieapps.Components.Security
{
/// <summary>
/// Servicing methods for working with captcha images
/// </summary>
public static partial class CaptchaService
{
/// <summary>
/// Generates random code for using with captcha or other purpose
/// </summary>
/// <param name="useShortCode">true to use short-code</param>
/// <param name="useHex">true to use hexa in code</param>
/// <returns>The string that presents random code</returns>
public static string GenerateRandomCode(bool useShortCode = true, bool useHex = false)
=> UtilityService.GetRandomCode(useShortCode, useHex);
/// <summary>
/// Generates new code of the captcha
/// </summary>
/// <param name="salt">The string to use as salt</param>
/// <returns>The encrypted string that contains code of captcha</returns>
public static string GenerateCode(string salt = null)
=> $"{DateTime.Now.ToUnixTimestamp()}-{salt ?? UtilityService.NewUUID.Left(13)}-{CaptchaService.GenerateRandomCode()}".Encrypt(CaptchaService.EncryptionKey, true);
/// <summary>
/// Validates captcha code
/// </summary>
/// <param name="captchaCode">The string that presents encrypted code</param>
/// <param name="inputCode">The code that inputed by user</param>
/// <returns>true if valid</returns>
public static bool IsCodeValid(string captchaCode, string inputCode)
{
try
{
if (string.IsNullOrWhiteSpace(captchaCode) || string.IsNullOrWhiteSpace(inputCode))
return false;
var info = captchaCode.Decrypt(CaptchaService.EncryptionKey, true).ToArray('-');
return (DateTime.Now.ToUnixTimestamp() - info.First().CastAs<long>()) / 60 <= 5 && inputCode.Trim().IsEquals(info.Last());
}
catch
{
return false;
}
}
static string _EncryptionKey = null;
/// <summary>
/// Gets or Sets the encryption key for encrypting/decrypting captcha image
/// </summary>
public static string EncryptionKey
{
get => CaptchaService._EncryptionKey ?? (CaptchaService._EncryptionKey = UtilityService.GetAppSetting("Keys:Encryption", CryptoService.DEFAULT_PASS_PHRASE));
set => CaptchaService._EncryptionKey = value;
}
}
}