VB.NET Xor + Mod - vb.net

I'm very new to VB.NET language so there are some things I'm still learning and I need some help here. So I'd appreciate any guidance.
I'm making an XOR encryption app where there's a key, input and output. The flow is like this: Key XOR Input and the result will appear as the output. I managed to successfully come out with workable codes for that part though.
However, right now, I need to make a continuation from that part. I need the output to come out within the ASCII range of 33 - 126 (DEC) only.
I have not done anything much in terms of coding as I can't seem to find the right guide. Additionally, I don't really know where to start except that some mathematical logic (MOD) is involved here.
So any pointers? Thank you.
I am using Visual Studio (2017) and here's my code:
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim key As String
Dim input As String
Dim output As String
Dim keyCounter As Integer = 0
Dim length As Integer
key = TextBox1.Text
input = TextBox2.Text
length = key.Length
For Each letter As Char In input
output = output & Chr(Asc(letter) Xor Asc(key.Chars(keyCounter)))
If keyCounter = length - 1 Then
keyCounter = 0
Else
keyCounter += 1
End If
Next
TextBox3.Text = output
End Sub
End Class

The math is quite simple. To constrain a number within a range using modulo start by calculating how many numbers there are in the range (inclusive):
126 - 33 + 1 = 94
Then take your value and calculate the modulo using the length, and add the lower value of the range (33) to make it go from 33-126 instead of 0-93:
(value Mod 94) + 33
Alternatively, if you need numbers that already are in the range 33-126 to not change you can subtract the lower value first:
((value - 33) Mod 94) + 33

Related

Input sequence / Output number VB.Net

I currently have a question with an activity which I am attempting.
The question is as follows:
Steve wants to enter all his staff member's names into a system. He has the following criteria however:
Must be last names.
Must be in the correct format.
Must calculate and output the number of surnames.
The format must be as the below example:
**stevens#smith#thomas#mitchell#adams**
To summarise:
The program must input the character sequence (made up of one or more surenames)
Check that the character sequence has a valid format.
Calculate and output the number of surnames.
This is what I have done so far - however I was wondering if there were any way that I could remove the array and make the code simpler and easier to remember. Any ideas are much appreciated!
Module Module1
Sub Main()
Dim sequence As String
Dim surnamecount As Integer = 0
Dim sequencearray() As String
Console.WriteLine("Please enter a character sequence")
sequence = Console.ReadLine
If Len(sequence) >= 5 And sequence.Substring(0, 2) = "**" And sequence.Substring() Then
sequencearray = Split(sequence, "#")
sequencearray(0) = sequencearray(0).Substring(2)
sequencearray(UBound(sequencearray)) = sequencearray(UBound(sequencearray)).Substring(0, Len(sequencearray(UBound(sequencearray))) - 2)
For i As Integer = 0 To UBound(sequencearray)
Console.WriteLine(sequencearray(i))
surnamecount = surnamecount + 1
Next
Console.ReadLine()
End Sub
Thank you in advance!

How to use the value of one variable in the name of another in VB.NET

I am trying to make a simple keygen app (hoping to evolve it later) and am running into a problem with naming my variables:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim keylength As Double = TrackBar1.Value
Dim baseloop As Double = 1
Dim charpos As Double = 1
Do While baseloop < keylength
Randomize()
Dim name As String = "num" & charpos
Dim (name) As Integer = CInt(Int((62 * Rnd()) + 1))
'I would like to name this variable the current value of the variable "name".
baseloop = baseloop + 1
charpos = charpos + 1
Loop
End Sub
The end result should be random doubles (as many as TrackBar1.Value) containing random doubles from 1-62 and named num1, num2, num3, etc.... Then I can replace all the 1s with a, 2 with b, etc etc....
Thanks for your help
As has been said, what you claim to want to do is not possible. You can't declare an arbitrary number of variables at run time because variables are declared at design time. If you want to store an arbitrary number of values then you declare one variable and assign to that variable an array or collection of some sort. An array can be created with any size at run time and collections can grow to an arbitrary size at run time. Basically, what you're trying to do is outright wrong.
If you want an arbitrary number of Double values then create an array with a sized based on a user-defined value and then simply loop to populate it, e.g.
Dim values(userDefinedValue - 1) As Double
For i = 0 To values.GetUpperBound(0)
'...
Next
You then access the values by index. The first value is at index 0, the second at index 1, ..., the last at index GetUpperBound(0).

