Using vb.net ReadAllBytes - vb.net

I used vb .NET function ReadAllBytes to read a file and send it over a socket. When received, I used WriteAllBytes. The problem is they are not same size! The original is 16kb, but the received data is 24kb. My code is below. What am I doing wrong?
Dim bteRead() As Byte
Try
bteRead = IO.File.ReadAllBytes(filepath)
Catch ex As System.IO.IOException
End Try
Return bteRead
then i convert bytes to string and send it , and when received i convert it back from string to bytes and do the WriteAllBytes
Dim str As String = a(1)
Dim encod As New System.Text.UTF8Encoding
Dim byteData() As Byte = encod.GetBytes(str)
IO.File.WriteAllBytes("c:\lol.db", byteData)

Solution for me was to change:
Dim encod As New System.Text.UTF8Encoding
Dim byteData() As Byte = encod.GetBytes(str)
To
Dim byteData() As Byte = System.Text.Encoding.Default.GetBytes(str)

Related

Chrome Native Messaging Host VB.Net

I have had a hard time finding any support for Chrome Native Messaging Hosts in VB.Net, after much trial and error I have put together something that works for a single message at a time. However I have not been able to get the
While OpenStandardStreamIn() IsNot Nothing
part to work. If anyone has any suggestions...
OTHERWISE THIS CODE WORKS GREAT, for anyone else like me looking for a VB.Net Native Message Host:
Also, this uses Newtonsoft.Json Lib for JSON serializing...
Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports System.Text
Imports System.Threading.Tasks
Imports System.Diagnostics
Imports System.Runtime.InteropServices
Module Module1
Public Sub Main(ByVal args As String())
'create response as an array so it can be easily converted JSON
Dim ResponseString() As String = {""}
' get input from chrome extension
Dim InputString As String = OpenStandardStreamIn()
' Do whatever you want with Input, then prepare Response
ResponseString(0) = DO_SOMETHING(InputString)
' Send Response to Chrome
OpenStandardStreamOut(ResponseString)
End Sub
Public Function OpenStandardStreamIn() As String
Dim MsgLength As Integer = 0
Dim InputData As String = ""
Dim LenBytes As Byte() = New Byte(3) {} 'first 4 bytes are length
Dim StdIn As System.IO.Stream = Console.OpenStandardInput() 'open the stream
StdIn.Read(LenBytes, 0, 4) 'length
MsgLength = System.BitConverter.ToInt32(LenBytes, 0) 'convert length to Int
Dim Buffer As Char() = New Char(MsgLength - 1) {} 'create Char array for remaining bytes
Using Reader As System.IO.StreamReader = New System.IO.StreamReader(StdIn) 'Using to auto dispose of stream reader
While Reader.Peek() >= 0 'while the next byte is not Null
Reader.Read(Buffer, 0, Buffer.Length) 'add to the buffer
End While
End Using
InputData = New String(Buffer) 'convert buffer to string
Return InputData
End Function
Private Sub OpenStandardStreamOut(ByVal ResponseData() As String) 'fit the response in an array so it can be JSON'd
Dim OutputData As String = ""
Dim LenBytes As Byte() = New Byte(3) {} 'byte array for length
Dim Buffer As Byte() 'byte array for msg
OutputData = Newtonsoft.Json.JsonConvert.SerializeObject(ResponseData) 'convert the array to JSON
Buffer = System.Text.Encoding.UTF8.GetBytes(OutputData) 'convert the response to byte array
LenBytes = System.BitConverter.GetBytes(Buffer.Length) 'convert the length of response to byte array
Using StdOut As System.IO.Stream = Console.OpenStandardOutput() 'Using for easy disposal
StdOut.WriteByte(LenBytes(0)) 'send the length 1 byte at a time
StdOut.WriteByte(LenBytes(1))
StdOut.WriteByte(LenBytes(2))
StdOut.WriteByte(LenBytes(3))
For i As Integer = 0 To Buffer.Length - 1 'loop the response out byte at a time
StdOut.WriteByte(Buffer(i))
Next
End Using
End Sub
End Module
From the Chrome Extension, open a connection, send a message, and once a response is received the host will close. Check our Chrome's Dev page for a sample app/extension: https://developer.chrome.com/apps/nativeMessaging
I hope this helps somebody, and please let me know if you make any improvements!
Sub Main() ' Recursive Version
Try
Dim stdin As Stream = Console.OpenStandardInput()
Dim stdout As Stream = Console.OpenStandardOutput()
Dim MsgLength As Integer = 0
Dim InputData As String = ""
Dim LenBytes As Byte() = New Byte(3) {}
stdin.Read(LenBytes, 0, 4)
MsgLength = BitConverter.ToInt32(LenBytes, 0)
Dim Buffer As Byte() = New Byte(MsgLength - 1) {}
stdin.Read(Buffer, 0, Buffer.Length)
InputData = Encoding.UTF8.GetString(Buffer)
Dim Str As String = Newtonsoft.Json.JsonConvert.SerializeObject("[" & Now & "] Arrrr!")
Dim buff() As Byte = Encoding.UTF8.GetBytes(Str)
stdout.Write(BitConverter.GetBytes(buff.Length), 0, 4)
stdout.Write(buff, 0, buff.Length)
Main()
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Critical, "Oh, Snap!")
End Try
End Sub

