Autor Tema: SOLUCIONADO - cSocketMaster y HTTPS  (Leído 6142 veces)

0 Usuarios y 1 Visitante están viendo este tema.

Jeronimo

  • Gigabyte
  • ****
  • Mensajes: 402
  • Reputación: +33/-2
    • Ver Perfil
SOLUCIONADO - cSocketMaster y HTTPS
« en: Noviembre 08, 2016, 09:47:19 am »
Hola.
Estoy usando la clase cSocketMaster para descargar una serie de archivos de imágenes de internet. Hasta ahora venía andando perfectamente, pero recientemente movieron todo a una dirección HTTPS y mi aplicación no puede descargar más los archivos.
Si copio el enlace en el Internet Explorer me devuelve el siguiente cartel:
"Existe un problema con el certificado de seguridad de este sitio web.
El certificado de seguridad de este sitio web no fue emitido por una entidad de certificación de confianza.
Este sitio web presentó un certificado de seguridad emitido para una dirección de sitio web diferente."
También me da la opción de continuar y finalmente me muestra la imagen en pantalla, pero en mi aplicación no me permite continuar.
Agregué la dirección en los sitios de confianza de las propiedades de internet del IE pero sigue dando este problema.
¿Saben si puedo modificar algo para poder seguir descargando los archivos?
¡Muchas gracias!

Jerónimo
« última modificación: Noviembre 14, 2016, 01:23:15 pm por Jeronimo »

obethermy

  • Megabyte
  • ***
  • Mensajes: 116
  • Reputación: +6/-7
    • Ver Perfil
Re:cSocketMaster y HTTPS
« Respuesta #1 en: Noviembre 08, 2016, 10:39:30 am »
configuralo para certificado ssl si la pagina trabaja con este certificado.

Jeronimo

  • Gigabyte
  • ****
  • Mensajes: 402
  • Reputación: +33/-2
    • Ver Perfil
Re:cSocketMaster y HTTPS
« Respuesta #2 en: Noviembre 08, 2016, 10:48:19 am »
¿Sabés cómo se hace?
Muchas gracias.

obethermy

  • Megabyte
  • ***
  • Mensajes: 116
  • Reputación: +6/-7
    • Ver Perfil
Re:cSocketMaster y HTTPS
« Respuesta #3 en: Noviembre 08, 2016, 05:00:05 pm »

Jeronimo

  • Gigabyte
  • ****
  • Mensajes: 402
  • Reputación: +33/-2
    • Ver Perfil
Re:cSocketMaster y HTTPS
« Respuesta #4 en: Noviembre 08, 2016, 05:11:03 pm »
Perdón por la ignorancia, pero, ¿qué consigo con eso?
Allí dice que los certificados son correctos y están vigentes. ¿Qué debo hacer ahora?
Muchas gracias.

Jerónimo

obethermy

  • Megabyte
  • ***
  • Mensajes: 116
  • Reputación: +6/-7
    • Ver Perfil
Re:cSocketMaster y HTTPS
« Respuesta #5 en: Noviembre 08, 2016, 06:15:37 pm »
CONFIGURA el cSocketMaster para trabajar con ssl

Waldo

  • Gigabyte
  • ****
  • Mensajes: 264
  • Reputación: +22/-0
    • Ver Perfil
Re:cSocketMaster y HTTPS
« Respuesta #6 en: Noviembre 09, 2016, 12:01:06 am »
Hmm no creo que ese módulo de clase permita usar ssl, es un módulo que realizó alguien, para reemplazar el viejo control ms winsock. Por empezar http usa el puerto 80, https usa otro puerto

LeandroA

  • Administrador
  • Petabyte
  • *****
  • Mensajes: 1128
  • Reputación: +151/-8
    • Ver Perfil
Re:cSocketMaster y HTTPS
« Respuesta #7 en: Noviembre 09, 2016, 12:55:45 am »
pienso lo mismo que Waldo, de todas formas ha otros métodos de descarga sin tener que utilizar cSocketMaster y son compatibles con ssl ahora con un conflicto de certificado no estoy muy seguro que pasaría. si no encontras algun metodos de descarga avisa o busca bien aca en el foro hay una clase que hizo Coco en la sección de Aportes.

