[Help]Vb.net - Captcha's

xShivam

Registered Member
Joined
Apr 28, 2012
Messages
75
Reaction score
18
I know how to link a text box with a webpage, and everything, its just that i can't get a captcha into a picture box or a webpage. so far in my GMail account creator I've managed to load the webpage :), but i don't know how to grab the captcha image url. any help would be appreciated :)
 
Sub 1:
Code:
' Process Captcha
    Friend Sub Process_Captcha(ByRef CaptchaFormSync As Object, ByRef a_Process As HttpObject, ByVal Username As String)
        ' Variables
        Dim DecaptcherSession As New Decaptcher
        Dim DeathByCaptchaSession As New DeathByCaptcha
        Dim URL As String
        Dim Data As String
        Dim Content As String
        Dim CaptchaChallengeKey As String = ""
        Dim CaptchaImageURL As String = ""
        Dim CaptchaAnswer As String = ""
        ' Check Captcha Settings
        If My.Settings.CaptchaSetting = "Manual Entry" Then
            ' Get Captcha Image URL
            Dim CaptchaAnswerDetails() As String = GetCaptcha(a_Process)
            CaptchaImageURL = CaptchaAnswerDetails(0)
            CaptchaChallengeKey = CaptchaAnswerDetails(1)
            ' Display Captcha Image To User For Entry
            SyncLock CaptchaFormSync
                CaptchaEntry.PictureBox1.Image = New System.Drawing.Bitmap(New IO.MemoryStream(New System.Net.WebClient().DownloadData(CaptchaImageURL)))
                CaptchaEntry.ShowDialog()
                CaptchaAnswer = CaptchaEntry.TextBox1.Text
            End SyncLock
            ' Confirm Captcha Entered
            If CaptchaAnswer = "" Then Throw New Exception("Captcha Not Entered")
        ElseIf My.Settings.CaptchaSetting = "De-Captcher.com" Then
            ' Get Captcha Image URL
            Try
                Dim CaptchaAnswerDetails() As String = GetCaptcha(a_Process)
                CaptchaImageURL = CaptchaAnswerDetails(0)
                CaptchaChallengeKey = CaptchaAnswerDetails(1)
            Catch ex As Exception
                Throw New Exception("Failed To Download Captcha Image: " & ex.Message)
            End Try
            ' Download Image To Hard Drive
            Try
                a_Process.GetImage(CaptchaImageURL, Username)
            Catch ex As Exception
                Throw New Exception("Failed To Download Captcha Image: " & ex.Message)
            End Try
            ' Get Captcha Answer
            Try
                CaptchaAnswer = DecaptcherSession.PostCaptcha(My.Application.Info.DirectoryPath & "\datastore\captchas\" & Username & ".jpg")
            Catch ex As Exception
                Throw New Exception("Failed To Send Captcha Image To De-Captcher: " & ex.Message)
            End Try
            ' Delete Image
            Try
                File.Delete(My.Application.Info.DirectoryPath & "\datastore\captchas\" & Username & ".jpg")
            Catch ex As Exception

            End Try
            ' Confirm Response
            If CaptchaAnswer = Nothing OrElse CaptchaAnswer = "" Then
                Throw New Exception("De-Captcher Did Not Respond To The Captcha Request")
            End If
            AddMessage("De-Captcher Returned Answer: " & CaptchaAnswer)
        ElseIf My.Settings.CaptchaSetting = "DeathByCaptcha.com" Then
            ' Get Captcha Image URL
            Try
                Dim CaptchaAnswerDetails() As String = GetCaptcha(a_Process)
                CaptchaImageURL = CaptchaAnswerDetails(0)
                CaptchaChallengeKey = CaptchaAnswerDetails(1)
            Catch ex As Exception
                Throw New Exception("Failed To Download Captcha Image: " & ex.Message)
            End Try
            ' Download Image To Hard Drive
            Try
                a_Process.GetImage(CaptchaImageURL, Username)
            Catch ex As Exception
                Throw New Exception("Failed To Download Captcha Image: " & ex.Message)
            End Try
            ' Get Captcha Answer
            Try
                CaptchaAnswer = DeathByCaptchaSession.PostCaptcha(My.Application.Info.DirectoryPath & "\datastore\captchas\" & Username & ".jpg")
            Catch ex As Exception
                Throw New Exception("Failed To Send Captcha Image To DeathByCaptcha: " & ex.Message)
            End Try
            ' Delete Image
            Try
                File.Delete(My.Application.Info.DirectoryPath & "\datastore\captchas\" & Username & ".jpg")
            Catch ex As Exception

            End Try
            ' Confirm Response
            If CaptchaAnswer = Nothing OrElse CaptchaAnswer = "" Then
                Throw New Exception("DeathByCaptcha Did Not Respond To The Captcha Request")
            End If
            AddMessage("DeathByCaptcha Returned Answer: " & CaptchaAnswer)
        ElseIf My.Settings.CaptchaSetting = "Skip Captcha Requests" Then
            Throw New Exception("Captcha Required To Login To Account, (Setting: Skip Captcha Requests). Skipping Account")
        End If
        ' Handle Captcha & Pass Details Onto Webpage

        ' ADD CODE HERE

        ' Check For Bad Captcha
        If Content.Contains("incorrect-captcha-sol") Then
            If My.Settings.CaptchaSetting = "De-Captcher.com" Then
                Try
                    DecaptcherSession.BadCaptcha()
                Catch ex As Exception
                    Throw New Exception("Decaptcher Refund Failed: " & ex.Message)
                End Try
                Throw New Exception("Captcha Failed, De-Captcher Refund Requested. (Answer: " & CaptchaAnswer & ")")
            ElseIf My.Settings.CaptchaSetting = "DeathByCaptcha.com" Then
                Try
                    DeathByCaptchaSession.BadCaptcha()
                Catch ex As Exception
                    Throw New Exception("DeathByCaptcha Refund Failed: " & ex.Message)
                End Try
                Throw New Exception("Captcha Failed, DeathByCaptcha Refund Requested. (Answer: " & CaptchaAnswer & ")")
            End If
            Throw New Exception("Incorrect Captcha Entry")
        End If
    End Sub

CaptchaEntry.vb (Add Textbox1, PictureBox1, Button1):
Code:
Public Class CaptchaEntry

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Me.Close()
    End Sub

    Private Sub CaptchaEntry_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        TextBox1.Text = ""
    End Sub
End Class

Decaptcher Class:
Code:
Imports System
Imports System.Text
Imports System.IO
Imports System.Net

Class Decaptcher

    Private username As String = My.Settings.DecaptcherUser
    Private password As String = My.Settings.DecaptcherPass

    Private resultCode As String = ""
    Private majorId As String = ""
    Private minorId As String = ""
    Private type As String = ""
    Private timeout As String = ""

    Public Function PostCaptcha(ByVal FilePath As String) As String
        Dim captcha As System.Drawing.Image
        Dim fs As New System.IO.FileStream(FilePath, System.IO.FileMode.Open)
        captcha = Image.FromStream(fs)

        Dim captchaResponse As String = ""
        Dim boundary As String = "myBoundary"
        Dim builder As New StringBuilder()

        builder.Append("--" & boundary & vbCr & vbLf & "Content-Disposition: form-data; name=")
        builder.Append("""function""")
        builder.Append(vbCr & vbLf & vbCr & vbLf)
        builder.Append("picture2")
        builder.Append(vbCr & vbLf)

        builder.Append("--" & boundary & vbCr & vbLf & "Content-Disposition: form-data; name=")
        builder.Append("""username""")
        builder.Append(vbCr & vbLf & vbCr & vbLf)
        builder.Append(username)
        builder.Append(vbCr & vbLf)

        builder.Append("--" & boundary & vbCr & vbLf & "Content-Disposition: form-data; name=")
        builder.Append("""password""")
        builder.Append(vbCr & vbLf & vbCr & vbLf)
        builder.Append(password)
        builder.Append(vbCr & vbLf)

        builder.Append("--" & boundary & vbCr & vbLf & "Content-Disposition: form-data; name=")
        builder.Append("""pict_to""")
        builder.Append(vbCr & vbLf & vbCr & vbLf)
        builder.Append("0")
        builder.Append(vbCr & vbLf)

        builder.Append("--" & boundary & vbCr & vbLf & "Content-Disposition: form-data; name=")
        builder.Append("""pict_type""")
        builder.Append(vbCr & vbLf & vbCr & vbLf)
        builder.Append("0")
        builder.Append(vbCr & vbLf)

        builder.Append("--" & boundary & vbCr & vbLf & "Content-Disposition: form-data; name=")
        builder.Append("""pict""; filename=captcha.jpg")
        builder.Append(vbCr & vbLf)
        builder.Append("Content-Type: image/jpeg")
        builder.Append(vbCr & vbLf & vbCr & vbLf)

        Dim headerBytes As Byte() = Encoding.ASCII.GetBytes(builder.ToString())

        Dim ms As New MemoryStream()
        captcha.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg)

        Dim imageBytes As Byte() = ms.ToArray()

        Dim footerBytes As Byte() = Encoding.ASCII.GetBytes((vbCr & vbLf & "--") + boundary)

        Dim postBytes As Byte() = New Byte(headerBytes.Length + imageBytes.Length + (footerBytes.Length - 1)) {}

        Buffer.BlockCopy(headerBytes, 0, postBytes, 0, headerBytes.Length)
        Buffer.BlockCopy(imageBytes, 0, postBytes, headerBytes.Length, imageBytes.Length)
        Buffer.BlockCopy(footerBytes, 0, postBytes, headerBytes.Length + imageBytes.Length, footerBytes.Length)

        Try
            Dim req As HttpWebRequest = DirectCast(WebRequest.Create("http://poster.de-captcher.com/"), HttpWebRequest)
            req.Proxy = Nothing
            req.Method = "POST"
            req.ContentType = "multipart/form-data; boundary=" & boundary
            req.ContentLength = postBytes.Length
            req.ServicePoint.Expect100Continue = False
            ' req.Timeout = 30000

            Using reqStream As Stream = req.GetRequestStream()
                reqStream.Write(postBytes, 0, postBytes.Length)
            End Using
            Using resp As WebResponse = req.GetResponse()
                Using respStream As Stream = resp.GetResponseStream()
                    Using read As New StreamReader(respStream)
                        captchaResponse = read.ReadToEnd()
                    End Using
                End Using
            End Using

            Dim respValues As String() = captchaResponse.Split("|"c)
            resultCode = respValues(0)
            majorId = respValues(1)
            minorId = respValues(2)
            type = respValues(3)
            timeout = respValues(4)
            captchaResponse = respValues(5)
            fs.Close()
            Return captchaResponse
        Catch ex As Exception
            If ex.Message.Contains("403") Then Throw New Exception("Incorrect DeCaptcher Login Details")
            If ex.Message.Contains("400") Then Throw New Exception("DeCaptcher Rejected The Captcha Image")
            If ex.Message.Contains("500") Then Throw New Exception("DeCaptcher Server Error Occured")
            If ex.Message.Contains("503") Then Throw New Exception("DeCaptcher Service Is Temporarily Unavailable")
            fs.Close()
            Return captchaResponse
        End Try
        fs.Close()
    End Function

    Public Sub BadCaptcha()
        Dim boundary As String = "myBoundary"

        Dim builder As New StringBuilder()

        builder.Append("--" & boundary & vbCr & vbLf & "Content-Disposition: form-data; name=")
        builder.Append("""function""")
        builder.Append(vbCr & vbLf & vbCr & vbLf)
        builder.Append("picture_bad2")
        builder.Append(vbCr & vbLf)

        builder.Append("--" & boundary & vbCr & vbLf & "Content-Disposition: form-data; name=")
        builder.Append("""username""")
        builder.Append(vbCr & vbLf & vbCr & vbLf)
        builder.Append(username)
        builder.Append(vbCr & vbLf)

        builder.Append("--" & boundary & vbCr & vbLf & "Content-Disposition: form-data; name=")
        builder.Append("""password""")
        builder.Append(vbCr & vbLf & vbCr & vbLf)
        builder.Append(password)
        builder.Append(vbCr & vbLf)

        builder.Append("--" & boundary & vbCr & vbLf & "Content-Disposition: form-data; name=")
        builder.Append("""major_id""")
        builder.Append(vbCr & vbLf & vbCr & vbLf)
        builder.Append(majorId)
        builder.Append(vbCr & vbLf)

        builder.Append("--" & boundary & vbCr & vbLf & "Content-Disposition: form-data; name=")
        builder.Append("""minor_id""")
        builder.Append(vbCr & vbLf & vbCr & vbLf)
        builder.Append(minorId)
        builder.Append(vbCr & vbLf)

        builder.Append("--" & boundary & vbCr & vbLf & "Content-Disposition: form-data; name=")
        builder.Append("""submit""")
        builder.Append(vbCr & vbLf & vbCr & vbLf)
        builder.Append("Send")
        builder.Append(vbCr & vbLf)
        builder.Append("--" & boundary)

        Dim postString As String = builder.ToString()

        Dim req As HttpWebRequest = DirectCast(WebRequest.Create("http://poster.de-captcher.com/"), HttpWebRequest)
        req.Proxy = Nothing
        req.Method = "POST"
        req.ContentType = "multipart/form-data; boundary=" & boundary
        Using reqStream As Stream = req.GetRequestStream()
            reqStream.Write(Encoding.ASCII.GetBytes(postString), 0, postString.Length)
        End Using
        Using resp As WebResponse = req.GetResponse()
            Using respStream As Stream = resp.GetResponseStream()
                Using read As New StreamReader(respStream)
                    Dim result As String = read.ReadToEnd()
                End Using
            End Using
        End Using
    End Sub

End Class

DeathByCaptcha Class:
Code:
Imports System
Imports System.Text
Imports System.IO
Imports System.Net
Imports System.Threading

Class DeathByCaptcha

    Private username As String = My.Settings.DeathByCaptchaUser
    Private password As String = My.Settings.DeathByCaptchaPass
    Private CaptchaID As String = ""

    Public Function Return_Content(ByVal URL As String) As String
        Dim Content As String = Nothing
        Dim request As Net.HttpWebRequest = CType(Net.WebRequest.Create(URL), HttpWebRequest)
        request.Proxy = Nothing
        request.Method = "GET"
        request.Timeout = 10000
        request.AllowAutoRedirect = True
        Dim response As Net.HttpWebResponse = CType(request.GetResponse(), HttpWebResponse)
        If response.StatusCode = Net.HttpStatusCode.OK Then
            Dim responseStream As IO.StreamReader = New IO.StreamReader(response.GetResponseStream())
            Content = responseStream.ReadToEnd()
        End If
        response.Close()
        Return Content
    End Function

    Public Function Post_Content(ByVal URL As String, ByVal Data As String) As String
        Dim encoding As New UTF8Encoding
        Dim byteData As Byte() = encoding.GetBytes(Data)
        Dim Content As String = Nothing
        ' New Request
        System.Net.ServicePointManager.Expect100Continue = False
        Dim request As HttpWebRequest = DirectCast(WebRequest.Create(URL), HttpWebRequest)
        ' Set Proxy Details
        request.Proxy = Nothing
        ' Request Settings
        request.Method = "POST"
        request.ServicePoint.Expect100Continue = False
        request.KeepAlive = False
        request.AllowAutoRedirect = False
        request.Timeout = 20000
        ' Headers
        request.ContentLength = byteData.Length
        request.ContentType = "application/x-www-form-urlencoded"
        ' Read Stream
        Dim postreqstream As Stream = request.GetRequestStream()
        postreqstream.Write(byteData, 0, byteData.Length)
        postreqstream.Close()
        Dim postresponse As HttpWebResponse
        postresponse = DirectCast(request.GetResponse(), HttpWebResponse)
        ' Check HTTP Status
       Dim postreqreader As New StreamReader(postresponse.GetResponseStream())
        Content = postreqreader.ReadToEnd
        ' Close Connection
        postresponse.Close()
        ' Return HTML Content
        If Content = Nothing Then Return "" Else Return Content
    End Function

    Public Function ConvertFileToBase64(ByVal fileName As String) As String
        Dim ReturnValue As String = ""
        If My.Computer.FileSystem.FileExists(fileName) Then
            Using BinaryFile As FileStream = New FileStream(fileName, FileMode.Open)
                Dim BinRead As BinaryReader = New BinaryReader(BinaryFile)
                Dim BinBytes As Byte() = BinRead.ReadBytes(CInt(BinaryFile.Length))
                ReturnValue = Convert.ToBase64String(BinBytes)
                BinaryFile.Close()
            End Using
        End If
        Return ReturnValue
    End Function

    Public Function PostCaptcha(ByVal FilePath As String) As String
        Dim captchaResponse As String = ""
        Dim boundary As String = "-----------------------------" & DateTime.Now.Ticks.ToString("x")
        Dim builder As New StringBuilder()

        builder.Append("--" & boundary & vbCr & vbLf & "Content-Disposition: form-data; name=")
        builder.Append("""username""")
        builder.Append(vbCr & vbLf & vbCr & vbLf)
        builder.Append(username)
        builder.Append(vbCr & vbLf)

        builder.Append("--" & boundary & vbCr & vbLf & "Content-Disposition: form-data; name=")
        builder.Append("""password""")
        builder.Append(vbCr & vbLf & vbCr & vbLf)
        builder.Append(password)
        builder.Append(vbCr & vbLf)

        builder.Append("--" & boundary & vbCr & vbLf & "Content-Disposition: form-data; name=")
        builder.Append("""captchafile""; filename=captcha.jpg")
        builder.Append(vbCr & vbLf & vbCr & vbLf)
        builder.Append("base64:" & ConvertFileToBase64(FilePath))
        builder.Append(vbCr & vbLf)

        Dim headerBytes As Byte() = Encoding.ASCII.GetBytes(builder.ToString())

        Dim footerBytes As Byte() = Encoding.ASCII.GetBytes((vbCr & vbLf & boundary & "--"))

        Dim postBytes As Byte() = New Byte(headerBytes.Length + (footerBytes.Length - 1)) {}

        Buffer.BlockCopy(headerBytes, 0, postBytes, 0, headerBytes.Length)
        Buffer.BlockCopy(footerBytes, 0, postBytes, headerBytes.Length, footerBytes.Length)

        Try
            Dim req As HttpWebRequest = DirectCast(WebRequest.Create("http://api.dbcapi.me/api/captcha"), HttpWebRequest)
            ' req.Proxy = Nothing
            req.Method = "POST"
            req.ContentType = "multipart/form-data; boundary=" & boundary
            req.ContentLength = postBytes.Length
            req.ServicePoint.Expect100Continue = False
            req.AllowAutoRedirect = False
            ' req.Timeout = 30000

            Using reqStream As Stream = req.GetRequestStream()
                reqStream.Write(postBytes, 0, postBytes.Length)
            End Using
            Using resp As WebResponse = req.GetResponse()
                Using respStream As Stream = resp.GetResponseStream()
                    Using read As New StreamReader(respStream)
                        captchaResponse = read.ReadToEnd()
                    End Using
                End Using
            End Using
            Dim TempResponse As String = GetBetween(captchaResponse, "&captcha=", "&")
            If TempResponse = Nothing Then Throw New Exception("Could Not Parse Response From DeathByCaptcha")
            CaptchaID = TempResponse
            ' Go Captcha ID Now Go To Status Page
            Dim CaptchaAnswer As String = ""
            For i = 0 To 10
                Dim Content As String = Return_Content("http://api.dbcapi.me/api/captcha/" & CaptchaID)
                CaptchaAnswer = GetBetween(Content, "&text=", "&")
                If CaptchaAnswer <> Nothing Then
                    CaptchaAnswer = CaptchaAnswer.Replace("+", " ")
                    Exit For
                Else
                    Thread.Sleep(2000)
                End If
            Next
            If CaptchaAnswer = Nothing Then Throw New Exception("DeathByCaptcha Exceeded 20 Second Time Limit. Skipping Captcha Request")
            Return CaptchaAnswer
        Catch ex As Exception
            If ex.Message.Contains("403") Then Throw New Exception("Incorrect DeathByCaptcha Login Details")
            If ex.Message.Contains("400") Then Throw New Exception("DeathByCaptcha Rejected The Captcha Image")
            If ex.Message.Contains("500") Then Throw New Exception("DeathByCaptcha Server Error Occured")
            If ex.Message.Contains("503") Then Throw New Exception("DeathByCaptcha Service Is Temporarily Unavailable")
            Throw New Exception(ex.Message)
        End Try

    End Function

    Public Sub BadCaptcha()
        Post_Content("http://api.dbcapi.me/api/captcha/" & CaptchaID & "/report", "username=" & username & "&password=" & password)
    End Sub

End Class

GetCaptcha Function (Change The Key To The Site's Recaptcha Key, Can be found in the page's HTML source):
Code:
' Get ReCaptcha Image & Challenge Key
    Friend Function GetCaptcha(ByRef a_Process As CurlFunctions) As String()
        ' Variables
        Dim RecaptchaKey As String = "SITES-RECAPTCHA-KEY"
        Dim CaptchaImageURL As String
        Dim URL As String
        Dim Content As String
        ' Generate CacheStop
        Dim CacheStop As String = "0." & GetRandomNumber(111111, 999999999)
        ' Load Challenge URL
        URL = "http://www.google.com/recaptcha/api/challenge?k=" & RecaptchaKey & "&ajax=1&cachestop=" & CacheStop
        Try
            Content = a_Process.Get_URL(URL)
        Catch ex As Exception
            Throw New Exception("Failed To Load Recaptcha Challenge URL: " & ex.Message)
        End Try
        ' Scrape Challenge Key
        Dim ChallengeKey As String = GetBetween(Content, "challenge : '", "'")
        ' Confirm ChallengeKey Exists
        If ChallengeKey = Nothing Then
            If Form1.AdminMode = True Then Log_Show_Error(Content)
            Throw New Exception("Failed To Scrape Challenge Key, Unknown Issue")
        End If
        ' Form Captcha Image URL
        CaptchaImageURL = "http://www.google.com/recaptcha/api/image?c=" & ChallengeKey
        ' Form Array
        Dim Keys() As String = {CaptchaImageURL, ChallengeKey}
        ' Return Captcha Image URL
        Return Keys
    End Function

GetRandomNumber Function:
Code:
' Get Random Number Function
    Dim objRandom As New System.Random(CType(System.DateTime.Now.Ticks Mod System.Int32.MaxValue, Integer))
    Public Function GetRandomNumber(Optional ByVal Low As Integer = 1, Optional ByVal High As Integer = 100) As Integer
        Return objRandom.Next(Low, High + 1)
    End Function
 
Damn nice post gimme4free!!!! Wish I had that type support on my old captcha questions.

I use this code a lot for my recpatcha captcha's.

Code:
Sub getcaptcha()

        If WebBrowser1.ReadyState = WebBrowserReadyState.Complete Then

            For Each Captcha As HtmlElement In WebBrowser1.Document.Images

                If Captcha.GetAttribute("src").Contains("http://www.google.com/recaptcha/api/image?c=") Then
                    PictureBox1.Load(Captcha.GetAttribute("src"))

                End If

            Next
        End If
    End Sub

Then I call the sub into the webbrowsers document completed area like so

Code:
    Private Sub WebBrowser1_DocumentCompleted(ByVal sender As System.Object, ByVal e As System.Windows.Forms.WebBrowserDocumentCompletedEventArgs) Handles WebBrowser1.DocumentCompleted
        call getcaptcha()
    End Sub
 
Last edited:
xD well i've never got around to actually learn vh.net i started because of PPD's.

Anyway, thanks alot :)

Sent from my SA3CNT using Tapatalk 2
 
Last edited:
Back
Top