VB.NET TCP Server Socket Programming - Receiving String from Byte

How to get string from this code instead of array of char ?
Client Code :
stm = tcpClient.GetStream()
Dim ascenc As New ASCIIEncoding
Dim byteData() As Byte = ascenc.GetBytes(strMessage(counter))
Thread.Sleep(2000)
Console.WriteLine("Transmitted ")
stm.Write(byteData, 0, byteData.Length())
Server code :
Dim size As Integer = TcpSocket.Receive(bitData)
Dim chars(size) As Char
For i As Integer = 0 To size
chars(i) = Convert.ToChar(bitData(i)) // i want to get the string directly, how ?
Next
Dim newString As New String(chars)
Console.WriteLine(newString)
strMessage(counter) = newString
You can use ASCIIEncoding on the server as well. Just use its GetString() method rather than GetBytes().
Dim ascenc As New ASCIIEncoding
Dim newString As String = ascenc.GetString(bitData)
You already have it implemented with your code I suggested:
Dim MyString As String = New String(MyArray)
If you want to convert the byte array you can use:
Dim MyString As String = Encoding.ASCII.GetString(bytes)

VB.NET convert UCS-2 bytes to ASCII

Ok so i am working on this program which sends a packet to a minecraft server and in return it gives me information about the server;(message of the day, players online, max players)
The problem is the response is in UCS-2
So when i send the packet to the server and get the response in bytes. How do i convert it to ascii so i can work with it?
Here is my code so far
Dim client As New System.Net.Sockets.TcpClient()
client .Connect("178.33.213.54", 25565)
Dim stream As NetworkStream = client .GetStream
'Send Bytes
Dim sendBytes As [Byte]() = {&HFE}
stream.Write(sendBytes, 0, sendBytes.Length)
'Receive Bytes
Dim bytes(client .ReceiveBufferSize) As Byte
stream.Read(bytes, 0, CInt(leclient.ReceiveBufferSize))
'Convert it to ASCII
....
'Output it to Console
....
Here is the same code in PHP, python, and ruby.
php -> https://gist.github.com/1235274
python -> https://gist.github.com/1209061
ruby -> http://pastebin.com/q5zFPcXV
The documentation is here:
http://www.wiki.vg/Protocol#Server_List_Ping_.280xFE.29
Thanks in advance!
Vidhu
Tested and working.
Dim client As New System.Net.Sockets.TcpClient()
client.Connect("178.33.213.54", 25565)
Dim stream As System.Net.Sockets.NetworkStream = client.GetStream
'Send Bytes
Dim sendBytes As [Byte]() = {&HFE}
stream.Write(sendBytes, 0, sendBytes.Length)
''Receive Bytes
Dim bytes(client.ReceiveBufferSize) As Byte
stream.Read(bytes, 0, CInt(client.ReceiveBufferSize))
Dim sb As New System.Text.StringBuilder
For i As Integer = 3 To bytes.GetUpperBound(0) Step 2
Dim byt2(1) As Byte
byt2(0) = bytes(i + 1)
byt2(1) = bytes(i)
Dim ii As Integer = BitConverter.ToInt16(byt2, 0)
'sb.Append(Hex(ii)) 'debug
sb.Append(ChrW(ii))
Next i
MsgBox(sb.ToString)
stream.Close()

Encryption of email address in vb.net

