VB.NET ROT13 Encode Function

ROT13 algorithm illustration

You want to implement the ROT13 algorithm for encoding plain text in your VB.NET program. The concept of ROT13 is that the letters A-Z and a-z are rotated 13 places, which scrambles the text but is easily reversible.

Example

To begin, the Main function calls the Rot13 function and we test to make sure the Rot13 function, when called twice, reverses the operation correctly. In the Rot13 function, we receive one String parameter and return a new String value.

This VB example method implements the ROT13 transformation cipher.

Program that implements ROT13 algorithm [VB.NET]

Module Module1
    Sub Main()
	Console.WriteLine("dotnetperls.com ZAza")
	Console.WriteLine(Rot13("dotnetperls.com ZAza"))
	Console.WriteLine(Rot13(Rot13("dotnetperls.com ZAza")))
    End Sub

    Public Function Rot13(ByVal value As String) As String
	' Could be stored as integers directly.
	Dim lowerA As Integer = Asc("a"c)
	Dim lowerZ As Integer = Asc("z"c)
	Dim lowerM As Integer = Asc("m"c)

	Dim upperA As Integer = Asc("A"c)
	Dim upperZ As Integer = Asc("Z"c)
	Dim upperM As Integer = Asc("M"c)

	' Convert to character array.
	Dim array As Char() = value.ToCharArray

	' Loop over string.
	Dim i As Integer
	For i = 0 To array.Length - 1

	    ' Convert to integer.
	    Dim number As Integer = Asc(array(i))

	    ' Shift letters.
	    If ((number >= lowerA) AndAlso (number <= lowerZ)) Then
		If (number > lowerM) Then
		    number -= 13
		Else
		    number += 13
		End If
	    ElseIf ((number >= upperA) AndAlso (number <= upperZ)) Then
		If (number > upperM) Then
		    number -= 13
		Else
		    number += 13
		End If
	    End If

	    ' Convert to character.
	    array(i) = Chr(number)
	Next i

	' Return string.
	Return New String(array)
    End Function
End Module

Output

dotnetperls.com ZAza
qbgargcreyf.pbz MNmn
dotnetperls.com ZAza
Note

Rot13 function body implementation. In the implementation of the Rot13 function, we first use the Asc function to convert several important characters to integers. These could be hard-coded in the program for a small optimization opportunity.

Val and Asc Function Examples

Using ToCharArray. Next, we invoke the ToCharArray function and then loop over all the individual characters in the string. We use Asc on each character to convert it to its ASCII representation. The shifting logic then tests letters and changes their values to be 13 greater or 13 less. Finally, the String constructor converts the character array back to a string and returns it.

Summary

The VB.NET programming language

The ROT13 algorithm is not a world-leading encryption technology; it is easily broken and won't stop others from reading your important secrets. But for those of us who don't have very many important secrets, it can help disguise data. Security by obscurity is actually useful if you don't really care about the security of your data very much.

VB.NET Tutorials
.NET