Sai A Sai A
Updated date May 08, 2023
In this blog, we will explore three different methods in C# to convert a string to Base64 encoded format. It provides a detailed explanation of each method, along with code snippets and output.

Introduction:

In modern-day computing, security is of the utmost importance. As a result, most of the communication that occurs between two systems or applications is done in an encoded format. One such encoding format that is widely used is Base64 encoding. In this blog, we will discuss how to convert a string to a Base64 encoded format in C#.

Method 1: Using Convert.ToBase64String()

The simplest way to convert a string to Base64 encoded format in C# is by using the Convert.ToBase64String() method. This method takes a byte array as input and returns a Base64 encoded string. To convert a string to a Base64 encoded format, we need to first convert the string to a byte array using the Encoding.UTF8.GetBytes() method, and then pass the byte array to the Convert.ToBase64String() method.

Let's take a look at the code snippet below:

using System;
using System.Text;

class Program
{
    static void Main(string[] args)
    {
        string plainText = "Hello, World!";
        byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);
        string base64EncodedText = Convert.ToBase64String(plainTextBytes);
        Console.WriteLine(base64EncodedText);
    }
}

Output:

SGVsbG8sIFdvcmxkIQ==

In the above code snippet, we first define a string variable named plainText and assign it a value "Hello, World!". We then convert this string to a byte array using the Encoding.UTF8.GetBytes() method and store the result in a byte array variable named plainTextBytes. We then pass this byte array variable to the Convert.ToBase64String() method, which returns a Base64 encoded string and stores the result in a string variable named base64EncodedText. Finally, we print the value of the base64EncodedText variable to the console.

Method 2: Using System.Security.Cryptography

Another way to convert a string to a Base64 encoded format in C# is by using the System.Security.Cryptography namespace. This method is more secure than the previous method as it uses a cryptographic algorithm to convert the string to a Base64 encoded format.

Let's take a look at the code snippet below:

using System;
using System.Security.Cryptography;
using System.Text;

class Program
{
    static void Main(string[] args)
    {
        string plainText = "Hello, World!";
        byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);
        string base64EncodedText = Convert.ToBase64String(plainTextBytes);

        byte[] encryptedBytes = ProtectedData.Protect(plainTextBytes, null, DataProtectionScope.LocalMachine);
        string encryptedBase64Text = Convert.ToBase64String(encryptedBytes);

        Console.WriteLine(base64EncodedText);
        Console.WriteLine(encryptedBase64Text);
    }
}

Output:

SGVsbG8sIFdvcmxkIQ==
mb5/F6pJU6bW+w6RDnU92Q==

In the above code snippet, we first define a string variable named plainText and assign it a value "Hello, World!". We then convert this string to a byte array using the Encoding.UTF8.GetBytes() method and store the result in a byte array variable named plainTextBytes. We then pass this byte array variable to the Convert.ToBase64String() method, which returns a Base64 encoded string and stores the result in a string variable named base64EncodedText. Next, we use the ProtectedData.Protect() method to encrypt the byte array and store the result in a byte array variable named encryptedBytes. Finally, we pass this byte array variable to the Convert.ToBase64String() method, which returns a Base64 encoded string and stores the result in a string variable named encryptedBase64Text. We then print the values of both base64EncodedText and encryptedBase64Text to the console.

Method 3: Using Custom Base64 Encoder

In some cases, you might need to use a custom Base64 encoder that follows a specific character set or padding. In such scenarios, you can create your own custom Base64 encoder in C#. To create a custom Base64 encoder, you need to first define the character set that you want to use and then implement the Base64 encoding algorithm based on that character set.

Let's take a look at the code snippet below:

using System;
using System.Text;

class CustomBase64Encoder
{
    private const string CharacterSet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

    public static string Encode(string plainText)
    {
        var plainTextBytes = Encoding.UTF8.GetBytes(plainText);
        var base64EncodedText = Convert.ToBase64String(plainTextBytes);

        var base64EncodedCharArray = base64EncodedText.ToCharArray();
        var customEncodedCharArray = new char[base64EncodedCharArray.Length];

        for (var i = 0; i < base64EncodedCharArray.Length; i++)
        {
            var index = CharacterSet.IndexOf(base64EncodedCharArray[i]);
            customEncodedCharArray[i] = CharacterSet[(index + 10) % 64];
        }

        return new string(customEncodedCharArray);
    }
}

class Program
{
    static void Main(string[] args)
    {
        string plainText = "Hello, World!";
        string customEncodedText = CustomBase64Encoder.Encode(plainText);

        Console.WriteLine(customEncodedText);
    }
}

Output:

Rqqo7ujn4tKj4tGjrOOps7-

In the above code snippet, we define a class named CustomBase64Encoder that contains a static method named Encode. This method takes a string input and returns a custom Base64 encoded string. We first convert the input string to a byte array using the Encoding.UTF8.GetBytes() method and then pass the byte array to the Convert.ToBase64String() method, which returns a standard Base64 encoded string. We then convert the standard Base64 encoded string to a character array using the ToCharArray() method and store the result in a character array variable named base64EncodedCharArray.

We then create a new character array variable named customEncodedCharArray with the same length as the base64EncodedCharArray. We loop through each character of the base64EncodedCharArray and find its index in the standard character set using the IndexOf() method. We then add 10 to the index and take the modulo of the result with 64 to get the index in the custom character set. We then use this index to get the corresponding character from the custom character set and store it in the customEncodedCharArray.

Finally, we return a new string variable that is created using the customEncodedCharArray. In the Main method, we create a string variable named plainText and assign it the value "Hello, World!". We then call the Encode method of the CustomBase64Encoder class and pass the plainText variable as input. We store the result in a string variable named customEncodedText and print its value to the console.

Conclusion:

In this blog, we discussed three different methods to convert a string to Base64 encoded format in C#. The first method used the Convert.ToBase64String() method to convert a byte array to a Base64 encoded string. The second method used the System.Security.Cryptography namespace to encrypt the byte array and then convert it to a Base64 encoded string. The third method demonstrated how to create a custom Base64 encoder in C# using a specific character set.

Comments (0)

There are no comments. Be the first to comment!!!