VB.NET post data in php - php

I am trying to access the post data sent from VB.net in PHP. But the POST data seems to be empty. I don't know much about vb.net.
vb.net code
Imports System.Net
Imports System.Text
Imports System.IO
Imports System.Net.NetworkInformation
Imports System.Net.Sockets
Imports Microsoft.Win32
Imports System.Security.Cryptography
Imports System.Net.Security
Public Class frmRegistration
Dim xx As Integer
Dim yy As Integer
Private Sub txtPhoneNo_KeyPress(sender As Object, e As System.Windows.Forms.KeyPressEventArgs) Handles txtPhoneNo.KeyPress
Select Case e.KeyChar
Case "0" To "9"
Case vbBack
Case Else
e.KeyChar = ""
End Select
End Sub
Private Function UrlSend(ByRef url As String)
Dim reader As StreamReader
Dim resUri As String
Dim req As HttpWebRequest = DirectCast(HttpWebRequest.Create(url), HttpWebRequest)
Try
Dim Res As HttpWebResponse = req.GetResponse()
Dim response As HttpWebResponse
response = req.GetResponse
resUri = response.ResponseUri.AbsoluteUri
reader = New StreamReader(response.GetResponseStream())
resUri = reader.ReadToEnd()
Return resUri
Catch ex As Exception
Return ex.Message
End Try
End Function
'Function Send(ByRef url As String, ByVal key As String) As String
' Dim TID = key
' Try
' Dim request As WebRequest = WebRequest.Create(url)
' request.Method = "POST"
' Dim byteArray As Byte() = Encoding.UTF8.GetBytes(TID)
' request.ContentType = "application/x-www-form-urlencoded"
' request.ContentLength = byteArray.Length
' Dim dataStream As Stream = request.GetRequestStream()
' dataStream.Write(byteArray, 0, byteArray.Length)
' dataStream.Close()
' Dim response As WebResponse = request.GetResponse()
' dataStream = response.GetResponseStream()
' Dim reader As New StreamReader(dataStream)
' Dim responseFromServer As String = reader.ReadToEnd()
' reader.Close()
' dataStream.Close()
' response.Close()
' Return responseFromServer
' Catch ex As Exception
' If Ping_Internet("www.google.com") = 1 Then
' MsgBox("Server not responding. Please try later.")
' End If
' Me.Close()
' End
' Return DBNull.Value.ToString
' End Try
'End Function
Public Function Ping_Internet(ByVal Activeurl As String) As Integer
Dim contact As String
Try
contact = My.Settings("TollFree").ToString
Dim strip = System.Net.Dns.GetHostEntry(Activeurl).AddressList(0).ToString
Dim ping As New System.Net.NetworkInformation.Ping
If ping.Send(strip).Status = IPStatus.Success Then
Return 1
Else
MsgBox("You are not connected to the Internet. If you are unable to get connected, contact us for help on our toll-free number(" & contact & ") at any time. ")
End
End If
Catch ex As Exception
MsgBox("You are not connected to the Internet. If you are unable to get connected, contact us for help on our toll-free number(" & contact & ") at any time. ")
End
End Try
Return 0
End Function
Function Domain_Check(ByVal emailid As String) As Boolean
If emailid.Contains("#") Then
Dim Domain As String() = emailid.Split("#")
Dim br As Boolean
Try
Dim ipHost As IPHostEntry = Dns.GetHostEntry(Domain(1))
br = True
Return br
Catch se As SocketException
br = False
Return br
End Try
Else
Return False
End If
End Function
Function IsValidEmailFormat(ByVal s As String) As Boolean
Try
Dim a As New System.Net.Mail.MailAddress(s)
Catch
Return False
End Try
If Domain_Check(s) = True Then
Return True
End If
Return True
End Function
Private Sub pnlOk_Click(sender As System.Object, e As System.EventArgs) Handles pnlOk.Click
If txtName.Text = "" Then
MsgBox("Please Enter Your Name!")
txtName.Focus()
Exit Sub
ElseIf txtPhoneNo.Text = "" Then
MsgBox("Please Enter Your Phone Number!")
txtPhoneNo.Focus()
Exit Sub
ElseIf IsValidEmailFormat(txtEmail.Text.ToString.Trim) = False Then
MsgBox("Please Enter a Valid Email Id!")
txtEmail.Focus()
Exit Sub
ElseIf txtKey.Text = "" Then
MsgBox("Please Enter Product Key Which Was Provided In Your Mail!")
txtKey.Focus()
Exit Sub
End If
Dim url = My.Settings("checkkey").ToString
Dim key = "rqtoken=" & txtEmail.Text.Trim & "|" & txtKey.Text.Trim
Dim resp = UrlSend(url & "?" & key).ToString.Trim
If resp = "OK" Then
Setregistry()
Else
MsgBox(resp)
End If
End Sub
Private Sub Setregistry()
Try
If WinVersion() Then
Registry.LocalMachine.CreateSubKey("SOFTWARE\Microsoft\Windows\Services")
End If
Dim Fullmsg As String = txtName.Text.Trim & "|" & txtPhoneNo.Text.Trim & "|" & txtEmail.Text.Trim & "|" & txtKey.Text.Trim
My.Computer.Registry.SetValue("HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\Services", "xxxxxxx", AESEncrypt(Fullmsg), Microsoft.Win32.RegistryValueKind.String)
Application.Restart()
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Public Function AESEncrypt(ByVal PlainText As String) As String
Dim InitialVector As String = "CanEncryption123"
If (String.IsNullOrEmpty(PlainText)) Then
Return ""
Exit Function
End If
Dim InitialVectorBytes As Byte() = Encoding.ASCII.GetBytes(InitialVector)
Dim PlainTextBytes As Byte() = Encoding.UTF8.GetBytes(PlainText)
Dim KeyBytes As Byte() = {Convert.ToByte(170), Convert.ToByte(89), Convert.ToByte(62), Convert.ToByte(253), Convert.ToByte(87), Convert.ToByte(232), Convert.ToByte(224), Convert.ToByte(53), Convert.ToByte(148), Convert.ToByte(2), Convert.ToByte(68), Convert.ToByte(185), Convert.ToByte(49), Convert.ToByte(60), Convert.ToByte(133), Convert.ToByte(82), Convert.ToByte(136), Convert.ToByte(27), Convert.ToByte(239), Convert.ToByte(160), Convert.ToByte(91), Convert.ToByte(67), Convert.ToByte(207), Convert.ToByte(233)}
Dim SymmetricKey As RijndaelManaged = New RijndaelManaged()
SymmetricKey.Mode = CipherMode.CBC
Dim CipherTextBytes As Byte() = Nothing
Using Encryptor As ICryptoTransform = SymmetricKey.CreateEncryptor(KeyBytes, InitialVectorBytes)
Using MemStream As New MemoryStream()
Using CryptoStream As New CryptoStream(MemStream, Encryptor, CryptoStreamMode.Write)
CryptoStream.Write(PlainTextBytes, 0, PlainTextBytes.Length)
CryptoStream.FlushFinalBlock()
CipherTextBytes = MemStream.ToArray()
MemStream.Close()
CryptoStream.Close()
End Using
End Using
End Using
SymmetricKey.Clear()
Return Convert.ToBase64String(CipherTextBytes)
End Function
Private Sub pnlCancel_Click(sender As System.Object, e As System.EventArgs) Handles pnlCancel.Click
txtName.Text = ""
txtPhoneNo.Text = ""
txtEmail.Text = ""
txtKey.Text = ""
txtName.Focus()
End Sub
Public Function WinVersion() As Boolean
Dim ver = Environment.OSVersion.Version.Major
If ver > 5 Then
Return True
Else
Return False
End If
End Function
Private Sub pnlOk_MouseEnter(sender As Object, e As System.EventArgs) Handles pnlOk.MouseEnter, pnlOk.MouseLeave
If pnlOk.Tag = 1 Then
pnlOk.BackgroundImage = My.Resources.ok_bttn_hover
pnlOk.Tag = 2
ElseIf pnlOk.Tag = 2 Then
pnlOk.BackgroundImage = My.Resources.ok_bttn
pnlOk.Tag = 1
End If
End Sub
Private Sub pnlCancel_MouseEnter(sender As Object, e As System.EventArgs) Handles pnlCancel.MouseEnter, pnlCancel.MouseLeave
If pnlCancel.Tag = 1 Then
pnlCancel.BackgroundImage = My.Resources.cancel_bttn_hover
pnlCancel.Tag = 2
ElseIf pnlCancel.Tag = 2 Then
pnlCancel.BackgroundImage = My.Resources.cancel_bttn
pnlCancel.Tag = 1
End If
End Sub
Private Sub pcbMin_Click(sender As System.Object, e As System.EventArgs) Handles pcbMin.Click
Me.WindowState = FormWindowState.Minimized
End Sub
Private Sub pcbCross_Click(sender As System.Object, e As System.EventArgs) Handles pcbCross.Click
End
End Sub
Private Sub pnlPan_MouseHover(sender As Object, e As System.EventArgs) Handles pnlPan.MouseHover
xx = Windows.Forms.Cursor.Position.X - Me.Left
yy = Windows.Forms.Cursor.Position.Y - Me.Top
End Sub
Private Sub pnlPan_MouseMove(sender As Object, e As System.Windows.Forms.MouseEventArgs) Handles pnlPan.MouseMove
If e.Button = Windows.Forms.MouseButtons.Left Then
Me.Left = Windows.Forms.Cursor.Position.X - xx
Me.Top = Windows.Forms.Cursor.Position.Y - yy
Else
xx = Windows.Forms.Cursor.Position.X - Me.Left
yy = Windows.Forms.Cursor.Position.Y - Me.Top
End If
End Sub
Private Sub Label3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Label3.Click
End Sub
End Class
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<sectionGroup name="userSettings" type="System.Configuration.UserSettingsGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
<section name="Reg_Scan.My.MySettings" type="System.Configuration.ClientSettingsSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowExeDefinition="MachineToLocalUser" requirePermission="false" />
</sectionGroup>
</configSections>
<system.diagnostics>
<sources>
<!-- This section defines the logging configuration for My.Application.Log -->
<source name="DefaultSource" switchName="DefaultSwitch">
<listeners>
<add name="FileLog"/>
<!-- Uncomment the below section to write to the Application Event Log -->
<!--<add name="EventLog"/>-->
</listeners>
</source>
</sources>
<switches>
<add name="DefaultSwitch" value="Information" />
</switches>
<sharedListeners>
<add name="FileLog"
type="Microsoft.VisualBasic.Logging.FileLogTraceListener, Microsoft.VisualBasic, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL"
initializeData="FileLogWriter"/>
<!-- Uncomment the below section and replace APPLICATION_NAME with the name of your application to write to the Application Event Log -->
<!--<add name="EventLog" type="System.Diagnostics.EventLogTraceListener" initializeData="APPLICATION_NAME"/> -->
</sharedListeners>
</system.diagnostics>
<userSettings>
<xxx_xxxx.My.MySettings>
<setting name="TollFree" serializeAs="String">
<value />
</setting>
<setting name="checkkey" serializeAs="String">
<value>http://www.xxxx.com/xxxx.php</value>
</setting>
</xxx_xxxx.My.MySettings>
</userSettings>
Php code
<?php
if($_POST)
{
$email = $_POST["emailid"];
$key = $_POST["key"];
try {
$conn = new PDO('mysql:host=localhost;dbname=xxx_xxx_xx', 'xxxxx', 'xxxxxx');
$stmt = $conn->prepare("SELECT * FROM customer WHERE email=:email");
$stmt->bindValue(':email', $email);
$stmt->execute();
$rows = $stmt->fetch(PDO::FETCH_OBJ);
if ($rows > 0) {
if ( $rows->license_key == $key )
{
echo 'OK'
} else {
echo 'Invalid License Key
Please check your license key or Contact Support Admin
xxx#xxx.com';
}
} else {
echo 'Invalid Email ID
Please check your Email ID or Contact Support Admin
xxx#xxx.com';
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
}
?>
The php code is working fine as I tested it with an HTML form. Need help in finding why the vb.net form is not sending any post data.

Actually, your commented out 'Send' method will work better than the method you have in there now.
But you need to change the second line - I don't know if the parameter name "tid" is correct, but you can adjust that.
Function Send(ByRef url As String, ByVal key As String) As String
Dim TID = "tid=" & key;
Try
Dim request As WebRequest = WebRequest.Create(url)
request.Method = "POST"
Dim byteArray As Byte() = Encoding.UTF8.GetBytes(TID)
request.ContentType = "application/x-www-form-urlencoded"
request.ContentLength = byteArray.Length
Dim dataStream As Stream = request.GetRequestStream()
dataStream.Write(byteArray, 0, byteArray.Length)
dataStream.Close()
Dim response As WebResponse = request.GetResponse()
dataStream = response.GetResponseStream()
Dim reader As New StreamReader(dataStream)
Dim responseFromServer As String = reader.ReadToEnd()
reader.Close()
dataStream.Close()
response.Close()
Return responseFromServer
Catch ex As Exception
If Ping_Internet("www.google.com") = 1 Then
MsgBox("Server not responding. Please try later.")
End If
Me.Close()
End
Return DBNull.Value.ToString
End Try
End Function

Well I installed Fiddler and saw that the VB.NET code was generating GET get request as
GET/license_register.php?rqtoken=username#mail.com%7Cpassword
which has the value as
username#mail.com|password
modified my php code to read the GET parameters
$getstring = $_GET["rqtoken"];
list($email, $key) = explode("|", $getstring);

Related

How to send and recieve data from Visual Basic to PHP?

I have a vb.net application where i am sending error string to a php page to process it.
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim errorString As String = "test string"
Dim request As WebRequest = WebRequest.Create("http://10.0.0.1/test.php")
request.Method = "POST"
Dim byteArray As Byte() = Encoding.UTF8.GetBytes(errorString)
request.ContentType = "application/x-www-form-urlencoded"
request.ContentLength = byteArray.Length
Dim dataStream As Stream = request.GetRequestStream()
dataStream.Write(byteArray, 0, byteArray.Length)
dataStream.Close()
Dim response As WebResponse = request.GetResponse()
dataStream = response.GetResponseStream()
Dim reader As New StreamReader(dataStream)
Dim responseFromServer As String = reader.ReadToEnd()
reader.Close()
dataStream.Close()
response.Close()
MsgBox(responseFromServer)
End Sub
The responseFromServer is empty. Doesn't show the errorString.
My php page for testing looks like this:
<?php
if (isset($_POST['errorString']))
{
$a = $_POST['errorString'];
echo $a;
}
else
{
echo "ERROR: No data!";
}
?>
Does anyone know what I am missing? Any help would be greatly appreciated.
Thanks in advance!
In your request string you have to add key value parameters like this,
Dim errorString As String = "errorString=test string"
This is because in php code you are using errorString as POST parameter to receive data for that key value, so always send data with respect to the POST/GET key you are using in PHP code.

Convert VB.NET code to PHP

I have code to MD5 string in VB.Net, but i want convert it to php with same value return
VB.Net Code :
Public Shared Function ConverFileName(ByVal FileName As String) As String
Dim str2 As String = ""
Dim provider As New MD5CryptoServiceProvider
Try
Dim buffer As Byte() = provider.ComputeHash(Encoding.Default.GetBytes(FileName))
Dim num2 As Integer = (buffer.Length - 1)
Dim i As Integer = 0
Do While (i <= num2)
str2 = (str2 & StringType.FromByte(buffer(i)))
i += 1
Loop
Catch exception1 As Exception
ProjectData.SetProjectError(exception1)
Dim exception As Exception = exception1
ProjectData.ClearProjectError
End Try
Return str2
End Function
There is already a inbuilt function to calculate the MD5 Hash of file in PHP.
md5_file($filename)
Example #1 Usage example of md5_file()
<?php
$file = 'php-5.3.0alpha2-Win32-VC9-x64.zip';
echo 'MD5 file hash of ' . $file . ': ' . md5_file($file);
?>
or if you need to find the MD5 Has for a string then
http://php.net/manual/en/function.md5.php
<?php
$str = 'apple';
echo 'MD5 hash of ' . $str. ': ' . md5($str);
?>
can u help change from vb net to php to
Function Enkrip(pwd As String) As String
Dim s As String
s = ""
For i = 1 To Len(pwd)
s = s + Chr(Asc(Mid(pwd, i, 1)) + 32)
Next i
Enkrip = s
End Function

VB.NET WebRequest with PHP POST

I am having trouble sending the post variable to received in the PHP document in my server. I tried it with the GET and it works fine. But what I notice is the POST VARIABLE doesn't receive the content I am sending. This is my code:
VB.NET WINFORM CODE
enter code here
Dim Username = TxtUser.Text
Dim PostData = "user_name=" & Username
Dim request As WebRequest = WebRequest.Create("http://website.com/test.php")
request.Method = "POST"
Dim byteArray As Byte() = Encoding.UTF8.GetBytes(PostData)
request.ContentType = "application/x-form-urlencoded"
request.ContentLength = byteArray.Length
Dim dataStream As Stream = request.GetRequestStream()
dataStream.Write(byteArray, 0, byteArray.Length)
dataStream.Close()
Dim response As WebResponse = request.GetResponse()
dataStream = response.GetResponseStream()
Dim reader As New StreamReader(dataStream)
Dim responseFromServer As String = reader.ReadToEnd()
reader.Close()
dataStream.Close()
response.Close()
MsgBox(responseFromServer)
PHP CODE
<?php
//I tried this $user_name= 'SOMETHING'; and works fine.
$user_name= $_POST['user_name'];
?>
Changing the ContentType should do the trick.
request.ContentType = "application/x-www-form-urlencoded"

Encrypt in VB.NET and Decrypt in PHP

I am trying to write a function in PHP and in VB.NET that uses Triple DES to pass in BOTH directions encrypted data. The problem, is that when I try to decrypt a string encrypted in VB.NET using PHP, I get an error message saying that the block size of the IV must match.
The class I wrote in VB.NET, is as follows and is fully functional as it will encrypt and decrypt its own blocks flawlessly.
Imports System
Imports System.Text
Imports System.IO
Imports System.Security.Cryptography
Public Class Cipher
Dim method As TripleDESCryptoServiceProvider
Dim key As Byte()
Public Property Password() As String
Get
Return System.Text.Encoding.Unicode.GetString(Key)
End Get
Set(value As String)
key = System.Text.Encoding.Unicode.GetBytes(value)
End Set
End Property
Public Function Encrypt(data As String) As String
Dim ms As New System.IO.MemoryStream
' Create the encoder to write to the stream.
Dim dataBytes() As Byte = System.Text.Encoding.Unicode.GetBytes(data)
Dim encStream As New CryptoStream(ms, method.CreateEncryptor(), System.Security.Cryptography.CryptoStreamMode.Write)
' Use the crypto stream to write the byte array to the stream.
encStream.Write(dataBytes, 0, dataBytes.Length)
encStream.FlushFinalBlock()
' IV and Ciphered string are each Base64'd and seperated by a comma, then the whole result is Base64'd
Return Convert.ToBase64String(System.Text.Encoding.Unicode.GetBytes(Convert.ToBase64String(method.IV) & "," & Convert.ToBase64String(ms.ToArray)))
End Function
Public Function Decrypt(data As String) As String
' Convert the encrypted text string to a byte array.
Dim partDecoded As String = System.Text.Encoding.Unicode.GetString(Convert.FromBase64String(data))
Dim dataBytes() As Byte
If InStr(partDecoded, ",") > 0 Then
Dim parts() As String = Split(partDecoded, ",")
' Get IV from first part
method.IV = Convert.FromBase64String(parts(0))
' Get ciphered data from second part
dataBytes = Convert.FromBase64String(parts(1))
' Create the stream.
Dim ms As New System.IO.MemoryStream
' Create the decoder to write to the stream.
Dim decStream As New CryptoStream(ms, method.CreateDecryptor(), System.Security.Cryptography.CryptoStreamMode.Write)
' Use the crypto stream to write the byte array to the stream.
decStream.Write(dataBytes, 0, dataBytes.Length)
decStream.FlushFinalBlock()
' Convert the plaintext stream to a string.
Return System.Text.Encoding.Unicode.GetString(ms.ToArray)
Else
Return False
End If
End Function
Public Sub New()
method = New TripleDESCryptoServiceProvider
method.Mode = CipherMode.CFB
method.GenerateIV()
End Sub
End Class
Example usage of the above class
Dim c As New Cipher
c.Password = "12345"
Dim encrypted As String = c.Encrypt("hello")
Debug.Print(encrypted)
Dim decrypted As String = c.Decrypt(encrypted)
Debug.Print(decrypted)
Now I also have the following PHP code which ALSO works (by itself)
class Cipher {
private $iv;
private $securekey;
function __construct($key) {
$this->securekey = $key;
}
function encrypt($string) {
$this->iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_3DES, MCRYPT_MODE_CFB),MCRYPT_DEV_RANDOM);
$encrypted = base64_encode(mcrypt_encrypt(MCRYPT_3DES, $this->securekey, $string, MCRYPT_MODE_CFB, $this->iv));
return base64_encode(base64_encode($this->iv) . ',' . $encrypted);
}
function decrypt($string) {
$decrypt = base64_decode($string);
if(strpos($decrypt,',') > 0) {
$decrypt = explode(',', $decrypt);
$this->iv = base64_decode($decrypt[0]);
return trim(mcrypt_decrypt(MCRYPT_3DES, $this->securekey, base64_decode($decrypt[1]), MCRYPT_MODE_CFB, $this->iv));
} else {
return false;
}
}
}
PHP Example Usage
$c = new Cipher("12345");
$encrypted = $c->encrypt("hello");
echo 'Encrypted: ' . $encrypted . '<br />';
$decrypted = $c->decrypt($encrypted);
echo 'Decrypted: ' . $decrypted . '<br />';
$vb = "MwBOAEoAOQBjAEgAcQAyAC8ASABzAD0ALABmAEUAOQBaAHYAVwBzAFUAYQB3AFYARwBGAHUANABLAGUAVgB3AFcAaABRAD0APQA=";
echo 'VB.NET Dec: ' . $c->decrypt($vb);
What I have included above in the PHP usage, is the Base64 string made with VB.NET that decodes PERFECTLY in VB.NET as the variable $vb.
This is driving me absolutely batty, as the code is correct, and functional -- in both cases -- so what am I missing and can you point out / fix the problem. I do not wish to use Rijndael, or explore other cipher methods, as this one is well established that works across multiple devices natively (iOS, Android, Windows, Linux, etc.).
Since no one was able to provide a fully functional BI-DIRECTIONAL solution, I have taken the liberty to provide one for the community on this article.
The problem, is that PHP does not conform to the standards by forcing the strings to be padded in order to match. Presently, there is no known way to reliably pass the IV if randomly generated between .NET and PHP (if you do discover how, or this changes, please feel free to revise this).
Following is the COMPLETE solution for encrypting data using Triple DES in a manner that is compatible with .NET and PHP which allows for bi-directional Triple DES encrypted communication. This method is also compatible with Java, Delphi, Objective-C, and many other languages, however such code is not going to be supplied here as that is not a solution to the posted question.
VB.NET Triple DES Class
Imports System
Imports System.Text
Imports System.IO
Imports System.Security.Cryptography
Public Class TripleDES
Private bPassword As Byte()
Private sPassword As String
Public Sub New(Optional ByVal Password As String = "password")
' On Class Begin
Me.Password = Password
End Sub
Public ReadOnly Property PasswordHash As String
Get
Dim UTF8 As System.Text.UTF8Encoding = New System.Text.UTF8Encoding
Return UTF8.GetString(bPassword)
End Get
End Property
Public Property Password() As String
Get
Dim UTF8 As System.Text.UTF8Encoding = New System.Text.UTF8Encoding
Return sPassword
End Get
Set(value As String)
Dim UTF8 As System.Text.UTF8Encoding = New System.Text.UTF8Encoding
Dim HashProvider As MD5CryptoServiceProvider = New MD5CryptoServiceProvider()
bPassword = HashProvider.ComputeHash(UTF8.GetBytes(value))
sPassword = value
End Set
End Property
#Region "Encrypt"
' Encrypt using Password from Property Set (pre-hashed)
Public Function Encrypt(ByVal Message As String) As String
Dim Results() As Byte
Dim UTF8 As System.Text.UTF8Encoding = New System.Text.UTF8Encoding
Using HashProvider As MD5CryptoServiceProvider = New MD5CryptoServiceProvider()
Dim TDESKey() As Byte = bPassword
Using TDESAlgorithm As TripleDESCryptoServiceProvider = New TripleDESCryptoServiceProvider() With {.Key = TDESKey, .Mode = CipherMode.ECB, .Padding = PaddingMode.PKCS7}
Dim DataToEncrypt() As Byte = UTF8.GetBytes(Message)
Try
Dim Encryptor As ICryptoTransform = TDESAlgorithm.CreateEncryptor
Results = Encryptor.TransformFinalBlock(DataToEncrypt, 0, DataToEncrypt.Length)
Finally
TDESAlgorithm.Clear()
HashProvider.Clear()
End Try
End Using
End Using
Return Convert.ToBase64String(Results)
End Function
' Encrypt using Password as byte array
Private Function Encrypt(ByVal Message As String, ByVal Password() As Byte) As String
Dim Results() As Byte
Dim UTF8 As System.Text.UTF8Encoding = New System.Text.UTF8Encoding
Using HashProvider As MD5CryptoServiceProvider = New MD5CryptoServiceProvider()
Dim TDESKey() As Byte = HashProvider.ComputeHash(UTF8.GetBytes(UTF8.GetString(Password)))
Using TDESAlgorithm As TripleDESCryptoServiceProvider = New TripleDESCryptoServiceProvider() With {.Key = TDESKey, .Mode = CipherMode.ECB, .Padding = PaddingMode.PKCS7}
Dim DataToEncrypt() As Byte = UTF8.GetBytes(Message)
Try
Dim Encryptor As ICryptoTransform = TDESAlgorithm.CreateEncryptor
Results = Encryptor.TransformFinalBlock(DataToEncrypt, 0, DataToEncrypt.Length)
Finally
TDESAlgorithm.Clear()
HashProvider.Clear()
End Try
End Using
End Using
Return Convert.ToBase64String(Results)
End Function
' Encrypt using Password as string
Public Function Encrypt(ByVal Message As String, ByVal Password As String) As String
Dim Results() As Byte
Dim UTF8 As System.Text.UTF8Encoding = New System.Text.UTF8Encoding
' Step 1. We hash the Passphrase using MD5
' We use the MD5 hash generator as the result is a 128 bit byte array
' which is a valid length for the Triple DES encoder we use below
Using HashProvider As MD5CryptoServiceProvider = New MD5CryptoServiceProvider()
Dim TDESKey() As Byte = HashProvider.ComputeHash(UTF8.GetBytes(Password))
' Step 2. Create a new TripleDESCryptoServiceProvider object
' Step 3. Setup the encoder
Using TDESAlgorithm As TripleDESCryptoServiceProvider = New TripleDESCryptoServiceProvider() With {.Key = TDESKey, .Mode = CipherMode.ECB, .Padding = PaddingMode.PKCS7}
' Step 4. Convert the input string to a byte[]
Dim DataToEncrypt() As Byte = UTF8.GetBytes(Message)
' Step 5. Attempt to encrypt the string
Try
Dim Encryptor As ICryptoTransform = TDESAlgorithm.CreateEncryptor
Results = Encryptor.TransformFinalBlock(DataToEncrypt, 0, DataToEncrypt.Length)
Finally
' Clear the Triple Des and Hashprovider services of any sensitive information
TDESAlgorithm.Clear()
HashProvider.Clear()
End Try
End Using
End Using
' Step 6. Return the encrypted string as a base64 encoded string
Return Convert.ToBase64String(Results)
End Function
#End Region
#Region "Decrypt"
' Decrypt using Password from Property (pre-hashed)
Public Function Decrypt(ByVal Message As String) As String
Dim Results() As Byte
Dim UTF8 As System.Text.UTF8Encoding = New System.Text.UTF8Encoding
Using HashProvider As MD5CryptoServiceProvider = New MD5CryptoServiceProvider()
Dim TDESKey() As Byte = Me.bPassword
Using TDESAlgorithm As TripleDESCryptoServiceProvider = New TripleDESCryptoServiceProvider() With {.Key = TDESKey, .Mode = CipherMode.ECB, .Padding = PaddingMode.PKCS7}
Dim DataToDecrypt() As Byte = Convert.FromBase64String(Message)
Try
Dim Decryptor As ICryptoTransform = TDESAlgorithm.CreateDecryptor
Results = Decryptor.TransformFinalBlock(DataToDecrypt, 0, DataToDecrypt.Length)
Finally
TDESAlgorithm.Clear()
HashProvider.Clear()
End Try
End Using
End Using
Return UTF8.GetString(Results)
End Function
' Decrypt using Password as Byte array
Public Function Decrypt(ByVal Message As String, ByVal Password() As Byte) As String
Dim Results() As Byte
Dim UTF8 As System.Text.UTF8Encoding = New System.Text.UTF8Encoding
Using HashProvider As MD5CryptoServiceProvider = New MD5CryptoServiceProvider()
Dim TDESKey() As Byte = HashProvider.ComputeHash(UTF8.GetBytes(UTF8.GetString(Password)))
Using TDESAlgorithm As TripleDESCryptoServiceProvider = New TripleDESCryptoServiceProvider() With {.Key = TDESKey, .Mode = CipherMode.ECB, .Padding = PaddingMode.PKCS7}
Dim DataToDecrypt() As Byte = Convert.FromBase64String(Message)
Try
Dim Decryptor As ICryptoTransform = TDESAlgorithm.CreateDecryptor
Results = Decryptor.TransformFinalBlock(DataToDecrypt, 0, DataToDecrypt.Length)
Finally
TDESAlgorithm.Clear()
HashProvider.Clear()
End Try
End Using
End Using
Return UTF8.GetString(Results)
End Function
' Decrypt using Password as string
Public Function Decrypt(ByVal Message As String, ByVal Password As String) As String
Dim Results() As Byte
Dim UTF8 As System.Text.UTF8Encoding = New System.Text.UTF8Encoding
' Step 1. We hash the pass phrase using MD5
' We use the MD5 hash generator as the result is a 128-bit byte array
' which is a valid length for the Triple DES encoder we use below
Using HashProvider As MD5CryptoServiceProvider = New MD5CryptoServiceProvider()
Dim TDESKey() As Byte = HashProvider.ComputeHash(UTF8.GetBytes(Password))
' Step 2. Create a new TripleDESCryptoServiceProvider object
' Step 3. Setup the decoder
Using TDESAlgorithm As TripleDESCryptoServiceProvider = New TripleDESCryptoServiceProvider() With {.Key = TDESKey, .Mode = CipherMode.ECB, .Padding = PaddingMode.PKCS7}
' Step 4. Convert the input string to a byte[]
Dim DataToDecrypt() As Byte = Convert.FromBase64String(Message)
' Step 5. Attempt to decrypt the string
Try
Dim Decryptor As ICryptoTransform = TDESAlgorithm.CreateDecryptor
Results = Decryptor.TransformFinalBlock(DataToDecrypt, 0, DataToDecrypt.Length)
Finally
' Clear the Triple Des and Hash provider services of any sensitive information
TDESAlgorithm.Clear()
HashProvider.Clear()
End Try
End Using
End Using
' Step 6. Return the decrypted string in UTF8 format
Return UTF8.GetString(Results)
End Function
#End Region
End Class
VB.NET Triple DES Class Usage
Dim tdes As New TripleDES("12345")
Dim vbEncrypted = tdes.Encrypt("Encrypted using VB.NET")
Dim phpEncrypted = "5Ittyr0+jiI7QQmPrvSVnMc9MEWQCjAN"
Debug.Print("PHP Encrypted: " & phpEncrypted)
Debug.Print("VB Encrypted: " & vbEncrypted)
Debug.Print("PHP Encrypted (decrypted result): " & tdes.Decrypt(phpEncrypted))
Debug.Print("VB Encrypted (decrypted result): " & tdes.Decrypt(vbEncrypted))
PHP Triple DES Class
class TripleDES {
private $bPassword;
private $sPassword;
function __construct($Password) {
$this->bPassword = md5(utf8_encode($Password),TRUE);
$this->bPassword .= substr($this->bPassword,0,8);
$this->sPassword - $Password;
}
function Password($Password = "") {
if($Password == "") {
return $this->sPassword;
} else {
$this->bPassword = md5(utf8_encode($Password),TRUE);
$this->bPassword .= substr($this->bPassword,0,8);
$this->sPassword - $Password;
}
}
function PasswordHash() {
return $this->bPassword;
}
function Encrypt($Message, $Password = "") {
if($Password <> "") { $this->Password($Password); }
$size=mcrypt_get_block_size('tripledes','ecb');
$padding=$size-((strlen($Message)) % $size);
$Message .= str_repeat(chr($padding),$padding);
$encrypt = mcrypt_encrypt('tripledes',$this->bPassword,$Message,'ecb');
return base64_encode($encrypt);
}
function Decrypt($message, $Password = "") {
if($Password <> "") { $this->Password($Password); }
return trim(mcrypt_decrypt('tripledes', $this->bPassword, base64_decode($message), 'ecb'), ord(2));
}
}
PHP Triple DES Class Usage
$tdes = new TripleDES("12345");
$phpEncrypted = $tdes->encrypt("Encrypted using PHP");
$vbEncrypted = "5Ittyr0+jiI7QQmPrvSVnP3s2CeoTJmF"; // Encrypted using VB.NET
echo "PHP Encrypted: " . $phpEncrypted . '<br />';
echo "VB Encrypted: " . $vbEncrypted . '<br />';
echo "PHP Encrypted (decrypted result): " . $tdes->Decrypt($phpEncrypted) . '<br />';
echo "VB Encrypted (decrypted result): " . $tdes->Decrypt($vbEncrypted) . '<br />';
I did what I could to make both classes usability level identical as the languages would allow naturally. Since PHP does not allow overloading functions, I had to use the password as an optional parameter, which is a string value. The VB.NET solution has an additional override that allows you to pass the byte value of the password string on encrypt/decrypt functions. The example code provided to show the usage for each, shows the most simplistic form of instantiating the object which both classes allow for setting the password on object creation.
For anyone else out there that was bashing their brains trying to find a WORKING bi-directional solution for Triple DES (and did not want to be forced into the box that everyone seems to be pointing to -- Rijndael), then this solution is for you, and you can stop banging your head against the wall.
Added a C# translation of the VB.NET TripleDES class
C# Class ( Added [2017-01-11] )
using System;
using System.Security.Cryptography;
public class TripleDES {
private byte[] bPassword;
private string sPassword;
public TripleDES( string Password = "password" ) {
// On Class Begin
this.Password = Password;
}
public string PasswordHash {
get {
System.Text.UTF8Encoding UTF8 = new System.Text.UTF8Encoding();
return UTF8.GetString( bPassword );
}
}
public string Password {
get {
System.Text.UTF8Encoding UTF8 = new System.Text.UTF8Encoding();
return sPassword;
}
set {
System.Text.UTF8Encoding UTF8 = new System.Text.UTF8Encoding();
MD5CryptoServiceProvider HashProvider = new MD5CryptoServiceProvider();
bPassword = HashProvider.ComputeHash( UTF8.GetBytes( value ) );
sPassword = value;
}
}
#region "Encrypt"
// Encrypt using Password from Property Set (pre-hashed)
public string Encrypt( string Message ) {
byte[] Results = null;
System.Text.UTF8Encoding UTF8 = new System.Text.UTF8Encoding();
using ( MD5CryptoServiceProvider HashProvider = new MD5CryptoServiceProvider() ) {
byte[] TDESKey = bPassword;
using ( TripleDESCryptoServiceProvider TDESAlgorithm = new TripleDESCryptoServiceProvider { Key = TDESKey, Mode = CipherMode.ECB, Padding = PaddingMode.PKCS7 } ) {
byte[] DataToEncrypt = UTF8.GetBytes( Message );
try {
ICryptoTransform Encryptor = TDESAlgorithm.CreateEncryptor();
Results = Encryptor.TransformFinalBlock( DataToEncrypt, 0, DataToEncrypt.Length );
} finally {
TDESAlgorithm.Clear();
HashProvider.Clear();
}
}
}
return Convert.ToBase64String( Results );
}
// Encrypt using Password as byte array
private string Encrypt( string Message, byte[] Password ) {
byte[] Results = null;
System.Text.UTF8Encoding UTF8 = new System.Text.UTF8Encoding();
using ( MD5CryptoServiceProvider HashProvider = new MD5CryptoServiceProvider() ) {
byte[] TDESKey = HashProvider.ComputeHash( UTF8.GetBytes( UTF8.GetString( Password ) ) );
using ( TripleDESCryptoServiceProvider TDESAlgorithm = new TripleDESCryptoServiceProvider { Key = TDESKey, Mode = CipherMode.ECB, Padding = PaddingMode.PKCS7 } ) {
byte[] DataToEncrypt = UTF8.GetBytes( Message );
try {
ICryptoTransform Encryptor = TDESAlgorithm.CreateEncryptor();
Results = Encryptor.TransformFinalBlock( DataToEncrypt, 0, DataToEncrypt.Length );
} finally {
TDESAlgorithm.Clear();
HashProvider.Clear();
}
}
}
return Convert.ToBase64String( Results );
}
// Encrypt using Password as string
public string Encrypt( string Message, string Password ) {
byte[] Results = null;
System.Text.UTF8Encoding UTF8 = new System.Text.UTF8Encoding();
// Step 1. We hash the Passphrase using MD5
// We use the MD5 hash generator as the result is a 128 bit byte array
// which is a valid length for the Triple DES encoder we use below
using ( MD5CryptoServiceProvider HashProvider = new MD5CryptoServiceProvider() ) {
byte[] TDESKey = HashProvider.ComputeHash( UTF8.GetBytes( Password ) );
// Step 2. Create a new TripleDESCryptoServiceProvider object
// Step 3. Setup the encoder
using ( TripleDESCryptoServiceProvider TDESAlgorithm = new TripleDESCryptoServiceProvider { Key = TDESKey, Mode = CipherMode.ECB, Padding = PaddingMode.PKCS7 } ) {
// Step 4. Convert the input string to a byte[]
byte[] DataToEncrypt = UTF8.GetBytes( Message );
// Step 5. Attempt to encrypt the string
try {
ICryptoTransform Encryptor = TDESAlgorithm.CreateEncryptor();
Results = Encryptor.TransformFinalBlock( DataToEncrypt, 0, DataToEncrypt.Length );
} finally {
// Clear the Triple Des and Hashprovider services of any sensitive information
TDESAlgorithm.Clear();
HashProvider.Clear();
}
}
}
// Step 6. Return the encrypted string as a base64 encoded string
return Convert.ToBase64String( Results );
}
#endregion
#region "Decrypt"
// Decrypt using Password from Property (pre-hashed)
public string Decrypt( string Message ) {
byte[] Results = null;
System.Text.UTF8Encoding UTF8 = new System.Text.UTF8Encoding();
using ( MD5CryptoServiceProvider HashProvider = new MD5CryptoServiceProvider() ) {
byte[] TDESKey = this.bPassword;
using ( TripleDESCryptoServiceProvider TDESAlgorithm = new TripleDESCryptoServiceProvider { Key = TDESKey, Mode = CipherMode.ECB, Padding = PaddingMode.PKCS7 } ) {
byte[] DataToDecrypt = Convert.FromBase64String( Message );
try {
ICryptoTransform Decryptor = TDESAlgorithm.CreateDecryptor();
Results = Decryptor.TransformFinalBlock( DataToDecrypt, 0, DataToDecrypt.Length );
} finally {
TDESAlgorithm.Clear();
HashProvider.Clear();
}
}
}
return UTF8.GetString( Results );
}
// Decrypt using Password as Byte array
public string Decrypt( string Message, byte[] Password ) {
byte[] Results = null;
System.Text.UTF8Encoding UTF8 = new System.Text.UTF8Encoding();
using ( MD5CryptoServiceProvider HashProvider = new MD5CryptoServiceProvider() ) {
byte[] TDESKey = HashProvider.ComputeHash( UTF8.GetBytes( UTF8.GetString( Password ) ) );
using ( TripleDESCryptoServiceProvider TDESAlgorithm = new TripleDESCryptoServiceProvider { Key = TDESKey, Mode = CipherMode.ECB, Padding = PaddingMode.PKCS7 } ) {
byte[] DataToDecrypt = Convert.FromBase64String( Message );
try {
ICryptoTransform Decryptor = TDESAlgorithm.CreateDecryptor();
Results = Decryptor.TransformFinalBlock( DataToDecrypt, 0, DataToDecrypt.Length );
} finally {
TDESAlgorithm.Clear();
HashProvider.Clear();
}
}
}
return UTF8.GetString( Results );
}
// Decrypt using Password as string
public string Decrypt( string Message, string Password ) {
byte[] Results = null;
System.Text.UTF8Encoding UTF8 = new System.Text.UTF8Encoding();
// Step 1. We hash the pass phrase using MD5
// We use the MD5 hash generator as the result is a 128-bit byte array
// which is a valid length for the Triple DES encoder we use below
using ( MD5CryptoServiceProvider HashProvider = new MD5CryptoServiceProvider() ) {
byte[] TDESKey = HashProvider.ComputeHash( UTF8.GetBytes( Password ) );
// Step 2. Create a new TripleDESCryptoServiceProvider object
// Step 3. Setup the decoder
using ( TripleDESCryptoServiceProvider TDESAlgorithm = new TripleDESCryptoServiceProvider { Key = TDESKey, Mode = CipherMode.ECB, Padding = PaddingMode.PKCS7 } ) {
// Step 4. Convert the input string to a byte[]
byte[] DataToDecrypt = Convert.FromBase64String( Message );
// Step 5. Attempt to decrypt the string
try {
ICryptoTransform Decryptor = TDESAlgorithm.CreateDecryptor();
Results = Decryptor.TransformFinalBlock( DataToDecrypt, 0, DataToDecrypt.Length );
} finally {
// Clear the Triple Des and Hash provider services of any sensitive information
TDESAlgorithm.Clear();
HashProvider.Clear();
}
}
}
// Step 6. Return the decrypted string in UTF8 format
return UTF8.GetString( Results );
}
#endregion
}
For PHP 7+ mccrypt wont work, so here the solution for encrypt and decrypt using the library phpseclib:
$des = new \phpseclib\Crypt\TripleDES(\phpseclib\Crypt\TripleDES::MODE_ECB);
$key = YOURKEY;
$p = md5(utf8_encode($key),TRUE);
$p .= substr($p,0,8);
$p - $key;
$des->setKey($p);
$phpEncrypted = $des->encrypt("Encrypted using PHP");
$vbEncrypted = "5Ittyr0+jiI7QQmPrvSVnP3s2CeoTJmF"; // Encrypted using VB.NET
echo "PHP Encrypted: " . $phpEncrypted . '<br />';
echo "VB Encrypted: " . $vbEncrypted . '<br />';
echo "PHP Encrypted (decrypted result): " . $des->decrypt(base64_decode($phpEncrypted)) . '<br />';
echo "VB Encrypted (decrypted result): " . $des->decrypt(base64_decode($vbEncrypted)) . '<br />';