I would like to know how I can encrypt an email address via vb.net code.
I found one sample which doesn't quite work with special characters and I am getting this error:
The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters, or a non-white space character among the padding characters.
Here is the code I am trying:
'The function used to encrypt the text
Private Function Encrypt(ByVal strText As String, ByVal strEncrKey _
As String) As String
Dim byKey() As Byte = {}
Dim IV() As Byte = {&H12, &H34, &H56, &H78, &H90, &HAB, &HCD, &HEF}
Try
byKey = System.Text.Encoding.UTF8.GetBytes(Left(strEncrKey, 8))
Dim des As New DESCryptoServiceProvider()
Dim inputByteArray() As Byte = Encoding.UTF8.GetBytes(strText)
Dim ms As New MemoryStream()
Dim cs As New CryptoStream(ms, des.CreateEncryptor(byKey, IV), CryptoStreamMode.Write)
cs.Write(inputByteArray, 0, inputByteArray.Length)
cs.FlushFinalBlock()
Return Convert.ToBase64String(ms.ToArray())
Catch ex As Exception
Return ex.Message
End Try
End Function
What do you guys think? What am I doing wrong?
Thanks, Laziale
UPDATE: Full Stack trace:
System.FormatException was caught
Message=The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters, or a non-white space character among the padding characters.
Source=mscorlib
StackTrace:
at System.Convert.FromBase64String(String s)
at WEbsite.Login.Decrypt(String strText, String sDecrKey) in D:\Website\Account\Login.aspx.vb:line 213
InnerException:
UPDATE 2:
Encryption method added:
'The function used to decrypt the text
Private Function Decrypt(ByVal strText As String, ByVal sDecrKey _
As String) As String
Dim byKey() As Byte = {}
Dim IV() As Byte = {&H12, &H34, &H56, &H78, &H90, &HAB, &HCD, &HEF}
Dim inputByteArray(strText.Length) As Byte
Try
byKey = System.Text.Encoding.UTF8.GetBytes(Left(sDecrKey, 8))
Dim des As New DESCryptoServiceProvider()
inputByteArray = Convert.FromBase64String(strText)
Dim ms As New MemoryStream()
Dim cs As New CryptoStream(ms, des.CreateDecryptor(byKey, IV), CryptoStreamMode.Write)
cs.Write(inputByteArray, 0, inputByteArray.Length)
cs.FlushFinalBlock()
Dim encoding As System.Text.Encoding = System.Text.Encoding.UTF8
Return encoding.GetString(ms.ToArray())
Catch ex As Exception
Return ex.Message
End Try
End Function
I have tried your Decrypt using, as input, the encrypted text and the same key.
It works as expected. The only change I have made to your code is the use of the Substring method instead of Left as in
byKey = System.Text.Encoding.UTF8.GetBytes(strDecrKey.Substring(0, 8))
I call the two methods in this way:
Dim result as String = Encrypt("test#gmail.com", "ABCD9876")
Dim decrypted = Decrypt(result, "ABCD9876")
I get back "test#gmail.com".
-Buon Weekend anche a te-
Use an String Builder instead of string as the parameter with the special characters.
Best regards.

Shorten a string containing data

