Base64 Encoding in Visual Basic .NET

Our first example demonstrates base64 encoding and decoding. Visual Basic .NET provides built-in support for base64 encoding/decoding.

Imports System
Imports System.Text
Imports System.Convert

Module Base64EncodingExample
    Sub Main()
        ' Here's the string we'll encode/decode.
        Dim data As String = "abc123!?$*&()'-=@~"

        ' Visual Basic .NET supports standard base64 encoding.
        ' Here's how to encode using the standard encoder.
        Dim sEnc As String = Convert.ToBase64String(Encoding.UTF8.GetBytes(data))
        Console.WriteLine(sEnc)

        ' Decoding may throw an exception, which you can catch
        ' if you don't already know the input to be well-formed.
        Try
            Dim sDec As Byte() = Convert.FromBase64String(sEnc)
            Console.WriteLine(Encoding.UTF8.GetString(sDec))
        Catch ex As FormatException
            Console.WriteLine("Invalid Base64 string")
        End Try

        Console.WriteLine()

        ' Visual Basic .NET doesn't have a built-in URL-compatible base64 format.
        ' However, we can create one by replacing characters:
        Dim uEnc As String = sEnc.Replace("+", "-").Replace("/", "_").TrimEnd("="c)
        Console.WriteLine(uEnc)

        ' To decode the URL-safe string, we need to add back the padding and replace characters
        Dim padding As String = New String("="c, (4 - uEnc.Length Mod 4) Mod 4)
        Dim uDec As Byte() = Convert.FromBase64String(uEnc.Replace("-", "+").Replace("_", "/") & padding)
        Console.WriteLine(Encoding.UTF8.GetString(uDec))
    End Sub
End Module

This code demonstrates base64 encoding and decoding in Visual Basic .NET. Here’s what it does:

  1. We start by importing the necessary namespaces.

  2. We define a string that we’ll encode and decode.

  3. We use Convert.ToBase64String to encode the string to standard base64. The string is first converted to a byte array using UTF-8 encoding.

  4. For decoding, we use Convert.FromBase64String. This may throw an exception if the input is not valid base64, so we wrap it in a try-catch block.

  5. Visual Basic .NET doesn’t have a built-in URL-safe base64 encoding, but we can create one by replacing + with -, / with _, and removing the trailing = padding characters.

  6. To decode the URL-safe string, we need to reverse these changes: add back the padding and replace the characters back to their original forms before decoding.

To run this program, save it as Base64EncodingExample.vb and compile it using the Visual Basic compiler:

$ vbc Base64EncodingExample.vb
$ mono Base64EncodingExample.exe
YWJjMTIzIT8kKiYoKSctPUB+
abc123!?$*&()'-=@~

YWJjMTIzIT8kKiYoKSctPUB-
abc123!?$*&()'-=@~

The string encodes to slightly different values with the standard and URL-safe base64 encoders (trailing + vs -), but they both decode to the original string as desired.