Encrypter Learn programming Visual Basic (VB.net)

Lesson:

OOP More On Classes


Exercise:

Encrypter


Objetive:

Create a class "Encrypter" to encrypt and decrypt text.

It will have a "Encrypt" method, which will receive a string and return another string. It will be a static method, so that we do not need to create any object of type "Encrypter".

There will be also a "Decrypt" method.

In this first approach, the encryption method will be a very simple one: to encrypt we will add 1 to each character, so that "Hello" would become "Ipmb", and to decrypt we would subtract 1 to each character.

An example of use might be

string newText = Encrypter.Encrypt("Hola");


Code:

Imports System
Namespace Program
    Class Encrypter
        Public Shared Function Encrypt(ByVal text As String) As String
            Dim letterInt As Integer = 0
            Dim letter As Char = " "c
            Dim textEncripted As String = ""

            For i As Integer = 0 To text.Length - 1
                letterInt = CInt(text(i)) + 1
                letter = ChrW(letterInt)
                textEncripted += letter.ToString()
            Next

            Return textEncripted
        End Function

        Public Shared Function Decrypt(ByVal text As String) As String
            Dim letterInt As Integer = 0
            Dim letter As Char = " "c
            Dim textDecripted As String = ""

            For i As Integer = 0 To text.Length - 1
                letterInt = CInt(text(i)) - 1
                letter = ChrW(letterInt)
                textDecripted += letter.ToString()
            Next

            Return textDecripted
        End Function
    End Class

    Class TextEncripted
        Private Shared Sub Main()
            Dim debug As Boolean = True
            Dim newText As String = Encrypter.Encrypt("Hola")
            Console.WriteLine("Text encripted: {0}", newText)
            Dim TextDescripted As String = Encrypter.Decrypt(newText)
            Console.WriteLine("Text Decripted: {0}", TextDescripted)
            If debug Then Console.ReadLine()
        End Sub
    End Class
End Namespace

Juan A. Ripoll - Systems Tutorials and Programming Courses ©  All rights reserved.  Legal Conditions.