博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
验证码生成(转)
阅读量:4554 次
发布时间:2019-06-08

本文共 4407 字,大约阅读时间需要 14 分钟。

大 家对于验证码都很熟悉了,几乎每天都会和它打交道,如注册、登录,论坛回帖等。可以说验证码与我们广大网民的生活工作息息相关。当我们在输入验证码时有人 可能会觉得麻烦,虽然验证码让我们有一点小小的麻烦,但是它给我们带来了很大的好处。它可以防止利用恶意程序批量注册、发帖、灌水还能有效的防止黑客暴力 破解密码。验证码虽然一般只有简单的几个字符,但是它的作用着实不小啊!下面我们就一起看看如何实现网站中的验证码。

下图为一个含有字母跟数字的简单验证码:

 

 

下面我们就来看看它们是如何产生的:

 

用一般处理程序生成验证码

 

using
System;
using
System.Web;
using
System.Drawing;
using
System.Drawing.Drawing2D;
using
System.Web.SessionState;
 
namespace
Web.handler
{
    
/// <summary>
    
/// WaterMark 的摘要说明
    
/// </summary>
    
public
class
WaterMark : IHttpHandler, IRequiresSessionState 
// 要使用session必须实现该接口,记得要导入System.Web.SessionState命名空间
    
{
        
public
void
ProcessRequest(HttpContext context)
        
{
            
string
checkCode = GenCode(5); 
// 产生5位随机字符
            
context.Session[
"Code"
] = checkCode;
//将字符串保存到Session中,以便需要时进行验证
            
System.Drawing.Bitmap image =
new
System.Drawing.Bitmap(70, 22);
            
Graphics g = Graphics.FromImage(image);
            
try
            
{
                
//生成随机生成器
                
Random random =
new
Random();
 
                
//清空图片背景色
                
g.Clear(Color.White);
 
                
// 画图片的背景噪音线
                
int
i;
                
for
(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"
, 12, (System.Drawing.FontStyle.Bold));
                
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.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);
                
context.Response.ClearContent();
                
context.Response.ContentType =
"image/Gif"
;
                
context.Response.BinaryWrite(ms.ToArray());
            
}
            
finally
            
{
                
g.Dispose();
                
image.Dispose();
            
}
        
}
 
        
/// <summary>
        
/// 产生随机字符串
        
/// </summary>
        
/// <param name="num">随机出几个字符</param>
        
/// <returns>随机出的字符串</returns>
        
private
string
GenCode(
int
num)
        
{
        
//验证码中出现的字符
            
string
str =
"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
;
//str中的值就是将来会在验证码中出现的字符
            
char
[] chastr = str.ToCharArray();
           
            
string
code =
""
;
            
Random rd =
new
Random();
            
int
i;
            
for
(i = 0; i < num; i++)
            
{
                
//code += source[rd.Next(0, source.Length)];
                
code += str.Substring(rd.Next(0, str.Length), 1);
            
}
            
return
code;
 
        
}
 
        
public
bool
IsReusable
        
{
            
get
            
{
                
return
false
;
            
}
        
}
 
    
}
 
}

  

 

刷新验证码的HTML及Javascript代码:

 

 

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Login.aspx.cs" Inherits="nwessystem.Login" %>
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">
 
<
html
xmlns
=
""
>
<
head
runat
=
"server"
>
    
<
title
>登录窗体</
title
>
    
<
link
href
=
"../css/login.css"
rel
=
"stylesheet"
type
=
"text/css"
/>
        
<
script
language
=
"javascript"
type
=
"text/javascript"
>
            
//刷新验证码的js函数
            