Jeronimo

  • Gigabyte
  • ****
  • Mensajes: 402
  • Reputación: +33/-2
    • Ver Perfil
Re:cSocketMaster y HTTPS
« Respuesta #8 en: Noviembre 09, 2016, 08:12:27 am »
¡Genial!
Uso esa clase porque venía con un ejemplo (supongo que lo habrá hecho alguno de ustedes, porque de aquí es de donde me nutro casi en la totalidad) donde en un listview se veía la progresión de la descarga. Podría utilizar cualquiera sin problema.
Voy a buscar la clase de Coco.
¡Muchas gracias!

Jerónimo

obethermy

  • Megabyte
  • ***
  • Mensajes: 116
  • Reputación: +6/-7
    • Ver Perfil
Re:cSocketMaster y HTTPS
« Respuesta #9 en: Noviembre 09, 2016, 11:55:27 am »
Este es un ejemplo usando winsock que tenia en mi baul espero que te sirva


Agregar en proyectos componentes microsoft winsock control 6.0
un fromulario con dos commandbutton(enviar datos,conectar a servidor) y 3 textbox(text1 multiline a true y scrollbar vertical) y un winsock

Código: (VB) [Seleccionar]
Option Explicit
Private Sub Command2_Click()
    'Send Encrypted Record if Ready
    If Layer = 3 Then
        Call SSLSend(Winsock1, Text2.Text & vbCrLf)
        Text2.Text = ""
    End If
End Sub
Private Sub Text3_Change()
    'Update Text2.Text to match the hostname
    Text2.Text = "GET https://" & Text3.Text & "/"
End Sub
' Modified by Seth Taylor 2005-02-22 to buffer incoming data and process appropriately
Private Sub Winsock1_DataArrival(ByVal bytesTotal As Long)
    Dim TheData As String
    Dim Response As String
    Response = ""
   
    ' Buffer incoming data while connection is open or being opened
    If Layer < 4 Then
        Call Winsock1.GetData(TheData, vbString, bytesTotal)
        DataBuffer = DataBuffer & TheData
    End If
   
    If Layer = 3 Then
        ' Download complete response before processing
        Exit Sub
    End If
   
    'Parse each SSL Record
    Do
   
        If SeekLen = 0 Then
            If Len(DataBuffer) >= 2 Then
                TheData = GetBufferDataPart(2)
                SeekLen = BytesToLen(TheData)
            Else
                Exit Sub
            End If
        End If
       
        If Len(DataBuffer) >= SeekLen Then
            TheData = GetBufferDataPart(SeekLen)
        Else
            Exit Sub
        End If
       
       
        Select Case Layer
            Case 0:
                ENCODED_CERT = Mid(TheData, 12, BytesToLen(Mid(TheData, 6, 2)))
                CONNECTION_ID = Right(TheData, BytesToLen(Mid(TheData, 10, 2)))
                Call IncrementRecv
                Call SendMasterKey(Winsock1)
            Case 1:
                TheData = SecureSession.RC4_Decrypt(TheData)
                If Right(TheData, Len(CHALLENGE_DATA)) = CHALLENGE_DATA Then
                    If VerifyMAC(TheData) Then
                        Call SendClientFinish(Winsock1)
                    Else
                        ' SSL Error -- send SSL error to server
                        MsgBox ("SSL Error: Invalid MAC data ... aborting connection.")
                        Winsock1.Close
                    End If
                Else
                    ' SSL Error -- send SSL error to server
                    MsgBox ("SSL Error: Invalid Challenge data ... aborting connection.")
                    Winsock1.Close
                End If
             Case 2:
                TheData = SecureSession.RC4_Decrypt(TheData)
                If VerifyMAC(TheData) = False Then
                    ' SSL Error -- send SSL error to server
                    MsgBox ("SSL Error: Invalid MAC data ... aborting connection.")
                    Winsock1.Close
                End If
                Layer = 3
             Case 3:
                ' Do nothing while buffer is filled ... wait for connection to close
             Case 4:
                TheData = SecureSession.RC4_Decrypt(TheData)
                If VerifyMAC(TheData) Then
                    Response = Response & Mid(TheData, 17)
                Else
                    ' SSL Error -- data is corrupt and must be discarded
                    MsgBox ("SSL Error: Invalid MAC data ... Data discarded.")
                    Layer = 0
                    DataBuffer = ""
                    Response = ""
                    Exit Sub
                End If
        End Select
   
        SeekLen = 0

    Loop Until Len(DataBuffer) = 0
   
    If Layer = 4 Then
        Layer = 0
        Call ProcessData(Response)
    End If