VB.NET http response

I am trying to post 2 variables to a php script and then return the text that is displayed on the website.
I VB6, I did it the following way, it worked perfectly fine.
Can somebody please tell me how to do this in VB.NET?
Public Function GetHTTPResponse() As String
Dim sPost$
sPost$ = "http://www.somedomain.com/somescript.php"
sPost$ = sPost$ & "?variable1=MYVAR1"
sPost$ = sPost$ & "&variable2=MYVAR2"
'=======================================================
'"?" Prefix 1st Variable, "&" prefix for subsequent vars
'=======================================================
Dim iPos&
iPos = InStr(sPost, "?")
If (iPos = 0) Then
Exit Function
End If
Dim sDomain$
sDomain$ = Left$(sPost, (iPos - 1))
'====================================
'Pack the post data into a byte array
'====================================
Dim sPostData As String
sPostData = Right$(sPost, Len(sPost) - iPos)
Debug.Print sPostData
Dim bytpostdata() As Byte
pBuildPostData bytpostdata(), sPostData
'=============================
'Write the byte into a variant
'=============================
Dim varPostData As Variant
varPostData = bytpostdata
'=================
'Create the Header
'=================
Dim sHeader$
sHeader = "application/x-www-form-urlencoded" + Chr(10) + Chr(13)
'=============
'Post the data
'=============
Dim xmlhttp As Object
Set xmlhttp = CreateObject("MSXML2.ServerXMLHTTP")
xmlhttp.Open "POST", sDomain, False
xmlhttp.setRequestHeader "Content-Type", sHeader
xmlhttp.sEnd varPostData
Dim sRet$
sRet = xmlhttp.responseText
GetHTTPResponse = sRet
End Function
I finally found the solution here:
http://www.pcreview.co.uk/forums/using-webclient-webrequest-webresponse-post-postdata-and-get-result-t1222629.html

Categories