PDA

View Full Version : آموزش: تصویر امنیتی بسیار ساده و کاربردی Captcha



FirstLine
دوشنبه 15 فروردین 1390, 14:24 عصر
با سلام
یه تصویر امنیتی بسیار ساده و کارآمد برای استفاده

روش استفاده :
1- کافیه که یک فایل Captcha.aspx معمولی بدون مستر پیج ایجاد کرده و بجز خط تعریف صفحه (دایرکتیو) در قسمت html بقیه را پاک کنیم.
2- در قسمت CodeBehind کد های زیر را قرار دهید:


using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;

----------------------------

void Create_captha()
{
string str_Salt = ConfigurationSettings.AppSettings["Salt"].ToString(); // عبارتی که میتوانیم بعنوان کلیدی یا سالت استفاده کنیم و مقدار ان را از داخل وبکانفیگ بخواند
int int_Captch_Length = 5; //طول رشته ومتن
System.Drawing.Bitmap objBmp = new System.Drawing.Bitmap(80, 28); // طول و عرض عکس
System.Drawing.Graphics objGraphics = System.Drawing.Graphics.FromImage(objBmp);
objGraphics.Clear(System.Drawing.Color.Green);
objGraphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
System.Drawing.Font objFont = new System.Drawing.Font("tahoma", 14, System.Drawing.FontStyle.Regular); / اندازه و فونت
string strRandom = "";
string[] strArray = new string[34];
strArray = new string[] { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "1", "2", "3", "4", "5", "6", "7", "8", "9" }; Random autoRand = new Random();
int x;
for (x = 0; x < int_Captch_Length; x++)
{
int i = Convert.ToInt32(autoRand.Next(0, 34));
strRandom += strArray[i].ToString();
}


Session.Add("Simpa_strRandom", str_Salt + strRandom);
objGraphics.DrawString(strRandom, objFont, System.Drawing.Brushes.White, 6, 3);
Response.ContentType = "image/GIF";
objBmp.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Gif);
objFont.Dispose();
objGraphics.Dispose();
objBmp.Dispose();
}
protected void Page_Load(object sender, EventArgs e)
{
Create_captha();

}


3- برای قراردادن در صفحات کافیست کد زیر را قرار دهیم:


<asp:Image ID="img_CP" runat="server" />


در کد صفحه لاگین کد زیر را قرار دهید:



protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
img_CP.ImageUrl = "/Include/Captcha.aspx?" + DateTime.Now.ToString("HHmmss").ToString();
}
}


4- برای استفاده کافیست مقدار سیشن را خوانده و عبارت کلیدی یا سالت را از آن حذف کرده و مقایسه کنید



if (Session["Simpa_strRandom"] != null)
{
string str_Salt = ConfigurationSettings.AppSettings["Simpa_Salt"].ToString();
str_Captcha = Session["Simpa_strRandom"].ToString();


string str_Temp = str_Captcha.Replace(str_Salt, "");
if (txt_CP.Text == str_Temp)
{
bol_IsValid = true;
txt_CP.Text = "";
Session["Simpa_strRandom"] = "Heidarnia.com";
}
}


لطفا نظرات و پیشنهادات خودتونو جهت بهینه تر شدن اعلام بفرمایید.

با تشکر