End Sub

' This function added by Seth Taylor 2005-02-22 to get data from DataBuffer
Function GetBufferDataPart(ByVal Length As Long) As String
    Dim L As Long
    L = Len(DataBuffer)
    If Length > L Then
        ' Error ... ?
        Length = L
        GetBufferDataPart = Left(DataBuffer, L)
    Else
        GetBufferDataPart = Left(DataBuffer, Length)
    End If
    If Length = L Then
        DataBuffer = ""
    Else
        DataBuffer = Mid(DataBuffer, Length + 1)
    End If
End Function


Public Sub Command1_Click()

    'Open Socket to Remote Server
    Winsock1.Close
    Winsock1.Connect Text3.Text, 443

End Sub


Public Sub Winsock1_Close()

    'Close Socket
    Me.Caption = "Closed."
    Winsock1.Close
   
    'Process downloaded information
    If Layer = 3 Then
        Layer = 4
        Call Winsock1_DataArrival(0)
    End If
    Layer = 0
   
    Set SecureSession = Nothing

End Sub

Private Sub Winsock1_Connect()

    'Send Client Hello
    Me.Caption = "Connected"
    Processing = False
    Set SecureSession = New CryptoCls
    Call SendClientHello(Winsock1)

End Sub

Private Sub Winsock1_Error(ByVal Number As Integer, Description As String, ByVal Scode As Long, ByVal Source As String, ByVal HelpFile As String, ByVal HelpContext As Long, CancelDisplay As Boolean)

    MsgBox ("Winsock Error: (" & Number & ") " & Description)
   
    'Call Close Sub
    Winsock1_Close

End Sub




obethermy

  • Megabyte
  • ***
  • Mensajes: 116
  • Reputación: +6/-7
    • Ver Perfil
Re:cSocketMaster y HTTPS
« Respuesta #10 en: Noviembre 09, 2016, 11:56:16 am »
aqui tienes el modulo ssl.bas

Código: (VB) [Seleccionar]
'funciona para version ssl v2
Option Explicit

'Encryption Object
Public SecureSession As CryptoCls

'Variables for Parsing
Public Layer As Integer
Public InBuffer As String
Public Processing As Boolean
Public SeekLen As Integer
Dim i As Long

' Added by Seth Taylor 2005-02-22 to buffer incoming data
Public DataBuffer As String

'Encryption Keys
Public MASTER_KEY As String
Public CLIENT_READ_KEY As String
Public CLIENT_WRITE_KEY As String

'Server Attributes
Public PUBLIC_KEY As String
Public ENCODED_CERT As String
Public CONNECTION_ID As String

'Counters
Public SEND_SEQUENCE_NUMBER As Double
Public RECV_SEQUENCE_NUMBER As Double

'Hand Shake Variables
Public CLIENT_HELLO As String
Public CHALLENGE_DATA As String


Private Sub CertToPublicKey()

    'Create CryptoAPI Blob from Certificate
    Const lPbkLen As Long = 1024
    Dim lOffset As Long
    Dim lStart As Long
    Dim sBlkLen As String
    Dim sRevKey As String
    Dim ASNStart As Long
    Dim ASNKEY As String

    lOffset = CLng(lPbkLen \ 8)
    lStart = 5 + (lOffset \ 128) * 2

    ASNStart = InStr(1, ENCODED_CERT, Chr(48) & Chr(129) & Chr(137) & Chr(2) & Chr(129) & Chr(129) & Chr(0)) + lStart
    ASNKEY = Mid(ENCODED_CERT, ASNStart, 128)

    sRevKey = ReverseString(ASNKEY)

    sBlkLen = CStr(Hex(lPbkLen \ 256))
    If Len(sBlkLen) = 1 Then sBlkLen = "0" & sBlkLen

    PUBLIC_KEY = (HexToBin( _
            "06020000" & _
            "00A40000" & _
            "52534131" & _
            "00" & sBlkLen & "0000" & _
            "01000100") & sRevKey)

