Microsoft & .NETVisual BasicVB .NET Tip: Encryption in Just Twelve Lines of Code!

VB .NET Tip: Encryption in Just Twelve Lines of Code!

Developer.com content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

At times, you may want to very simply encrypt a small piece of text to store in the registry, a database, or file, but you don’t want the overhead or complexity of a government-standard encryption technique.

A much simpler encryption method is required, and the following function provides just that. It’s called Crypt: Pass it your plain text and it’ll encrypt it; pass it your encrypted text and it’ll decrypt it. It’s simple and all in fewer than fifteen lines of code:

Public Function SimpleCrypt( _
       ByVal Text As String) As String
  ' Encrypts/decrypts the passed string using 
  ' a simple ASCII value-swapping algorithm
  Dim strTempChar As String, i As Integer
  For i = 1 To Len(Text)
    If Asc(Mid$(Text, i, 1)) < 128 Then
      strTempChar = _
CType(Asc(Mid$(Text, i, 1)) + 128, String)
    ElseIf Asc(Mid$(Text, i, 1)) > 128 Then
      strTempChar = _
CType(Asc(Mid$(Text, i, 1)) - 128, String)
    End If
    Mid$(Text, i, 1) = _
        Chr(CType(strTempChar, Integer))
  Next i
  Return Text
End Function

It’s not recommended for highly confidential information (as anyone with this script could also decrypt your data), but it’s nonetheless highly useful. Here’s how you might use this function:

Dim MyText As String
' Encrypt
MyText = "Karl Moore"
MyText = Crypt(MyText)
MessageBox.Show(MyText)
' Decrypt
MyText = Crypt(MyText)
MessageBox.Show(MyText)

About the Author

Karl Moore (MCSD, MVP) is an experience author living in Yorkshire, England. He is the author of numerous technology books, including the new Ultimate VB .NET and ASP.NET Code Book (ISBN 1-59059-106-2), plus regularly features at industry conferences and on BBC radio. Moore also runs his own creative consultancy, White Cliff Computing Ltd. Visit his official Web site at www.karlmoore.com.

# # #

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Latest Posts

Related Stories