.net 인증 코드 생성 및 사용 방법

高洛峰
풀어 주다: 2017-01-13 15:02:59
원래의
1416명이 탐색했습니다.

소규모 클래스: 인증코드의 역할:

몇 년 전만 해도 대부분의 웹사이트, 포럼 등에 인증코드가 없었습니다. 일반 사용자의 경우 인증코드로 인해 사용자 작업이 줄어들었기 때문입니다. 경험. 하지만 이후에는 각종 스팸 로봇, 투표 로봇, 악성 등록 로봇이 잇달아 등장해 웹사이트의 부담을 크게 가중시켰고, 웹사이트 데이터베이스에 대량의 정크 데이터를 가져오기도 했다. 각종 로봇 프로그램의 파괴를 막기 위해 프로그래머들은 인간의 눈으로만 인식할 수 있고, 프로그램에서는 쉽게 인식할 수 없는 인증코드를 고안해냈습니다!

인증 코드는 그림이며 문자, 숫자, 심지어 한자가 그림 내용으로 포함되어 있습니다. 이러한 그림의 내용은 사람의 눈으로 쉽게 식별할 수 있지만 프로그램에서는 식별할 수 없습니다. 그것을 식별합니다. 프로그램은 데이터베이스 작업(로그인 인증, 투표, 게시, 회신, 등록 등)을 수행하기 전에 먼저 클라이언트가 제출한 인증 코드가 그림의 내용과 동일한지 확인합니다. 데이터베이스 작업을 수행합니다. 다르면 확인 코드 오류가 표시되고 데이터베이스 작업이 수행되지 않습니다. 이런 식으로 모든 종류의 로봇 프로그램이 차단됩니다!

그런데 컴퓨터 과학이 발달하면서 패턴인식 같은 기술이 점점 성숙해지고 있어서 로봇 프로그램을 쓰는 사람이 프로그램을 통해 그림에 직접 적힌 내용을 인식해서 제출하면 된다. 코드는 쓸모가 없습니다. 로봇 프로그램의 인식을 방지하기 위해 인증코드의 이미지 생성도 지속적으로 발전하고 있으며, 간섭점 추가, 간섭선 추가, 문자 변형, 각도 위치 변경, 색상 차이 등... 컴퓨터 인식 방지를 위한 다양한 기술도 적용되고 있다. 인증 코드. 이 두 기술의 경쟁 속에서 지금 우리가 보는 인증코드가 탄생했는데, 이미 많은 사람들이 "이게 무슨 인증코드지? 인간의 눈으로는 아무것도 구분할 수 없다"고 불평하고 있다.

인증코드의 기능을 이해하고, 인증코드 생성 및 사용에 대한 간단한 예시를 작성해 보겠습니다

.net 인증 코드 생성 및 사용 방법

먼저 인증코드를 표시할 페이지를 생성합니다. 인증 코드 입력이 올바른지 확인

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
 <title></title>
 <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
 <script type="text/javascript">
 //点击切换验证码
 function f_refreshtype() {
 var Image1 = document.getElementById("img");
 if (Image1 != null) {
 Image1.src = Image1.src + "?";
 }
 } 
 </script>
</head>
<body>
 <form id="form1" runat="server">
 <div>
 <table>
 <tr>
 <td>
  <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
 </td>
 <td>
  <img  src="png.aspx" id="img" onclick="f_refreshtype()" / alt=".net 인증 코드 생성 및 사용 방법" >
 </td>
 <td>
  <asp:Button ID="Button1" runat="server" Text="确定" />
 </td>
 </tr>
 </table>
 </div>
 </form>
</body>
</html>
로그인 후 복사

이 페이지는 백그라운드에서 인증 코드를 확인합니다

protected void Page_Load(object sender, EventArgs e)
{
//生成的验证码被保存到session中
if (Session["CheckCode"] != null)
{
string checkcode = Session["CheckCode"].ToString();
if (this.TextBox1.Text == checkcode)
{
 ClientScript.RegisterClientScriptBlock(this.GetType(), "", "alert(&#39;验证码输入正确!&#39;)", true);
}
else
{
 ClientScript.RegisterClientScriptBlock(this.GetType(), "", "alert(&#39;验证码输入错误!&#39;)", true);
}
}
 
}
로그인 후 복사