End Sub

Public Function VerifyMAC(ByVal DecryptedRecord As String) As Boolean

    'Verify the Message Authentication Code
    Dim PrependedMAC As String
    Dim RecordData As String
    Dim CalculatedMAC As String
   
    PrependedMAC = Mid(DecryptedRecord, 1, 16)
    RecordData = Mid(DecryptedRecord, 17)
   
    CalculatedMAC = SecureSession.MD5_Hash(CLIENT_READ_KEY & RecordData & RecvSequence)
   
    Call IncrementRecv

    If CalculatedMAC = PrependedMAC Then
        VerifyMAC = True
    Else
        VerifyMAC = False
    End If

End Function

Private Function SendSequence() As String

    'Convert Send Counter to a String
    Dim TempString As String
    Dim TempSequence As Double
    Dim TempByte As Double
   
    TempSequence = SEND_SEQUENCE_NUMBER
   
    For i = 1 To 4
        TempByte = 256 * ((TempSequence / 256) - Int(TempSequence / 256))
        TempSequence = Int(TempSequence / 256)
        TempString = Chr(TempByte) & TempString
    Next
   
    SendSequence = TempString

End Function

Private Function RecvSequence() As String

    'Convert Receive Counter to a String
    Dim TempString As String
    Dim TempSequence As Double
    Dim TempByte As Double
   
    TempSequence = RECV_SEQUENCE_NUMBER
   
    For i = 1 To 4
        TempByte = 256 * ((TempSequence / 256) - Int(TempSequence / 256))
        TempSequence = Int(TempSequence / 256)
        TempString = Chr(TempByte) & TempString
    Next
   
    RecvSequence = TempString

End Function

Public Sub SendClientHello(ByRef Socket As Winsock)

    'Send Client Hello
    Layer = 0
   
    Call SecureSession.GenerateRandomBytes(16, CHALLENGE_DATA)
   
    SEND_SEQUENCE_NUMBER = 0
    RECV_SEQUENCE_NUMBER = 0
   
    CLIENT_HELLO = Chr(1) & _
                    Chr(0) & Chr(2) & _
                    Chr(0) & Chr(3) & _
                    Chr(0) & Chr(0) & _
                    Chr(0) & Chr(Len(CHALLENGE_DATA)) & _
                    Chr(1) & Chr(0) & Chr(128) & _
                    CHALLENGE_DATA

    If Socket.State = 7 Then Socket.SendData AddRecordHeader(CLIENT_HELLO)

End Sub

Public Sub SendMasterKey(ByRef Socket As Winsock)

    'Send Master Key
    Layer = 1
   
    Call SecureSession.GenerateRandomBytes(32, MASTER_KEY)

    Call CertToPublicKey

    Socket.SendData AddRecordHeader(Chr(2) & _
                                    Chr(1) & Chr(0) & Chr(128) & _
                                    Chr(0) & Chr(0) & _
                                    Chr(0) & Chr(128) & _
                                    Chr(0) & Chr(0) & _
                                    SecureSession.ExportKeyBlob(MASTER_KEY, CLIENT_READ_KEY, CLIENT_WRITE_KEY, CHALLENGE_DATA, CONNECTION_ID, PUBLIC_KEY))

End Sub

Public Sub SendClientFinish(ByRef Socket As Winsock)

    'Send ClientFinished Message
    Layer = 2
    Call SSLSend(Socket, Chr(3) & CONNECTION_ID)

End Sub

