> Manuales > Taller de ASP.NET

Con este truco podrás crear rápidamente un sistema de código de seguridad para tu página web.

Para crear un código de seguridad seguiremos los siguientes pasos:

Tenemos que agregar en el formulario que deseamos insertar el código de seguridad los siguientes controles:

En el código VB de la página del registro declararemos una variable llamada bAntiBots

#Region "Members"
Dim bAntiBots As Boolean = False
#End Region


En el Page_Load:

If Not IsPostBack Then
Session("AntiBots") = GenerateRandomCode()
Else
'Comprobamos el código antibots
If frm_Codigo_Seguridad.Value = Session("AntiBots").ToString() Then
bAntiBots = True
Else
bAntiBots = False
Me.Session("AntiBots") = GenerateRandomCode()
End If
End If


Tenemos que crear la función GenerateRandomCode para generar un código de seguridad al azar

#Region "GenerateRandomCode"

Private Function GenerateRandomCode() As String
Dim random As New Random
Dim s As String = ""
Dim i As Int32 = 0
Dim iChr As Int32

While (i <; 6)
iChr = random.Next(48, 90)
While iChr >; 57 And iChr <; 65
iChr = random.Next(48, 90)
End While
s = String.Concat(s, Chr(iChr).ToString())
i = i + 1
End While
Return s
End Function
#End Region


Para seguir, nos faltará crear la clase encargada de crear, manipular y deformar el código de seguridad generado en imagen

Imports System
Imports System.Drawing
Imports System.Drawing.Drawing2D
Imports System.Drawing.Imaging
Imports System.Drawing.Text

Public Class ImagenAntiBots

Dim m_text As String
Dim m_width As Int32
Dim m_height As Int32
Dim m_familyName As String
Dim m_image As Bitmap
Dim m_random As New Random
#Region "Propiedades de lectura"

Public ReadOnly Property Text() As String
Get
Return m_text
End Get
End Property

Public ReadOnly Property Width() As Int32
Get
Return m_width
End Get
End Property

Public ReadOnly Property Height() As Int32
Get
Return m_height
End Get
End Property

Public ReadOnly Property Image() As Bitmap
Get
Return m_image
End Get
End Property

#End Region

Public Sub New(ByVal s As String, ByVal width As Int32, ByVal height As Int32)
Me.m_text = s
Me.SetDimensions(width, height)
Me.GenerateImage()
End Sub

Public Sub New(ByVal s As String, ByVal width As Int32, ByVal height As Int32, ByVal familyName As String)

Me.m_text = s
Me.SetDimensions(width, height)
Me.SetFamilyName(familyName)
Me.GenerateImage()
End Sub

Private Sub SetDimensions(ByVal width As Int32, ByVal height As Int32)
If width <;= 0 Then
Throw New ArgumentOutOfRangeException("width", width, "Argument out of range, must be greater than zero.")
End If
If (height <;= 0) Then
Throw New ArgumentOutOfRangeException("height", height, "Argument out of range, must be greater than zero.")
End If

Me.m_width = width
Me.m_height = height

End Sub

Private Sub SetFamilyName(ByVal familyName As String)
Try
Dim font As Font = New Font(familyName, 12.0F)
Me.m_familyName = familyName
font.Dispose()

Catch ex As Exception
Me.m_familyName = System.Drawing.FontFamily.GenericSerif.Name
End Try
End Sub

Private Sub GenerateImage()
Dim bitmap As New Bitmap(Me.m_width, Me.m_height, PixelFormat.Format32bppArgb)

'Creamos objeto grafico
Dim g As Graphics = Graphics.FromImage(bitmap)
g.SmoothingMode = SmoothingMode.AntiAlias
Dim rect As New RectangleF(0, 0, Me.m_width, Me.m_height)

'Rellenamos el fondo
Dim hatchBrush As New HatchBrush(HatchStyle.SmallConfetti, Color.LightGray, Color.White)
g.FillRectangle(hatchBrush, rect)

'Establecemos la fuente
Dim size As SizeF
Dim fontSize As Single = rect.Height + 1
Dim font As Font
'Ajusta el tamaño de la fuente

Do
fontSize = fontSize - 1
font = New Font(Me.m_familyName, fontSize, FontStyle.Bold)
size = g.MeasureString(Me.m_text, font)
Loop While (size.Width >; rect.Width)

'Establece el formato de texto
Dim format As New StringFormat
format.Alignment = StringAlignment.Center
format.LineAlignment = StringAlignment.Center

Dim path As New GraphicsPath
path.AddString(Me.m_text, font.FontFamily, CType(font.Style, Int32), font.Size, rect, format)
Dim v As Single = 4.0F

Dim points As System.Drawing.PointF() = { _
New System.Drawing.PointF(m_random.Next(CType(rect.Width, Integer)) / v, m_random.Next(CType(rect.Height, Integer)) / v), _
New System.Drawing.PointF(rect.Width - m_random.Next(CType(rect.Width, Integer)) / v, m_random.Next(CType(rect.Height, Integer)) / v), _
New System.Drawing.PointF(m_random.Next(CType(rect.Width, Integer)) / v, rect.Height - m_random.Next(CType(rect.Height, Integer)) / v), _
New System.Drawing.PointF(rect.Width - m_random.Next(CType(rect.Width, Integer)) / v, rect.Height - m_random.Next(CType(rect.Height, Integer)) / v)}

Dim matrix As New Matrix
matrix.Translate(1, 3)

'Deformamos la imagen
path.Warp(points, rect, matrix, 0)

'Dibuja el texto
hatchBrush = New HatchBrush(HatchStyle.OutlinedDiamond, Color.Orange, Color.BlueViolet)
g.FillPath(hatchBrush, path)
'Añade efectos
Dim m As Int32 = Math.Max(CType(rect.Width, Integer), CType(rect.Height, Integer))
Dim i As Int32 = 0
While i <; CType((rect.Width * rect.Height / 30.0F), Int32)
Dim x As Int32 = m_random.Next(CType(rect.Width, Integer))
Dim y As Int32 = m_random.Next(CType(rect.Height, Integer))
Dim w As Int32 = m_random.Next(CType(m / 50, Integer))
Dim h As Int32 = m_random.Next(CType(m / 50, Integer))
g.FillEllipse(hatchBrush, x, y, w, h)
i = i + 1
End While

font.Dispose()
hatchBrush.Dispose()
g.Dispose()

'Establece la imagen
Me.m_image = bitmap

End Sub

End Class


Ahora en el proyecto crearemos la página que apunta nuestra imagen (el primer control que hemos agregado en el proyecto, y en el Page_Load pondremos este código:

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'Creamos una imagen creando el texto guardado en la sesion
Dim ab As New ImagenAntiBots(Session("AntiBots").ToString(), 200, 50, "Arial")

'Cambiamos la respuesta al cliente a tipo "imagen/jpeg"
Me.Response.Clear()
Me.Response.ContentType = "image/jpeg"

'Salvamos la imagen en el Response
ab.Image.Save(Me.Response.OutputStream, ImageFormat.Jpeg)
End Sub


Y para terminar, en el formulario del registro, dónde hemos agregado los controles, en el botón del submit, utilizar esta condición:

If bAntiBots Then
' Creamos el registro
Else
' El código de seguridad no está bien colocado
End if

Puedes descargarte todo el código fuente de pulsando aquí.

Pol Salvat

Manual