Method 1: Using Convert.ToBase64String()
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.
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==
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.
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==
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.
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-
Comments (0)