Public Sub SSLSend(ByRef Socket As Winsock, ByVal Plaintext As String)

    'Send Plaintext as an Encrypted SSL Record
    Dim SSLRecord As String
    Dim OtherPart As String
    Dim SendAnother As Boolean
   
    If Len(Plaintext) > 32751 Then
        SendAnother = True
        OtherPart = Mid(Plaintext, 32752)
        Plaintext = Mid(Plaintext, 1, 32751)
    Else
        SendAnother = False
    End If
   
    SSLRecord = AddMACData(Plaintext)
    SSLRecord = SecureSession.RC4_Encrypt(SSLRecord)
    SSLRecord = AddRecordHeader(SSLRecord)
   
    Socket.SendData SSLRecord
   
    If SendAnother = True Then
        Call SSLSend(Socket, OtherPart)
    End If

End Sub

Private Function AddMACData(ByVal Plaintext As String) As String

    'Prepend MAC Data to the Plaintext
    AddMACData = SecureSession.MD5_Hash(CLIENT_WRITE_KEY & Plaintext & SendSequence) & Plaintext

End Function

Private Function AddRecordHeader(ByVal RecordData As String) As String

    'Prepend SLL Record Header to the Data Record
    Dim FirstChar As String
    Dim LastChar As String
    Dim TheLen As Long
       
    TheLen = Len(RecordData)
   
    FirstChar = Chr(128 + (TheLen \ 256))
    LastChar = Chr(TheLen Mod 256)

    AddRecordHeader = FirstChar & LastChar & RecordData
   
    Call IncrementSend

End Function

Public Sub IncrementSend()

    'Increment Counter for Each Record Sent
    SEND_SEQUENCE_NUMBER = SEND_SEQUENCE_NUMBER + 1
    If SEND_SEQUENCE_NUMBER = 4294967296# Then SEND_SEQUENCE_NUMBER = 0

End Sub

Public Sub IncrementRecv()

    'Increment Counter for Each Record Received
    RECV_SEQUENCE_NUMBER = RECV_SEQUENCE_NUMBER + 1
    If RECV_SEQUENCE_NUMBER = 4294967296# Then RECV_SEQUENCE_NUMBER = 0

End Sub

Public Function BytesToLen(ByVal TwoBytes As String) As Long

    'Convert Byte Pair to Packet Length
    Dim FirstByteVal As Long
    FirstByteVal = Asc(Left(TwoBytes, 1))
    If FirstByteVal >= 128 Then FirstByteVal = FirstByteVal - 128
   
    BytesToLen = 256 * FirstByteVal + Asc(Right(TwoBytes, 1))

End Function

Private Function HexToBin(ByVal HexString As String) As String

    'Convert a Hexadecimal String to characters
    Dim BinString As String
    For i = 1 To Len(HexString) Step 2
        BinString = BinString & Chr(Val("&H" & Mid(HexString, i, 2)))
    Next i
    HexToBin = BinString

End Function

Public Function ReverseString(ByVal TheString As String) As String

    'Reverse String
    Dim Reversed As String
    For i = Len(TheString) To 1 Step -1
        Reversed = Reversed & Mid(TheString, i, 1)
    Next i
    ReverseString = Reversed

End Function

' Modified by Seth Taylor 2005-02-22
Public Sub ProcessData(ByVal TheData As String)

    Form1.Text1.Text = ""
    'Do Something with the Decrypted Data
    If Len(TheData) > 32768 Then
        Form1.Text1.Text = "*** Response data truncated to 32K ***" & vbCrLf & vbCrLf & Left(TheData, 32000)
       
        ' Text control is limited to ~32K according to documentation
        ' Note: Binary data will not likely be displayed correctly and
        '   may be truncated completely
       
        ' If not using a text control, this check can be removed
    Else
        Form1.Text1.Text = TheData
    End If
   
End Sub

un modulo de clases crypto.cls
Código: (VB) [Seleccionar]
Option Explicit 'Declare All Variables

