Caesar Cipher encryption VB.net - vb.net

I am trying to make an encryption method in VB.net.
I plan to use arrays so you input the value and it then compares two arrays changing the value.
Console.WriteLine("Please input text")
Dim UserInput As String = Console.ReadLine
UserInput = UserInput.ToUpper()
Console.WriteLine("Original Input is " & UserInput)
Dim EncriptedText As String
Dim Numbers() As String = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "21", "22", "23", "24", "25", "26", "27"}
Dim Letters() As String = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", " "}
For counter As Integer = 0 To UserInput.Length - 1
Dim pos As Integer = Array.IndexOf(Numbers, UserInput.Chars(counter))
Dim CharValue As Char = Letters.ElementAt(pos)
UserInput = UserInput + CharValue
Console.WriteLine(UserInput)
Next
Console.Read()
End Sub
It throws an error when I try to run it.
Does anyone have any idea how I could fix it?
Error : Found on The Dim CharValue As Char Line
An unhandled exception of type 'System.ArgumentOutOfRangeException' occurred in mscorlib.dll
Additional information: Index was out of range. Must be non-negative and less than the size of the collection.
I was thinking it could be because I am trying to convert numbers to chars and if so what other methods could I use?

1) You are using the wrong array to get the index of a letter, and so the wrong array to get its enciphered value.
2) When you use Array.IndexOf like that, you need to give it a string to look for rather than a char. In your code, it is returning -1 because it didn't find the char in the array of strings (once the correct array is used).
3) You're modifying the input string in the loop, I guess you meant to use a separate variable for it.
Console.WriteLine("Please input text")
Dim userInput As String = Console.ReadLine()
userInput = userInput.ToUpper()
Console.WriteLine("Original input is " & userInput)
Dim numbers() As String = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "21", "22", "23", "24", "25", "26", "27"}
Dim letters() As String = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", " "}
Dim encryptedText As String = ""
For counter As Integer = 0 To userInput.Length - 1
Dim pos As Integer = Array.IndexOf(letters, (userInput.Chars(counter)))
Dim cipherValue As String = numbers.ElementAt(pos)
encryptedText = encryptedText & cipherValue
Console.WriteLine(encryptedText)
Next
Console.Read()
Please note that it is usual to start variable names with a lowercase letter.
Now that you can get output, you can go on to find the other problems with the code :)

Related

Retrieve String Join separated by a comma

Output Expected: I want to return the combinations of 2, in the case below, each separated by a comma and vbcrlf, for example:
1,2
3,4
5,6
and so on...
the problem is that this code below does not.
It returns my values in the line (1,2,3,4,5,6,7,8,9,10,11,12 .. and so on.
how do I make the code from button1 work properly?
Function GetCombinations(ByVal depth As Integer, ByVal values As String()) As IEnumerable(Of String)
If depth > values.Count + 1 Then Return New List(Of String)
Dim result = New List(Of String)
For i = 0 To depth - 1
For y = 0 To values.Count - 1
If i = 0 Then
result.Add(values(y))
Else
result.Add(values(i - 1) + values(y))
End If
Next
Next
Return result
End Function
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim data_array As String() = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14",
"15"}
Dim result = GetCombinations(2, data_array)
Dim resultx As String = String.Join(",", result)
TxtListScanTxt.AppendText(resultx)
End Sub
This is one way to do it - tested and working
Public Sub Main()
Dim data_array As String() = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14",
"15"}
dim second as boolean
dim sb = new stringbuilder()
For i as integer = 0 To data_array.Length - 1
if second then
sb.AppendLine(data_array(i -1) & "," & data_array(i))
second = false
continue for
end if
if i = data_array.Length - 1 then
sb.AppendLine(data_array(i))
end if
second = true
next
Console.WriteLine(sb.ToString())
End Sub
my solution
Dim data_array As String() = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14",
"15"}
Dim depth As Integer = 3, i As Integer = 1
Dim result As StringBuilder = New StringBuilder
For y = 0 To data_array.Count - 1
If i < depth Then
result.Append(data_array(y) + ",")
i += 1
Else
result.Append(data_array(y) + vbNewLine)
i = 1
End If
Next
RichTextBox1.AppendText(result.ToString)
Sub Main(args As String())
Dim arr = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15"}
'// First, we join all array values with comma to get a string.
'// Second, we find each group of two digits separated by comma (\d+,\d+)
'// and replace it ($1) with the same group PLUS the new-line character.
Dim x = Regex.Replace(String.Join(",", arr), "(\d+,\d+),?", $"$1{vbCrLf}")
End Sub