function changeCode() {
                
var imgNode = document.getElementById("vimg");               
 
                
//重新加载验证码,达到刷新的目的
                
imgNode.src = "../handler/WaterMark.ashx?t=" + (new Date()).valueOf();  // 这里加个时间的参数是为了防止浏览器缓存的问题  
            
</
script
>
</
head
>
<
body
>
    
            
<
p
>验证码:<
img
src
=
"../handler/WaterMark.ashx"
id
=
"vimg"
alt
=
"点击刷新验证码"
onclick
=
"changeCode() " 
/><
asp:TextBox
ID
=
"txtCode"
runat
=
"server"
CssClass
=
"txtcode"
></
asp:TextBox
></
p
>
          
</
body
>
</
html
>

  

登录时判断验证码是否正确

 

using
System;
using
System.Collections.Generic;
using
System.Linq;
using
System.Web;
using
System.Web.UI;
using
System.Web.UI.WebControls;
using
BLL;
 
namespace
nwessystem
{
    
public
partial
class
Login : System.Web.UI.Page
    
{
 
        
protected
void
btnLogin_Click(
object
sender, EventArgs e)
        
{
            
//检验验证码部分
            
string
code = txtCode.Text.Trim().ToUpper();
            
string
rightCode = Session[
"Code"
].ToString();
            
            
//判断验证码是否正确
            
if
(code != rightCode)
            
{
                
//验证码输入错误!
                
Page.ClientScript.RegisterStartupScript(Page.GetType(),
"message"
,
"<script language='javascript' defer>alert('验证码错误!');</script>"
);
                
return
;
            
}
 
            
//检验用户名和密码部分
            
string
name=txtName.Text.Trim();
            
string
pwd=txtPassword.Text.Trim();
            
bool
b = LoginManager.Login(name, pwd);
 
            
if
(b)
            
{
                
//登录成功
                
Page.ClientScript.RegisterStartupScript(Page.GetType(),
"message"
,
"<script language='javascript' defer>alert('登录成功!');</script>"
);
            
}
            
else
            
{
                
//登录失败
                
Page.ClientScript.RegisterStartupScript(Page.GetType(),
"message"
,
"<script language='javascript' defer>alert('登录失败,用户名或密码错误!');</script>"
);
            
}
             
        
}
    
}
}

 

 

好了,通过上面简单的代码就可以实现验证码的生成与验证了。代码里注释很详细了,相信不用我再写多余的说明,大家也都可以看懂。如果还是不懂欢迎在下方留言。博客水平有限,希望各位多多指正!

转载于:https://www.cnblogs.com/tonykan/archive/2012/09/26/2704088.html

你可能感兴趣的文章
C#对DataTable里数据筛选排序的方法
查看>>
Confluence 6 设置公共访问
查看>>
堆内存管理
查看>>
PIE保护绕过
查看>>
牛客假日团队赛11 A 级数求和
查看>>
2019百度之星初赛一 1005 Seq HDU - 6672 (打表找规律)
查看>>
[kuangbin带你飞]专题十六 KMP & 扩展KMP & Manacher D - Cyclic Nacklace HDU - 3746(循环节kmp)...
查看>>
Por Costel and the Match Gym - 100923H(经典种类并查集)
查看>>
Happy 2006 POJ - 2773(欧几里得算法 互素问题)
查看>>
[kuangbin带你飞]专题十六 KMP & 扩展KMP & Manacher E - Period HDU - 1358(循环节kmp)
查看>>
[kuangbin带你飞]专题十二 基础DP1 F - Piggy-Bank HDU - 1114(完全背包)
查看>>
Trailing Zeroes (I) LightOJ - 1028(唯一分解 因子个数)
查看>>
洛谷题 P3366 【模板】最小生成树
查看>>
Farey Sequence POJ - 2478 (欧拉函数 前缀和)
查看>>
[kuangbin带你飞]专题六 最小生成树 B - Networking
查看>>
[kuangbin带你飞]专题十二 基础DP1 E - Super Jumping! Jumping! Jumping! HDU - 1087(不连续单调递增最长子序列的和)...
查看>>
[kuangbin带你飞]专题四 最短路练习 B( POJ 2253) Frogger(spfa)
查看>>
[kuangbin带你飞]专题六 最小生成树 A - Jungle Roads
查看>>
Codeforces Round #570 (Div. 3)B
查看>>
[kuangbin带你飞]专题五 并查集 B - The Suspects
查看>>