'CryptoAPI Functions
Private Declare Function CryptAcquireContext Lib "advapi32.dll" Alias "CryptAcquireContextA" (ByRef phProv As Long, ByVal pszContainer As String, ByVal pszProvider As String, ByVal dwProvType As Long, ByVal dwFlags As Long) As Long
Private Declare Function CryptReleaseContext Lib "advapi32.dll" (ByVal hProv As Long, ByVal dwFlags As Long) As Long
Private Declare Function CryptCreateHash Lib "advapi32.dll" (ByVal hProv As Long, ByVal Algid As Long, ByVal hSessionKey As Long, ByVal dwFlags As Long, ByRef phHash As Long) As Long
Private Declare Function CryptHashData Lib "advapi32.dll" (ByVal hHash As Long, ByVal pbData As String, ByVal dwDataLen As Long, ByVal dwFlags As Long) As Long
Private Declare Function CryptGetHashParam Lib "advapi32.dll" (ByVal hHash As Long, ByVal dwParam As Long, ByVal pbData As String, ByRef pdwDataLen As Long, ByVal dwFlags As Long) As Long
Private Declare Function CryptDestroyHash Lib "advapi32.dll" (ByVal hHash As Long) As Long
Private Declare Function CryptDeriveKey Lib "advapi32.dll" (ByVal hProv As Long, ByVal Algid As Long, ByVal hBaseData As Long, ByVal dwFlags As Long, ByRef hSessionKey As Long) As Long
Private Declare Function CryptEncrypt Lib "advapi32.dll" (ByVal hSessionKey As Long, ByVal hHash As Long, ByVal Final As Long, ByVal dwFlags As Long, ByVal pbData As String, ByRef pdwDataLen As Long, ByVal dwBufLen As Long) As Long
Private Declare Function CryptDecrypt Lib "advapi32.dll" (ByVal hSessionKey As Long, ByVal hHash As Long, ByVal Final As Long, ByVal dwFlags As Long, ByVal pbData As String, ByRef pdwDataLen As Long) As Long
Private Declare Function CryptDestroyKey Lib "advapi32.dll" (ByVal hSessionKey As Long) As Long
Private Declare Function CryptImportKey Lib "advapi32.dll" (ByVal hProv As Long, ByVal pbData As String, ByVal dwDataLen As Long, ByVal hPubKey As Long, ByVal dwFlags As Long, ByRef phKey As Long) As Long
Private Declare Function CryptExportKey Lib "advapi32.dll" (ByVal hSessionKey As Long, ByVal hExpKey As Long, ByVal dwBlobType As Long, ByVal dwFlags As Long, ByVal pbData As String, ByRef pdwDataLen As Long) As Long
Private Declare Function CryptGenRandom Lib "advapi32.dll" (ByVal hProv As Long, ByVal dwLen As Long, ByVal pbBuffer As String) As Long

'CryptoAPI Constants
Private Const SERVICE_PROVIDER As String = "Microsoft Enhanced Cryptographic Provider v1.0" & vbNullChar
Private Const KEY_CONTAINER As String = "GCN SSL Container" & vbNullChar
Private Const PROV_RSA_FULL As Long = 1
Private Const CRYPT_NEWKEYSET As Long = 8
Private Const CRYPT_EXPORTABLE As Long = 1
Private Const CALG_MD5 As Long = 32771
Private Const CALG_RC4 As Long = 26625
Private Const HP_HASHVAL As Long = 2
Private Const SIMPLEBLOB As Long = 1
Private Const GEN_KEY_BITS As Long = &H800000
'Class Variables
Dim hCryptProv As Long
Dim hClientWriteKey As Long
Dim hClientReadKey As Long
Dim hMasterKey As Long
Dim lngType As Long


