天天看點

c#實作驗證碼功能

一、驗證碼簡介 

驗證碼功能一般是用于防止批量注冊的,不少網站為了防止使用者利用機器人自動注冊、登入、灌水,都采用了驗證碼技術。所謂驗證碼,就是将一串随機産生的數字或字母或符号或文字,生成一幅圖檔, 圖檔裡加上一些幹擾象素(防止OCR),由使用者肉眼識别其中的驗證碼資訊,輸入表單送出網站驗證,驗證成功後才能使用某項功能。

常見的驗證碼有如下幾種: 

1、純數字驗證碼,一般為四位随機數字; 

2、數字+字母驗證碼,一般從數字(0~9)和字母(A~Z和a~z)中随機抽出幾個字元組成; 

3、漢字驗證碼,相對而言,這種驗證碼比較少見一點,實作起來也相對複雜一些,但在不少網站中還是可以看到的;

二、驗證碼的實作 

1、純數字驗證碼的實作 

純數字驗證碼的實作相對比較簡單,可通過以下兩種方法來實作 

/// <summary>
        /// 數字驗證碼
         /// </summary>
        /// <param name="codeCount">驗證碼的位數‘n’</param>
        /// <returns>傳回‘n’位驗證碼的字元串</returns>
        private static String GetRandomint(int codeCount)
        {
            Random random = new Random();
            StringBuilder sbmin = new StringBuilder();
            StringBuilder sbmax = new StringBuilder();
            for (int i = 0; i < codeCount; i++)
            {
                sbmin.Append("1");
                sbmax.Append("9");
            }
           return random.Next(Convert.ToInt32(sbmin.ToString()), Convert.ToInt32(sbmax.ToString())).ToString();
        }      

2、數字與字母組合字元串

字母與數字組合的字元串也比較簡單  可以按照自己的規則去生成大小寫字母

/// <summary>
        /// 生成驗證碼字元串
         /// </summary>
        /// <param name="codeLen">驗證碼字元長度</param>
        /// <returns>傳回驗證碼字元串</returns>
        private static string MakeCode(int codeLen)
        {
            if (codeLen < 1)
            {
                return string.Empty;
            }
            int number;
            StringBuilder sbCheckCode = new StringBuilder();
            Random random = new Random();

            for (int index = 0; index < codeLen; index++)
            {
                number = random.Next();

                if (number % 2 == 0)
                {
                    sbCheckCode.Append((char)(\'0\' + (char)(number % 10))); //生成數字
                  }
                else
                {
                    sbCheckCode.Append((char)(\'A\' + (char)(number % 26))); //生成字母
                  }
            }
            return sbCheckCode.ToString();
        }      

3、生成圖檔流

原理:先生成驗證碼,然後把生成的驗證碼轉化為圖檔流進行輸出

///<summary>
         /// 擷取驗證碼圖檔流
         /// </summary>
        /// <param name="checkCode">驗證碼字元串</param>
        /// <returns>傳回驗證碼圖檔流</returns>
        public static MemoryStream CreateCodeImg(string checkCode)
        {
            if (string.IsNullOrEmpty(checkCode))
            {
                return null;
            }
            Bitmap image = new Bitmap((int)Math.Ceiling((checkCode.Length * 12.5)), 22);
            Graphics graphic = Graphics.FromImage(image);
            try
            {
                Random random = new Random();
                graphic.Clear(Color.White);
                int x1 = 0, y1 = 0, x2 = 0, y2 = 0;
                for (int index = 0; index < 25; index++)
                {
                    x1 = random.Next(image.Width);
                    x2 = random.Next(image.Width);
                    y1 = random.Next(image.Height);
                    y2 = random.Next(image.Height);

                    graphic.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);
                }
                Font font = new Font("Arial", 12, (FontStyle.Bold | FontStyle.Italic));
                System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Red, Color.DarkRed, 1.2f, true);
                graphic.DrawString(checkCode, font, brush, 2, 2);

                int x = 0;
                int y = 0;

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

                    image.SetPixel(x, y, Color.FromArgb(random.Next()));
                }
                //畫圖檔的邊框線
                graphic.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);
                //将圖檔驗證碼儲存為流Stream傳回
                System.IO.MemoryStream ms = new System.IO.MemoryStream();
                image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
                return ms;
            }
            finally
            {
                graphic.Dispose();
                image.Dispose();
            }
        }      
調用方法      
在HttpHander的ProcessRequest中進行調用:

pupublic void ProcessRequest(HttpContext context)
{
     string code = MakeCode(5);
     context.Response.ClearContent();
     context.Response.ContentType = "image/Gif";
     MemoryStream ms = CreateCodeImg(code);
     if (null != ms)
     {
        context.Response.BinaryWrite(ms.ToArray());
     }
}      

 (本文轉自黎木大大,原文位址:https://www.cnblogs.com/running-mydream/p/4071528.html 感謝分享!)