I have IP range string below:
Dim IPRange as String = "192.168.0.1-192.168.0.100"
I used code to count IP and add into Arraylist:
Dim beginIP() As Byte = IPAddress.Parse(IPRange.Split("-")(0)).GetAddressBytes
Array.Reverse(beginIP)
Dim endIP() As Byte = IPAddress.Parse(IPRange.Split("-")(1)).GetAddressBytes
Array.Reverse(endIP)
Dim IPbegin As UInt32 = BitConverter.ToUInt32(beginIP, 0)
Dim IPend As UInt32 = BitConverter.ToUInt32(endIP, 0)
Dim total as Integer = 0
Dim arr as New ArrayList()
For i As UInt32 = IPbegin To IPend
Dim IPbyte() As Byte = BitConverter.GetBytes(i)
Array.Reverse(IPbyte)
Dim IPCheck As String = New IPAddress(IPbyte).ToString
total += 1
arr.Add(IPCheck)
Next
But I have thousand IPRange like that with billion IP, loop make my application very slow. How can I speed up this code or another way to calculate IP range in this case?
Using your code
Dim stpw As Stopwatch = Stopwatch.StartNew
Dim IPRange As String = "192.168.0.0-192.200.255.255"
Dim beginIP() As Byte = IPAddress.Parse(IPRange.Split("-"c)(0)).GetAddressBytes
Array.Reverse(beginIP)
Dim endIP() As Byte = IPAddress.Parse(IPRange.Split("-"c)(1)).GetAddressBytes
Array.Reverse(endIP)
Dim IPbegin As UInt32 = BitConverter.ToUInt32(beginIP, 0)
Dim IPend As UInt32 = BitConverter.ToUInt32(endIP, 0)
Dim total As Integer = 0
For i As UInt32 = IPbegin To IPend
Dim IPbyte() As Byte = BitConverter.GetBytes(i)
Array.Reverse(IPbyte)
Dim IPCheck As String = New IPAddress(IPbyte).ToString
total += 1
Next
stpw.Stop()
Debug.WriteLine("{0:n0} in {1}", total, stpw.Elapsed)
with a larger range produced these results.
2,162,688 in 00:00:00.3756208
Related
First of all, if i do encryption and decryption on the same computer, it works fine. Bu when i want to decrypt a file which encrypted on another computer with same key, it does not work. Error tells 'Parameter is invalid'. Here are the defines;
Dim cspp As New CspParameters
Dim rsa As New RSACryptoServiceProvider
Dim bVis As New baseVisitor
Dim encDec As New EncryptDecrypt
Public encFolder As String = ""
Public decFolder As String = ""
Public keyName As String = ""
Here is how can i define key;
Public Function GetKey() As Boolean
Dim sonuc As Boolean = False
Try
keyName = "keyName25*-"
If keyName.Length > 4 Then
cspp.KeyContainerName = keyName
rsa = New RSACryptoServiceProvider(cspp)
rsa.PersistKeyInCsp = True
sonuc = True
End If
Catch ex As Exception
sonuc = False
End Try
Return sonuc
End Function
After getting key here is the encryption code;
Public Sub EncryptFile(ByVal decFile As String)
Dim rjndl As RijndaelManaged = New RijndaelManaged()
rjndl.KeySize = 256
rjndl.BlockSize = 256
rjndl.Mode = CipherMode.CBC
Dim transform As ICryptoTransform = rjndl.CreateEncryptor()
Dim keyEncrypted As Byte() = rsa.Encrypt(rjndl.Key, False)
Dim LenK As Byte() = New Byte(3) {}
Dim LenIV As Byte() = New Byte(3) {}
Dim lKey As Integer = keyEncrypted.Length
LenK = BitConverter.GetBytes(lKey)
Dim lIV As Integer = rjndl.IV.Length
LenIV = BitConverter.GetBytes(lIV)
Dim startFileName As Integer = decFile.LastIndexOf("\") + 1
Dim outFile As String = decFile
Using outFs As FileStream = New FileStream(outFile, FileMode.Create)
outFs.Write(LenK, 0, 4)
outFs.Write(LenIV, 0, 4)
outFs.Write(keyEncrypted, 0, lKey)
outFs.Write(rjndl.IV, 0, lIV)
Using outStreamEncrypted As CryptoStream = New CryptoStream(outFs, transform, CryptoStreamMode.Write)
Dim count As Integer = 0
Dim offset As Integer = 0
Dim blockSizeBytes As Integer = rjndl.BlockSize / 8
Dim data As Byte() = New Byte(blockSizeBytes - 1) {}
Dim bytesRead As Integer = 0
Using inFs As FileStream = New FileStream(decFile, FileMode.Open)
Do
count = inFs.Read(data, 0, blockSizeBytes)
offset += count
outStreamEncrypted.Write(data, 0, count)
bytesRead += blockSizeBytes
Loop While count > 0
inFs.Close()
End Using
outStreamEncrypted.FlushFinalBlock()
outStreamEncrypted.Close()
End Using
outFs.Close()
End Using
End Sub
Encryption works for all computers. But Decription code which is below is the problem;
Public Sub DecryptFile(ByVal enFile As String)
Dim rjndl As RijndaelManaged = New RijndaelManaged()
rjndl.KeySize = 256
rjndl.BlockSize = 256
rjndl.Mode = CipherMode.CBC
Dim LenK As Byte() = New Byte(3) {}
Dim LenIV As Byte() = New Byte(3) {}
Dim outFile As String = enFile
Using inFs As FileStream = New FileStream(enFile, FileMode.Open)
inFs.Seek(0, SeekOrigin.Begin)
inFs.Seek(0, SeekOrigin.Begin)
inFs.Read(LenK, 0, 3)
inFs.Seek(4, SeekOrigin.Begin)
inFs.Read(LenIV, 0, 3)
Dim lenK32 As Integer = BitConverter.ToInt32(LenK, 0)
Dim lenIV32 As Integer = BitConverter.ToInt32(LenIV, 0)
Dim startC As Integer = lenK32 + lenIV32 + 8
Dim lenC As Integer = CInt(inFs.Length) - startC
Dim KeyEncrypted As Byte() = New Byte(lenK32 - 1) {}
Dim IV As Byte() = New Byte(lenIV32 - 1) {}
inFs.Seek(8, SeekOrigin.Begin)
inFs.Read(KeyEncrypted, 0, lenK32)
inFs.Seek(8 + lenK32, SeekOrigin.Begin)
inFs.Read(IV, 0, lenIV32)
Dim KeyDecrypted As Byte() = rsa.Decrypt(KeyEncrypted, False)
Dim transform As ICryptoTransform = rjndl.CreateDecryptor(KeyDecrypted, IV)
Using outFs As FileStream = New FileStream(outFile, FileMode.Create)
Dim count As Integer = 0
Dim offset As Integer = 0
Dim blockSizeBytes As Integer = rjndl.BlockSize / 8
Dim data As Byte() = New Byte(blockSizeBytes - 1) {}
inFs.Seek(startC, SeekOrigin.Begin)
Using outStreamDecrypted As CryptoStream = New CryptoStream(outFs, transform, CryptoStreamMode.Write)
Do
count = inFs.Read(data, 0, blockSizeBytes)
offset += count
outStreamDecrypted.Write(data, 0, count)
Loop While count > 0
outStreamDecrypted.FlushFinalBlock()
outStreamDecrypted.Close()
End Using
outFs.Close()
End Using
inFs.Close()
End Using
End Sub
Using same key must solve the problem but it error all the time. I searched everywhere. Is there anybody to help me?
NOTE : I just want to encrypt-decrypt jpg files
I'm trying to turn every value of an eight digit string, called "d8", into its ASCII value so then I have 8 integers. I then want to add them together to form one integer and display this value into OffFac.Text. But it always displays this error "Arithmetic operation resulted in an overflow".
Dim d8 As String
Dim Step2 As Integer
d8 = DEight.Text
Dim RandomNumber2C As Char = d8.Substring(0, 1)
Dim RandomNumber22C As Char = d8.Substring(1, 1)
Dim RandomNumber32C As Char = d8.Substring(2, 1)
Dim RandomNumber42C As Char = d8.Substring(3, 1)
Dim RandomNumber52C As Char = d8.Substring(4, 1)
Dim RandomNumber62C As Char = d8.Substring(5, 1)
Dim RandomNumber72C As Char = d8.Substring(6, 1)
Dim RandomNumber82C As Char = d8.Substring(7, 1)
Dim RandomNumberX As String = Asc(Mid(RandomNumber2C, 1))
Dim RandomNumber2X As String = Asc(Mid(RandomNumber22C,1))
Dim RandomNumber3X As String = Asc(Mid(RandomNumber32C, 1))
Dim RandomNumber4X As String = Asc(Mid(RandomNumber42C, 1))
Dim RandomNumber5X As String = Asc(Mid(RandomNumber52C, 1))
Dim RandomNumber6X As String = Asc(Mid(RandomNumber62C, 1))
Dim RandomNumber7X As String = Asc(Mid(RandomNumber72C, 1))
Dim RandomNumber8X As String = Asc(Mid(RandomNumber82C, 1))
Dim RandomNumberXX As String = CLng(RandomNumberX)
Dim RandomNumber2XX As String = CLng(RandomNumber2X)
Dim RandomNumber3XX As String = CLng(RandomNumber3X)
Dim RandomNumber4XX As String = CLng(RandomNumber4X)
Dim RandomNumber5XX As String = CLng(RandomNumber5X)
Dim RandomNumber6XX As String = CLng(RandomNumber6X)
Dim RandomNumber7XX As String = CLng(RandomNumber7X)
Dim RandomNumber8XX As String = CLng(RandomNumber8X)
Step2 = RandomNumberXX + RandomNumber2XX + RandomNumber3XX + RandomNumber4XX + RandomNumber5XX + RandomNumber6XX + RandomNumber7XX + RandomNumber8XX
Step2 = OffFac.Text
You are trying to concatenate (append a series of strings to one another) a series of numbers that are the ascii values of the numeric characters entered into your text box.
With the string "12345678" you get the following.
"49" + "50" + "51" + "52" + "53" + "54" + "55" + "56" = "4950515253545556"
The number 4950515253545556 is too large to be assigned to an integer.
Also, your last assignment statement should be
OffFac.text = step2
You probably want to do something like this
Dim RandomNumberX As Integer = Asc(Mid(RandomNumber2C, 1))
Dim RandomNumber2X As Integer = Asc(Mid(RandomNumber22C, 1))
Dim RandomNumber3X As Integer = Asc(Mid(RandomNumber32C, 1))
Dim RandomNumber4X As Integer = Asc(Mid(RandomNumber42C, 1))
Dim RandomNumber5X As Integer = Asc(Mid(RandomNumber52C, 1))
Dim RandomNumber6X As Integer = Asc(Mid(RandomNumber62C, 1))
Dim RandomNumber7X As Integer = Asc(Mid(RandomNumber72C, 1))
Dim RandomNumber8X As Integer = Asc(Mid(RandomNumber82C, 1))
Dim RandomNumberXX As Integer = CLng(RandomNumberX)
Dim RandomNumber2XX As Integer = CLng(RandomNumber2X)
Dim RandomNumber3XX As Integer = CLng(RandomNumber3X)
Dim RandomNumber4XX As Integer = CLng(RandomNumber4X)
Dim RandomNumber5XX As Integer = CLng(RandomNumber5X)
Dim RandomNumber6XX As Integer = CLng(RandomNumber6X)
Dim RandomNumber7XX As Integer = CLng(RandomNumber7X)
Dim RandomNumber8XX As Integer = CLng(RandomNumber8X)
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)
I am having a issue with decrypting, my goal is to be able to encrypt/decrypt with/without base64 encoding on the encrypted string. As of now I can encrypt/decrypt with base64 and encrypt without it but not decrypt without it. I get errors regarding the padding being incorrect.
Thanks in advance!
Here is my encryption/decryption function:
Public Function DoCryptWork(Type As String, Data As String) As String
Dim Pass As String = Hasher.TextBoxPassword.Text
Dim Salt As String = Hasher.TextBoxSalt.Text
Dim Vect As String = Hasher.TextBoxIntVector.Text
Select Case Type
Case "e"
Try
Dim PassPhrase As String = Pass
Dim SaltValue As String = Salt
Dim HashAlgorithm As String = My.Settings.HashAlgorithm
Dim PasswordIterations As Integer = 2
Dim InitVector As String = Vect
Dim KeySize As Integer = 256
Dim InitVectorBytes As Byte() = Encoding.ASCII.GetBytes(InitVector)
Dim SaltValueBytes As Byte() = Encoding.ASCII.GetBytes(SaltValue)
Dim PlainTextBytes As Byte() = Encoding.UTF8.GetBytes(Data)
Dim Password As New PasswordDeriveBytes(PassPhrase, SaltValueBytes, HashAlgorithm, PasswordIterations)
Dim KeyBytes As Byte() = Password.GetBytes(KeySize \ 8)
Dim SymmetricKey As New RijndaelManaged()
SymmetricKey.Mode = CipherMode.CBC
Dim Encryptor As ICryptoTransform = SymmetricKey.CreateEncryptor(KeyBytes, InitVectorBytes)
Dim MemoryStream As New MemoryStream()
Dim CryptoStream As New CryptoStream(MemoryStream, Encryptor, CryptoStreamMode.Write)
CryptoStream.Write(PlainTextBytes, 0, PlainTextBytes.Length)
CryptoStream.FlushFinalBlock()
Dim CipherTextBytes As Byte() = MemoryStream.ToArray()
MemoryStream.Close()
CryptoStream.Close()
Dim CipherText As String = Nothing
If My.Settings.Base64EncodeMD5Hash = True Then
CipherText = Convert.ToBase64String(CipherTextBytes)
Return CipherText
Else
Dim TextCipher As New StringBuilder()
For n As Integer = 0 To CipherTextBytes.Length - 1
TextCipher.Append(CipherTextBytes(n).ToString("X2"))
Next n
CipherText = TextCipher.ToString()
Return CipherText
End If
Catch ex As Exception
MsgBox("Encryption was unsuccessfull!", MsgBoxStyle.Critical, "Error")
Return "Encryption was unsuccessfull!"
End Try
Case "d"
Try
Dim PassPhrase As String = Pass
Dim SaltValue As String = Salt
Dim HashAlgorithm As String = My.Settings.HashAlgorithm
Dim PasswordIterations As Integer = 2
Dim InitVector As String = Vect
Dim KeySize As Integer = 256
Dim InitVectorBytes As Byte() = Encoding.ASCII.GetBytes(InitVector)
Dim SaltValueBytes As Byte() = Encoding.ASCII.GetBytes(SaltValue)
Dim CipherTextBytes As Byte() = Nothing
If My.Settings.Base64EncodeMD5Hash = True Then
CipherTextBytes = Convert.FromBase64String(Data)
Else
Dim bytedata As Byte() = Encoding.UTF8.GetBytes(Data)
CipherTextBytes = bytedata
End If
Dim Password As New PasswordDeriveBytes(PassPhrase, SaltValueBytes, HashAlgorithm, PasswordIterations)
Dim KeyBytes As Byte() = Password.GetBytes(KeySize \ 8)
Dim SymmetricKey As New RijndaelManaged()
SymmetricKey.Mode = CipherMode.CBC
Dim Decryptor As ICryptoTransform = SymmetricKey.CreateDecryptor(KeyBytes, InitVectorBytes)
Dim MemoryStream As New MemoryStream(CipherTextBytes)
Dim CryptoStream As New CryptoStream(MemoryStream, Decryptor, CryptoStreamMode.Read)
Dim PlainTextBytes As Byte() = New Byte(CipherTextBytes.Length - 1) {}
Dim DecryptedByteCount As Integer = CryptoStream.Read(PlainTextBytes, 0, PlainTextBytes.Length)
MemoryStream.Close()
CryptoStream.Close()
Dim PlainText As String = Encoding.UTF8.GetString(PlainTextBytes, 0, DecryptedByteCount)
Return PlainText
Catch Ex As Exception
MsgBox("Decryption was unsuccessfull!" & vbNewLine & vbNewLine & Ex.ToString(), MsgBoxStyle.Critical, "Error")
Return "Decryption was unsuccessfull!"
End Try
Case Else
Return "Error! Invalid Case Selected We should never see this but just to be safe we'll show this message if the wrong case is selected!"
End Select
Return True
End Function
I call the function as so:
TextBoxOutput.Text = Encryption.DoCryptWork("e", TextBoxInput.Text) ' encrypt data.
TextBoxOutput.Text = Encryption.DoCryptWork("d", TextBoxInput.Text) ' decrypt data.
When you convert the bytes to hex, you output two hex digits per byte. When you convert that hex back to bytes, you're converting every hex digit to a byte instead of every pair of hex digits.
Actually, I just took another look and noticed that you're not even keeping the earlier bytes. This loop:
For n As Integer = 0 To Data.Length - 1
CipherTextBytes = Convert.ToByte(Data(n))
Next n
sets CipherTextBytes on each iteration so you're going to replace the previous byte each time, so you only end up keeping the byte from the last digit.
I have the following variable.
I need to find how many numbers are before the decimal point and after the decimal point.
Dim x As Long = 123.456
I have tried converting this into a string
Dim xstr As String = x.ToString(x)
Dim searchChar As String = "."
How can I display the number of characters before the decimal point.
i.e. '3'
and also, the number of characters after the decimal point.
'3'.
You can call String.Split, like this:
Dim x As Double = 123.456
Dim xstr As String = x.ToString()
Dim searchChar As String = "."
Dim parts() As String = xstr.Split({searchChar}, StringSplitOptions.None)
Dim firstLength As Integer = parts(0).Length
Dim secondLength As Integer = parts(1).Length
Another possible solution, based on String.Substring():
Dim x As Double = 123.456
Dim xstr As String = x.ToString(NumberFormatInfo.InvariantInfo)
Dim beforeDecimalSeparator As Integer = xstr.Length
Dim afterDecimalSeparator As Integer = 0
Dim decimalSeparatorPosition As Integer = xstr.IndexOf("."c)
If decimalSeparatorPosition > -1 Then
beforeDecimalSeparator = xstr.Substring(0, decimalSeparatorPosition).Length
afterDecimalSeparator = xstr.Substring(decimalSeparatorPosition + 1).Length
End If
in your way:
xstr.Substring(xstr.IndexOf("."c) + 1)
But you do not need convert to String.
Dim y = x Mod 1
You can also use IndexOf to solve this issue.
Dim x As Double = 123.456
Dim xstr As String = x.ToString()
Dim mIndex As Integer = xstr.IndexOf(".")
Dim firstLength As Integer = mIndex;
Dim secondLength As Integer = (xstr.Length - mIndex) -1