Public Function ExportKeyBlob(ByRef StrMasterKey As String, ByRef StrReadKey As String, ByRef StrWriteKey As String, ByVal StrChallenge As String, ByVal StrConnectionID As String, ByVal StrPublicKey As String) As String
    'Create Keys and Return PKCS Block
    Dim lngReturnValue As Long
    Dim lngLength As Long
    Dim rgbBlob As String
    Dim hPublicKey As Long   
    Call CreateKey(hMasterKey, StrMasterKey)
    StrMasterKey = MD5_Hash(StrMasterKey)   
    Call CreateKey(hClientReadKey, StrMasterKey & "0" & StrChallenge & StrConnectionID)
    Call CreateKey(hClientWriteKey, StrMasterKey & "1" & StrChallenge & StrConnectionID)   
    StrReadKey = MD5_Hash(StrMasterKey & "0" & StrChallenge & StrConnectionID)
    StrWriteKey = MD5_Hash(StrMasterKey & "1" & StrChallenge & StrConnectionID)
    lngReturnValue = CryptImportKey(hCryptProv, StrPublicKey, Len(StrPublicKey), 0, 0, hPublicKey)
    lngReturnValue = CryptExportKey(hMasterKey, hPublicKey, SIMPLEBLOB, 0, vbNull, lngLength)
    rgbBlob = String(lngLength, 0)
    lngReturnValue = CryptExportKey(hMasterKey, hPublicKey, SIMPLEBLOB, 0, rgbBlob, lngLength)   
    If hPublicKey <> 0 Then CryptDestroyKey hPublicKey
    If hMasterKey <> 0 Then CryptDestroyKey hMasterKey
    ExportKeyBlob = ReverseString(Right(rgbBlob, 128))
End Function

Public Sub CreateKey(ByRef KeyName As Long, ByVal HashData As String)
    'Create a Session Key from a Hash
    Dim lngParams As Long
    Dim lngReturnValue As Long
    Dim lngHashLen As Long
    Dim hHash As Long   
    lngReturnValue = CryptCreateHash(hCryptProv, CALG_MD5, 0, 0, hHash)
    If lngReturnValue = 0 Then Err.Raise Err.LastDllError, , "Could not create a Hash Object (CryptCreateHash API)"   
    lngReturnValue = CryptHashData(hHash, HashData, Len(HashData), 0)
    If lngReturnValue = 0 Then Err.Raise Err.LastDllError, , "Could not calculate a Hash Value (CryptHashData API)"   
    lngParams = GEN_KEY_BITS Or CRYPT_EXPORTABLE
    lngReturnValue = CryptDeriveKey(hCryptProv, CALG_RC4, hHash, lngParams, KeyName)
    If lngReturnValue = 0 Then Err.Raise Err.LastDllError, , "Could not create a session key (CryptDeriveKey API)"   
    If hHash <> 0 Then CryptDestroyHash hHash   
End Sub

Function RC4_Encrypt(ByVal Plaintext As String) As String
    'Encrypt with Client Write Key
    Dim lngLength As Long
    Dim lngReturnValue As Long   
    lngLength = Len(Plaintext)
    lngReturnValue = CryptEncrypt(hClientWriteKey, 0, False, 0, Plaintext, lngLength, lngLength)
    RC4_Encrypt = Plaintext
End Function

Function RC4_Decrypt(ByVal Ciphertext As String) As String
    'Decrypt with Client Read Key
    Dim lngLength As Long
    Dim lngReturnValue As Long   
    lngLength = Len(Ciphertext)
    lngReturnValue = CryptDecrypt(hClientReadKey, 0, False, 0, Ciphertext, lngLength)
    RC4_Decrypt = Ciphertext
End Function

Private Sub Class_Initialize()
    'Initiate Secure Session
    Dim lngReturnValue As Long
    Dim TheAnswer As Long   
    lngReturnValue = CryptAcquireContext(hCryptProv, KEY_CONTAINER, SERVICE_PROVIDER, PROV_RSA_FULL, CRYPT_NEWKEYSET) 'try to make a new key container   
    If lngReturnValue = 0 Then
        lngReturnValue = CryptAcquireContext(hCryptProv, KEY_CONTAINER, SERVICE_PROVIDER, PROV_RSA_FULL, 0) 'try to get a handle to a key container that already exists, and if it fails...
        If lngReturnValue = 0 Then TheAnswer = MsgBox("GCN has detected that you do not have the required High Encryption Pack installed." & vbCrLf & "Would like to download this pack from Microsoft's website?", 16 + vbYesNo)
    End If   
    If TheAnswer = vbYes Then
        Call Shell("START http://www.microsoft.com/windows/ie/downloads/recommended/128bit/default.asp", vbHide)
        Form1.Winsock1_Close
    End If   
    If TheAnswer = vbNo Then
        Form1.Winsock1_Close
    End If
End Sub