인증 코드 생성 페이지 png.aspx

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
CreateCheckCodeImage(GenerateCheckCodes(4));
}
}
public void ShowAuthCode(Stream stream, out string code)
{
Random random = new Random();
code = random.Next(1000, 9999).ToString();
 
Bitmap bitmap = CreateAuthCode(code);
bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Gif);
}
 
private string GenerateCheckCodes(int iCount)
{
int number;
string checkCode = String.Empty;
int iSeed = DateTime.Now.Millisecond;
System.Random random = new Random(iSeed);
for (int i = 0; i < iCount; i++)
{
number = random.Next(10);
checkCode += number.ToString();
}
Session["CheckCode"] = checkCode;
return checkCode;
}
 
private Bitmap CreateAuthCode(string str)
{
Font fn = new Font("宋体", 12);
Brush forecolor = Brushes.Black;
Brush bgcolor = Brushes.White;
PointF pf = new PointF(5, 5);
Bitmap bitmap = new Bitmap(100, 25);
Rectangle rec = new Rectangle(0, 0, 100, 25);
Graphics gh = Graphics.FromImage(bitmap);
gh.FillRectangle(bgcolor, rec);
gh.DrawString(str, fn, forecolor, pf);
return bitmap;
}
 
private void CreateCheckCodeImage(string checkCode)
{
if (checkCode == null || checkCode.Trim() == String.Empty)
return;
int iWordWidth = 15;
int iImageWidth = checkCode.Length * iWordWidth;
Bitmap image = new Bitmap(iImageWidth, 20);
Graphics g = Graphics.FromImage(image);
try
{
//生成随机生成器 
Random random = new Random();
//清空图片背景色 
g.Clear(Color.White);
 
//画图片的背景噪音点
for (int i = 0; i < 20; 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);
}
 
//画图片的背景噪音线 
for (int i = 0; i < 2; i++)
{
 int x1 = 0;
 int x2 = image.Width;
 int y1 = random.Next(image.Height);
 int y2 = random.Next(image.Height);
 if (i == 0)
 {
 g.DrawLine(new Pen(Color.Gray, 2), x1, y1, x2, y2);
 }
 
}
 
 
for (int i = 0; i < checkCode.Length; i++)
{
 
 string Code = checkCode[i].ToString();
 int xLeft = iWordWidth * (i);
 random = new Random(xLeft);
 int iSeed = DateTime.Now.Millisecond;
 int iValue = random.Next(iSeed) % 4;
 if (iValue == 0)
 {
 Font font = new Font("Arial", 13, (FontStyle.Bold | System.Drawing.FontStyle.Italic));
 Rectangle rc = new Rectangle(xLeft, 0, iWordWidth, image.Height);
 LinearGradientBrush brush = new LinearGradientBrush(rc, Color.Blue, Color.Red, 1.5f, true);
 g.DrawString(Code, font, brush, xLeft, 2);
 }
 else if (iValue == 1)
 {
 Font font = new System.Drawing.Font("楷体", 13, (FontStyle.Bold));
 Rectangle rc = new Rectangle(xLeft, 0, iWordWidth, image.Height);
 LinearGradientBrush brush = new LinearGradientBrush(rc, Color.Blue, Color.DarkRed, 1.3f, true);
 g.DrawString(Code, font, brush, xLeft, 2);
 }
 else if (iValue == 2)
 {
 Font font = new System.Drawing.Font("宋体", 13, (System.Drawing.FontStyle.Bold));
 Rectangle rc = new Rectangle(xLeft, 0, iWordWidth, image.Height);
 LinearGradientBrush brush = new LinearGradientBrush(rc, Color.Green, Color.Blue, 1.2f, true);
 g.DrawString(Code, font, brush, xLeft, 2);
 }
 else if (iValue == 3)
 {
 Font font = new System.Drawing.Font("黑体", 13, (System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Bold));
 Rectangle rc = new Rectangle(xLeft, 0, iWordWidth, image.Height);
 LinearGradientBrush brush = new LinearGradientBrush(rc, Color.Blue, Color.Green, 1.8f, true);
 g.DrawString(Code, font, brush, xLeft, 2);
 }
}
//////画图片的前景噪音点 
//for (int i = 0; i < 8; 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.BinaryWrite(ms.ToArray());
}
finally
{
g.Dispose();
image.Dispose();
}
}
로그인 후 복사

More.net 확인 코드 생성 및 사용법 관련 글은 PHP 중국어 홈페이지를 참고해주세요!

관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
최신 이슈
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!