user10504780
user10504780

Reputation:

VB.NET Xor + Mod

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

Upvotes: 0

Views: 125

Answers (1)

Visual Vincent
Visual Vincent

Reputation: 18310

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

Upvotes: 1

Related Questions