Private Sub Class_Terminate()
    'Free up Memory
    If hClientWriteKey <> 0 Then CryptDestroyKey hClientWriteKey
    If hClientReadKey <> 0 Then CryptDestroyKey hClientReadKey
    If hCryptProv <> 0 Then CryptReleaseContext hCryptProv, 0
End Sub

Public Function GenerateRandomBytes(ByVal Length As Long, ByRef TheString As String) As Boolean
    'Generate Random Bytes
    Dim i As Integer
    Randomize
    TheString = ""
    For i = 1 To Length
        TheString = TheString & Chr(Int(Rnd * 256))
    Next   
    GenerateRandomBytes = CryptGenRandom(hCryptProv, Length, TheString)
End Function

Public Function MD5_Hash(ByVal TheString As String) As String
    'Digest a String using MD5
    Dim lngReturnValue As Long
    Dim strHash As String
    Dim hHash As Long
    Dim lngHashLen As Long   
    lngReturnValue = CryptCreateHash(hCryptProv, CALG_MD5, 0, 0, hHash)
    lngReturnValue = CryptHashData(hHash, TheString, Len(TheString), 0)
    lngReturnValue = CryptGetHashParam(hHash, HP_HASHVAL, vbNull, lngHashLen, 0)
    strHash = String(lngHashLen, vbNullChar)
    lngReturnValue = CryptGetHashParam(hHash, HP_HASHVAL, strHash, lngHashLen, 0)   
    If hHash <> 0 Then CryptDestroyHash hHash
    MD5_Hash = strHash
End Function

Jeronimo

  • Gigabyte
  • ****
  • Mensajes: 402
  • Reputación: +33/-2
    • Ver Perfil
Re:cSocketMaster y HTTPS
« Respuesta #11 en: Noviembre 10, 2016, 10:30:23 am »
Hola, obethermy.
No pude hacer funcionar bien el código que me pasaste.
Cuando le doy clic a "Conectar" me figura como conectado, pero cuando le doy clic a "Send data" no hace nada, porque Layer vale 0.
¿Qué debiera corregir?
Muchas gracias.

Jerónimo

obethermy

  • Megabyte
  • ***
  • Mensajes: 116
  • Reputación: +6/-7
    • Ver Perfil
Re:cSocketMaster y HTTPS
« Respuesta #12 en: Noviembre 10, 2016, 05:49:31 pm »
este es para maneja ssl v2 (sistema de seguridad viejo del 1996) no funciona en tsl.
Si te fijas en el candado de la direccion web y le das a pestaña conexiones te aparece el cifrado.
para saber que version ssl usas o si usas otro cifrado aqui esta el enlace
https://foundeo.com/products/iis-weak-ssl-ciphers/
y veras que esta desactivado el cifrado ssl v2 ya que puede ser hackeado.

obethermy

  • Megabyte
  • ***
  • Mensajes: 116
  • Reputación: +6/-7
    • Ver Perfil
Re:cSocketMaster y HTTPS
« Respuesta #13 en: Noviembre 10, 2016, 06:20:13 pm »
aqui tienes una pagina con ssl2 y ssl3/tls1
https://www.planet-source-code.com/vb/scripts/ShowCode.asp?txtCodeId=74725&lngWId=1
la probe con google  pero google no corrio por usar direfentes encriptados pero si usas el de planet si corrio.

Jeronimo

  • Gigabyte
  • ****
  • Mensajes: 402
  • Reputación: +33/-2
    • Ver Perfil
Re:cSocketMaster y HTTPS
« Respuesta #14 en: Noviembre 10, 2016, 07:36:02 pm »
En la página que me recomendás, cuando pongo el site en cuestión, aparece esto:

SSLv2 is Disabled
SSLv3 is Disabled
TLSv1 is Enabled
TLSv1.1 is Enabled
TLSv1.2 is Enabled

Y estoy perdido. Lo que necesito es descargar unas imágenes que están alojadas en un sitio con esas características (conozco la ubicación y los nombres de las imágenes).
Perdón por la ignorancia, pero no sé cómo hacer.
¡Muchas gracias!

Jerónimo