how i can figuring the highest number in my array...visual basic

how i can figure the highest number in my array...below is the code...can someone help me to solve my problems...n i wan to show the result in the label from the other windows form....thank u... :
Public Class Frm2
Public Parties(9) As String
Public Votes(9) As String
Dim vote As Integer
Dim Party As String
Party = TParty.Text
vote = TVote.Text
For I As Integer = 0 To Parties.Length - 1
If Parties(I) = "" Then
Parties(I) = TParty.Text()
For J As Integer = 0 To Votes.Length - 1
If Votes(J) = "" Then
Votes(J) = TVote.Text()
MsgBox(TParty.Text & TVote.Text & " votes")
TParty.Clear()
TVote.Clear()
Exit Sub
End If
Next J
End If
Next
MsgBox("you can vote now")
If you want to use an algorithm to find the highest number into an array (let's say Votes), the classic is coming from the so-called Bubble Sort:
Dim max As Long 'change the type accordingly, for example if votes are 1-10 then Integer is better
max = Votes(0) 'set the first vote as the max
For j = 1 To Votes.Length - 1
If Votes(j) >= max Then max = Votes(j) 'if another element is larger, then it is the max
Next j
Now the variable max stores the highest value of the array Votes, that you can show anywhere as, for example, in MyForm.MyLabel.Text = max. More useful info here.
Please note that now you declare Public Votes(9) As String, which means they are strings so not usable as numbers. You might want to declare them with a different data type, or use the CInt() method to convert strings in integers as suggested by ja72.
I thought this would only work with a Variant array, but in quick testing it seems to work with an array of Longs as well:
Dim Votes(9) as Long
Dim Max As Long
Max=WorksheetFunction.Max(Votes)
Note that, as Matteo says, you should change Votes() to an array of numeric types. I'd use Long, as it's a native VBA type.
EDIT: As noted by Dee, the code in this question is actually VB.Net. I added that as a tag. In VBA the solution would be even simpler, as Max is an array property:
Max=Votes.Max
(I suppose it would be a good idea to change the variable name from "Max".)

Get substring until first numeric character

like my title already explained, I want to get a substring of a string (who contains a address) and I would like to have only the street..
It's not possible to only take the text (non-numeric) chars, because then the box will remain.
It's not possible to take substring till first space, because the streetname can contain a space..
For example 'developerstreet 123a' -> would like to have 'developerstreet'
The 'a' is a box number of the house, which I'm not interested in..
How can I do this in VB.NET?
Parsing addresses is notoriously difficult, so I caution you to make sure that you a very deliberate about the choices you make. I would strongly recommend reviewing the documentation provided by the postal service. If these are US addresses, you should start by looking at the USPS Publication 28.
However, to answer your specific question, you can find the index of the first numeric character in a string by using the Char.IsDigit method. You may also want to take a look at the Char.IsNumber method, but that's probably more inclusive than what you really want. For instance, this will get the index of the first numeric character in the input string:
Dim index As Integer = -1
For i As Integer = 0 to input.Length - 1
If Char.IsDigit(input(i)) Then
index = i
Exit For
End If
Next
However, for complex string parsing, like this, I would suggest learning Regular Expressions. Getting the non-numeric portion at the beginning of a string becomes trivial with RegEx:
Dim m As Match = Regex.Match(input, "^\D+")
If m.Success Then
Dim nonNumericPart As String = m.Value
End If
Here is the meaning of the regular expression in the above example:
^ - The matching string must start at the beginning of the line
\D - Any non-numeric character
+ - One or more times
try this:
Private Sub MyFormLoad(sender As Object, e As EventArgs) Handles Me.Load
Dim str As String = "developerstreet 123a"
Dim index As Integer = GetIndexOfNumber(str)
Dim substr As String = str.Substring(0, index)
MsgBox(substr)
End Sub
Public Function GetIndexOfNumber(ByVal str As String)
For n = 0 To str.Length - 1
If IsNumeric(str.Substring(n, 1)) Then
Return n
End If
Next
Return -1
End Function
output will be: developerstreet
text.Substring(0, text.IndexOfAny("0123456789"))

Generate A Unquie Id (GUID) That Is Only 25 Characters In Length

What is the best appraoch to generate unquie ID's (no special characters) that will be 25 characters in length? I was thinking of generating a GUID and taking a substring of that, but I dont know if thats the best idea for uniqueness.
This is for dissconnected systems use. Creating a primary key in a database will not work in my situation. I need to create a unquie ID manually
I tried this but I am seeing duplicates in the output for some reason. So it doesnt seem too unquie even in this simple test..
Sub Main()
Dim sb As StringBuilder = New StringBuilder
For i As Integer = 1 To 100000
Dim s As String = GenerateRandomString(25, True)
sb.AppendLine(s)
sb.AppendLine(Environment.NewLine)
Next
Console.WriteLine(sb.ToString)
Console.ReadLine()
End Sub
Public Function GenerateRandomString(ByRef len As Integer, ByRef upper As Boolean) As String
Dim rand As New Random()
Dim allowableChars() As Char = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLOMNOPQRSTUVWXYZ0123456789".ToCharArray()
Dim final As String = String.Empty
For i As Integer = 0 To len - 1
final += allowableChars(rand.Next(allowableChars.Length - 1))
Next
Return IIf(upper, final.ToUpper(), final)
End Function
You’re probably seeing duplicates because New Random() is seeded according to a system clock, which may not have changed by the next iteration.
Try a cryptographically secure RNG:
Const ALLOWABLE_ALL As String = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
Const ALLOWABLE_UPPERCASE As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
Dim allowable As String = If(upper, ALLOWABLE_UPPERCASE, ALLOWABLE_ALL)
Dim result(len - 1) As Char
Dim current As Integer = 0
Using r As New Security.Cryptography.RNGCryptoServiceProvider()
Do
Dim buffer(255) As Byte
r.GetBytes(buffer)
For b As Byte In buffer
If b < allowable.Length Then
result(current) = allowable(b)
current += 1
If current = len Then Return New String(result)
End If
Next
Loop
End Using
This is also “more random” than your implementation in that letters aren’t weighted twice as heavily if upper is True.
A GUID might be 32 digits, but only if expressed in hexadecimal. That means it will only use characters 0-9 and A-F. If your string can use the entire alphabet then you can express the same GUID in fewer characters, especially if your string can be case sensitive.
See http://en.wikipedia.org/wiki/Globally_unique_identifier#Text_encoding for an example of alternative encoding, or http://web.archive.org/web/20100408172352/http://prettycode.org/2009/11/12/short-guid/ for example code. EDIT: Or Hans's method above which is much better. If you want to encode a GUID with only A-Z, a-z and 0-9 characters then you will need to look up Base-62 encoding (as opposed to base-64) because you only have 62 characters to encode into.
Stop trying to re-invent the wheel and just use .NET's built in GUID generator:
System.Guid.NewGuid()
which will generate a properly randomly seeded GUID, then simply sub-string it to your limit. Even better if you grab the last 25 chars, instead of the first 25.
PS: I don't consider this a great idea in general, because it's the entire GUID that's considered unique, not part of it, but it should satisfy what you want.