I am creating an application to create a key that is unique to each computer. This info is derived from the OS serial number and processorID.
Is there a way to 'shorten' a string? Maybe by converting it to HEX or something else...
The reason is this: I used to use a VB6 section of code (http://www.planet-source-code.com/vb...48926&lngWId=1) that gets the details and the output is only 13 digits long. Mine is a lot longer, but gets the same info...
BTW, the link I posted above won multiple awards, but I am having huge trouble in converting it to .NET. Has anyone by any chance converted it, or know of someone who has? Or a tool that actually works?
Thanks
EDIT
Here is the full working link: http://www.planet-source-code.com/vb/scripts/ShowCode.asp?txtCodeId=48926&lngWId=1
It sounds like you want a 'hashing algorithm' or 'hash function'. They are a common concept: http://en.wikipedia.org/wiki/Hash_function
Generally speaking you can simply write your own function to take a string and return a hashed number but there is some suitable code here that uses the .NET framework: http://support.microsoft.com/kb/301053
Here is a working example which retrieves the Processor ID, for the first Processor found, and the OS Serial Number; it concatenates these to strings together and then performs various encodings on them.
This is a simple VB.Net Console project. Be sure to reference the System.Management assembly in your project. Just copy and paste this code example into the main module, set a breakpoint at the end of Sub Main(), and look at the various results.
Module Module1
Sub Main()
Dim uniqueID As String = GetUniqueID()
' convert it to a base64 string
Dim encoding As New Text.ASCIIEncoding()
Dim result1 = Convert.ToBase64String(encoding.GetBytes(uniqueID))
' compress it
Dim result2 As String = CompressString(uniqueID)
Dim result3 As String = DecompressString(result2)
' encrypt it
Dim result4 As String = AES_Encrypt(uniqueID, "password")
Dim result5 As String = AES_Decrypt(result4, "password")
' hash it
Dim result6 As String = HashString(uniqueID)
End Sub
Private Function GetUniqueID() As String
Dim result As String = GetOSSerialNumber()
Dim processorIDs() As String = GetProcessorIDs()
If ((processorIDs IsNot Nothing) AndAlso (processorIDs.Count > 0)) Then
result &= processorIDs(0)
End If
Return result
End Function
Private Function GetProcessorIDs() As String()
Dim result As New List(Of String)
Dim searcher = New System.Management.ManagementObjectSearcher("Select ProcessorId from Win32_Processor")
For Each managementObj In searcher.Get()
result.Add(CStr(managementObj.Properties("ProcessorId").Value))
Next
Return result.ToArray()
End Function
Private Function GetOSSerialNumber() As String
Dim result As String = ""
Dim searcher = New System.Management.ManagementObjectSearcher("Select SerialNumber from Win32_OperatingSystem")
For Each managementObj In searcher.Get()
result = CStr(managementObj.Properties("SerialNumber").Value)
Next
Return result
End Function
Public Function CompressString(ByVal source As String) As String
Dim result As String = ""
Dim encoding As New Text.ASCIIEncoding()
Dim bytes() As Byte = encoding.GetBytes(source)
Using ms As New IO.MemoryStream
Using gzsw As New System.IO.Compression.GZipStream(ms, IO.Compression.CompressionMode.Compress)
gzsw.Write(bytes, 0, bytes.Length)
gzsw.Close()
result = Convert.ToBase64String(ms.ToArray)
End Using
End Using
Return result
End Function
Public Function DecompressString(ByVal source As String) As String
Dim result As String = ""
Dim bytes() As Byte = Convert.FromBase64String(source)
Using ms As New IO.MemoryStream(bytes)
Using gzsw As New System.IO.Compression.GZipStream(ms, IO.Compression.CompressionMode.Decompress)
Dim data(CInt(ms.Length)) As Byte
gzsw.Read(data, 0, CInt(ms.Length))
Dim encoding As New Text.ASCIIEncoding()
result = encoding.GetString(data)
End Using
End Using
Return result
End Function
Public Function AES_Encrypt(ByVal input As String, ByVal pass As String) As String
Dim AES As New System.Security.Cryptography.RijndaelManaged
Dim Hash_AES As New System.Security.Cryptography.MD5CryptoServiceProvider
Dim encrypted As String = ""
Try
Dim hash(31) As Byte
Dim temp As Byte() = Hash_AES.ComputeHash(System.Text.ASCIIEncoding.ASCII.GetBytes(pass))
Array.Copy(temp, 0, hash, 0, 16)
Array.Copy(temp, 0, hash, 15, 16)
AES.Key = hash
AES.Mode = Security.Cryptography.CipherMode.ECB
Dim DESEncrypter As System.Security.Cryptography.ICryptoTransform = AES.CreateEncryptor
Dim Buffer As Byte() = System.Text.ASCIIEncoding.ASCII.GetBytes(input)
encrypted = Convert.ToBase64String(DESEncrypter.TransformFinalBlock(Buffer, 0, Buffer.Length))
Catch ex As Exception
End Try
Return encrypted
End Function
Public Function AES_Decrypt(ByVal input As String, ByVal pass As String) As String
Dim AES As New System.Security.Cryptography.RijndaelManaged
Dim Hash_AES As New System.Security.Cryptography.MD5CryptoServiceProvider
Dim decrypted As String = ""
Try
Dim hash(31) As Byte
Dim temp As Byte() = Hash_AES.ComputeHash(System.Text.ASCIIEncoding.ASCII.GetBytes(pass))
Array.Copy(temp, 0, hash, 0, 16)
Array.Copy(temp, 0, hash, 15, 16)
AES.Key = hash
AES.Mode = Security.Cryptography.CipherMode.ECB
Dim DESDecrypter As System.Security.Cryptography.ICryptoTransform = AES.CreateDecryptor
Dim Buffer As Byte() = Convert.FromBase64String(input)
decrypted = System.Text.ASCIIEncoding.ASCII.GetString(DESDecrypter.TransformFinalBlock(Buffer, 0, Buffer.Length))
Catch ex As Exception
End Try
Return decrypted
End Function
Private Function HashString(ByVal source As String) As String
Dim encoding As New Text.ASCIIEncoding()
Dim bytes() As Byte = encoding.GetBytes(source)
Dim workingHash() As Byte = New System.Security.Cryptography.MD5CryptoServiceProvider().ComputeHash(bytes)
Dim result As String = ""
For Each b In workingHash
result = result & b.ToString("X2")
Next
Return result
End Function
End Module