2022年4月4日 星期一

[研究][ASP.NET]WebForm圖形驗證碼(CAPTCHA)程式

[研究][ASP.NET]WebForm圖形驗證碼(CAPTCHA)程式

2022-04-04

環境:Visual Studio 2022 + ASP.NET + WebForm + Web Application + C#

一般常用的 Google reCAPTCHA需要Web Server和Client可以連上Internet,但是若因特殊需求,就不能用 Google reCAPTCHA,需要一個封閉區域網路上可用的。

Default.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" 
    Inherits="WebApplication1.Default" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            驗證碼<asp:TextBox AutoComplete="Off" ID="txtCheckCode" Width="60" 
                runat="server"></asp:TextBox>
            <img src="/GenerateCaptchaCodeImage.aspx" width="69" height="20" />
            <br />
            <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
            <br />
            <asp:Label ID="Label1" runat="server"></asp:Label>
        </div>
    </form>
</body>
</html>


Default.aspx.cs

using System;

namespace WebApplication1
{
    public partial class Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            if (string.Compare(Session["CheckCode"].ToString(), txtCheckCode.Text, true) != 0)
            {
                Response.Write("<script>alert('圖片驗證碼錯誤');</script>");
                Label1.ForeColor = System.Drawing.Color.Red;
                Label1.Text = "圖片驗證碼錯誤";
                return;
            }
            else
            {
                Response.Write("<script>alert('圖片驗證碼成功');</script>");
                Label1.ForeColor = System.Drawing.Color.Green;
                Label1.Text = "圖片驗證碼成功";
            }
        }
    }
}


GenerateCaptchaCodeImage.aspx
<%@ Page Language="C#" AutoEventWireup="true" 
    CodeBehind="GenerateCaptchaCodeImage.aspx.cs" 
    Inherits="WebApplication1.GenerateCaptchaCodeImage" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
        </div>
    </form>
</body>
</html>


GenerateCaptchaCodeImage.aspx.cs
using System;
using System.Drawing;
using System.Web;

namespace WebApplication1
{
    public partial class GenerateCaptchaCodeImage : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            this.CreateCheckCodeImage(GenerateCheckCode());
        }
        private string GenerateCheckCode()
        {
            int number;
            char code;
            string checkCode = string.Empty;

            System.Random random = new Random();

            for (int i = 0; i < 4; i++)
            {
                number = random.Next();

                if (number % 2 == 0)
                    code = (char)('0' + (char)(number % 10));
                else
                    code = (char)('A' + (char)(number % 26));

                checkCode += code.ToString();
            }

            Session["CheckCode"] = checkCode;
            Response.Cookies.Add(new HttpCookie("CheckCode", checkCode));

            return checkCode;
        }

        private void CreateCheckCodeImage(string checkCode)
        {
            if (checkCode == null || checkCode.Trim() == string.Empty)
                return;

            //System.Drawing.Bitmap image = new System.Drawing.Bitmap((int)Math.Ceiling((checkCode.Length * 12.5)), 22);
            //System.Drawing.Bitmap image = new System.Drawing.Bitmap((int)Math.Ceiling((checkCode.Length * 20)), 40);
            System.Drawing.Bitmap image = new System.Drawing.Bitmap(100, 30);

            Graphics g = Graphics.FromImage(image);

            try
            {
                //生成隨機生成器
                Random random = new Random();

                //清空圖片背景色
                g.Clear(Color.White);

                //畫圖片的背景噪音線
                for (int i = 0; i < 25; i++)
                {
                    int x1 = random.Next(image.Width);
                    int x2 = random.Next(image.Width);
                    int y1 = random.Next(image.Height);
                    int y2 = random.Next(image.Height);

                    g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);
                }

                Font font = new System.Drawing.Font("Arial", 22, (System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic));
                System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Blue, Color.DarkRed, 1.2f, true);
                //g.DrawString(checkCode, font, brush, 2, 2);
                g.DrawString(checkCode, font, brush, 2, 2);

                //畫圖片的前景噪音點
                for (int i = 0; i < 500; i++)
                {
                    int x = random.Next(image.Width);
                    int y = random.Next(image.Height);

                    image.SetPixel(x, y, Color.FromArgb(random.Next()));
                }

                //畫圖片的邊框線
                g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);

                System.IO.MemoryStream ms = new System.IO.MemoryStream();
                image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
                Response.ClearContent();
                Response.ContentType = "image/Gif";
                Response.BinaryWrite(ms.ToArray());
            }
            finally
            {
                g.Dispose();
                image.Dispose();
            }
        }
    }
}


(完)

相關

浮雲雅築: [研究]ASP.NET WebForm CAPTCHA圖形驗證碼
https://shaurong.blogspot.com/2021/12/aspnet-webform-captcha.html

Simple CAPTCHA, Create Your Own in C# - CodeProject
https://www.codeproject.com/Articles/99148/Simple-CAPTCHA-Create-Your-Own-in-Csharp

A CAPTCHA Server Control for ASP.NET - CodeProject
https://www.codeproject.com/Articles/8751/A-CAPTCHA-Server-Control-for-ASP-NET

A Simple CAPTCHA Image Verification in C# and ASP.Net
http://www.codedigest.com/CodeDigest/88-A-Simple-CAPTCHA-Image-Verification-in-C--and-ASP-Net.aspx

使用 CAPTCHA 防止 bot 使用您的 ASP.NET Web Razor) 網站
https://docs.microsoft.com/zh-tw/aspnet/web-pages/overview/security/using-a-catpcha-to-prevent-automated-programs-bots-from-using-your-aspnet-web-site


沒有留言:

張貼留言