Inconsistencies in While Loop Variables

I am in the midst of writing a simple encryptor/decryptor program and have run into a small issue. All the characters are being generated a different string of characters to uniquely identify them. These strings are meant to be all the same length but don't seem to be. The code in question: (Full code can be viewed here)
Dim genLength As Integer = 0
Dim charNow As Integer = 0
Dim charGenned As String
Dim rndGend As Integer = 0
While genLength < enhancedMode
fs.Write(arrayAll(charNow))
Dim rndString As String = ""
While rndGend < encLength
Randomize()
Dim genned As Integer = CInt(Math.Ceiling(Rnd() * 46)) + 1
charGenned = arrayAll(genned)
rndString = rndString + charGenned
rndGend += 1
End While
fs.Write(rndString & vbNewLine)
rndGend = 0
charNow = charNow + 1
genLength = genLength + 1
End While
From what I can tell this should give me the result I am looking for, but the generated strings are not at all consistent in length. A sample of the output:
alh*ph)lufe$2fz!d7c0$qfd(ol6f173#
b^i24#^v0gx%01iqrpugg8)(mqsl8%
c1km5jnz0hti&u$#rqeh5ism31t^96^
dkx&6$ok!#u#*e^x6659jpvcnn258zpi
e%y1(y3%#w9kk9&h7d6gw)w72*3c9*d)j
fy#(i4yeg0%ltj#887!x4!e32^703e4l
gj$4#5&f!!zzdkvs)v##94)*rcmroy
While the string after the letter A is 32 digits long, as is for B, and C, when you get to G, the string is only 29 characters long. It is most noticeable in the fact that the program only generates strings for characters up to numeral 5, then stops:
3%y1(y3%#w9kk9&h7d6gw)w72*3c9*d)j
4y#(i4yeg0%ltj#887!x4!e32^703e4l
5j$4#5&f!!zzdkvs)
What is going amiss here?
I just tidied up a bit and changed to the Random class which I think is much easier to use. If you declaring an array in vb.net remember it is Dim variable(ubound) As Type. ubound stands for the Upper bound of the array, the highest index so an array with 47 elements would have indexes 0-46. The ubound would be 46 Dim variable(46) As String
Private r As New Random
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Button1.Enabled = False
Dim arrayLetters() As String = {"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"}
Dim arrayAll() As String = {"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "!", "#", "#", "$", "%", "^", "&", "*", "(", ")"}
Dim encLength As Integer = 16
If CheckBox2.Checked = True Then
encLength = 32
End If
Dim enhancedMode As Integer = 26
If CheckBox1.Checked = True Then
enhancedMode = 46
End If
Dim genLength As Integer = 0
Dim charNow As Integer = 0
Dim charGenned As String
Dim rndGend As Integer = 0
Dim sb As New StringBuilder
While genLength < enhancedMode
sb.Append(arrayAll(charNow))
Dim rndString As String = ""
While rndGend < encLength
Dim genned As Integer = r.Next(0, 46)
charGenned = arrayAll(genned)
rndString &= charGenned
rndGend += 1
End While
sb.AppendLine(rndString)
rndGend = 0
charNow += 1
genLength += 1
End While
Dim name As String
If TextBox1.Text = "" Then
name = "KeyGenned"
Else
name = TextBox1.Text
End If
Dim path As String = Application.StartupPath & "\" & name & ".txt"
File.WriteAllText(path, sb.ToString)
Close()
End Sub

Every time I generate a string, then close the program and generate again its the same

Well I have made this random string generate but I have recently noticed a fatal flaw. When I generate a random string, close the program and generate another random string it is the same as the first generation. Here is the code:
Public Function RandomString(ByVal length As Integer) As String
Dim strb As New System.Text.StringBuilder
Dim chars() As String = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"}
Dim UpperBound As Integer = UBound(chars)
For x As Integer = 1 To length
strb.Append(chars(Int(Rnd() * UpperBound)))
Next
Return strb.ToString
End Function
Private Sub PictureBox1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PictureBox1.Click
Try
System.Diagnostics.Process.Start("Link Removed!")
Catch
End Try
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim repeatCnt As Integer
'Check for valid numeric entry
If Integer.TryParse(TextBox2.Text, repeatCnt) Then
For repeatIdx As Integer = 1 To repeatCnt
Dim rndstring As String
'Generate random string...
rndstring = RandomString(24)
'...and append to text box with a line break
RichTextBox1.Text &= rndstring & vbCrLf
Next
Else
MessageBox.Show("Please enter a valid integer number in the text box")
End If
End Sub
Your problem is that you're running Rnd() instead of using the Random class.
In order to keep Rnd() from giving the same sequence of "random" numbers every time, Random.Next() should be called (in order to use the machine clock for the initial value / seed).
So in your case:
Dim random As New System.Random()
Public Function RandomString(ByVal length As Integer) As String
Dim strb As New System.Text.StringBuilder
Dim chars() As String = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"}
Dim UpperBound As Integer = UBound(chars)
For x As Integer = 1 To length
strb.Append(chars(Int(random.Next(UpperBound)))
Next
Return strb.ToString
End Function
Try generating a random string like this:
Public Shared Function GeneratePass() As String
Dim unique As Guid = Guid.NewGuid
Return unique.ToString.Substring(1, 6)
End Function

VB2010 Mutli-dimensional Arrays, mind-block

So I am trying to make the card game WAR in visual basic 2010. I have the following code and I kind of know what I need to do next but I just can't get to the next step.
Public Class form1
'throws an error unless this is the first class in the file
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
'click the button currently labled "loop"
Dim Cards() As String = {"Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack"} 'spades,hearts/diamonds,clubs
Dim Values() As String = {"11", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11"} 'faces is a term meaning a card that depicts a person
Dim suits() As String = {"H", "D", "C", "S"}
Dim p1deck()() As String '
'first (0) is the number of the array
'second(0) is the string
p1deck(0)(0) = "Ace"
p1deck(0)(1) = "11"
p1deck(0)(2) = "Hearts"
TextBox1.Text = p1deck(0)(0) & " of " & p1deck(0)(2)
'Cards.ToList(). add/removeAt
End Sub
End Class
You are not Initializing your p1deck array.
Try something like this:
Dim p1deck(2, 3) As String
p1deck(0, 0) = "Ace"
p1deck(0, 1) = "11"
p1deck(0, 2) = "Hearts"
TextBox1.Text = p1deck(0, 0) & " of " & p1deck(0, 2)

How do you create a New array in VB.NET? [duplicate]

This question already has answers here:
Closed 13 years ago.
Possible Duplicate:
VB.Net Initialising an array on the fly
This maybe a stupid question, but its got me exasperated. How do I declare a new array inline? Is this possible? I've tried all of the following and they all don't work.
myVar = {"a", "b", "c"}
myVar = Array(3)
myVar = Array("a", "b", "c")
myVar = New Array()
myVar = New Array(3)
myVar = New Array("a", "b", "c")
Either
Dim strings = New String() {"a", "b", "c"}
or
Dim strings() As String = {"a", "b", "c"}
should work