Base64 Extensions

Extensions

Make life easier using these extensions to deal with Base64 strings.

C# Extensions, in this case, is a way to intuitively use the Visual Studio IDE to code and decode Base 64 strings.

What is Base64?

A binary-to-text encoding technique called Base64 encoding converts binary data into an ASCII string format.

Binary data is transformed into a printable ASCII string format during the encoding phase, then back to binary data during decoding.

Computer systems frequently utilize Base64 encoding to send data over text-only channels like HTTP and email.

The Base64 Extensions Code

This code creates a generic extension <T> to all objects encoding to Base64 string.

And two decode Base64 extensions to get a string or byte array.

namespace System;

public static class EncodeExtensions
{
    public static string EncodeBase64<T>(this T? obj) =>
        Convert.ToBase64String(Encoding.ASCII.GetBytes(obj?.ToString() ?? throw new Exception("T Base64 is null.")));

    public static string DecodeBase64(this string? base64) =>
        Encoding.UTF8.GetString(Convert.FromBase64String(base64 ?? throw new Exception("String Base64 is null.")));

    public static byte[] DecodeBase642ByteArray(this string? base64) =>
        Convert.FromBase64String(base64 ?? throw new Exception("String Base64 is null."));

}

Easy of Use

This is an example of the use.

public class MyStringBase64
{
    public string Base64 { get; set; } = string.Empty;

    public string Base64Encoded { get; set; } = string.Empty;

    public string GetBase64() => Base64.EncodeBase64();

    public string DecodeBase64() => Base64.DecodeBase64();
}

The IDE automatically suggests the EncodeBase64 when typing .encode.

Publish string

Samples to use

If you are not familiar with C#, here are ten samples showing how you can apply the Base64 extensions.

// Sample 1: Encoding and decoding a string
string originalString = "Hello, World!";
string encodedString = originalString.EncodeBase64();
string decodedString = encodedString.DecodeBase64();

// Sample 2: Encoding and decoding an integer
int originalInt = 42;
string encodedInt = originalInt.EncodeBase64();
int decodedInt = encodedInt.DecodeBase64<int>();

// Sample 3: Encoding and decoding a floating-point number
double originalDouble = 3.14;
string encodedDouble = originalDouble.EncodeBase64();
double decodedDouble = encodedDouble.DecodeBase64<double>();

// Sample 4: Encoding and decoding a custom object (assuming ToString() is overridden)
MyCustomClass originalObject = new MyCustomClass();
string encodedObject = originalObject.EncodeBase64();
MyCustomClass decodedObject = encodedObject.DecodeBase64<MyCustomClass>();

// Sample 5: Encoding and decoding a byte array
byte[] originalBytes = new byte[] { 0x10, 0x20, 0x30, 0x40 };
string encodedBytes = originalBytes.EncodeBase64();
byte[] decodedBytes = encodedBytes.DecodeBase64ByteArray();

// Sample 6: Encoding and decoding a nullable integer
int? nullableInt = null;
string encodedNullableInt = nullableInt.EncodeBase64();
int? decodedNullableInt = encodedNullableInt.DecodeBase64<int?>();

// Sample 7: Encoding and decoding a DateTime object
DateTime originalDateTime = DateTime.Now;
string encodedDateTime = originalDateTime.EncodeBase64();
DateTime decodedDateTime = encodedDateTime.DecodeBase64<DateTime>();

// Sample 8: Encoding and decoding a long integer
long originalLong = 1234567890123456789;
string encodedLong = originalLong.EncodeBase64();
long decodedLong = encodedLong.DecodeBase64<long>();

// Sample 9: Encoding and decoding a GUID
Guid originalGuid = Guid.NewGuid();
string encodedGuid = originalGuid.EncodeBase64();
Guid decodedGuid = encodedGuid.DecodeBase64<Guid>();

// Sample 10: Encoding and decoding a boolean
bool originalBool = true;
string encodedBool = originalBool.EncodeBase64();
bool decodedBool = encodedBool.DecodeBase64<bool>();

The IDE automatically suggests the DecodeBase64 when typing .decode.

Decode Base64

 

Understand deeply

The process of representing binary data, usually in files or data, in a human-readable and ASCII-compatible format is known as base64 encoding. When binary files, such as documents or images, must be sent as text within an email message, Base64 encoding is frequently used in email attachments. Email systems that may not be able to handle binary data well can include the binary data in the text body of the email without any problems, thanks to Base64 encoding, which transforms the binary data into a string of ASCII characters. Another instance is the storage of binary data in text-based formats like XML or JSON, which might not be able to handle binary data directly. 

What are the limitations of using Base64 encoding for data transmission or storage?

Although base64 encoding is a helpful method for textual representation of binary data, it has several drawbacks in terms of data transport and storage:

Size increase: The data size is increased by roughly 33% when encoding it in Base64. This implies that the encoded data will be greater than the original binary data. This growth in size might be wasteful and result in increased bandwidth or storage needs if you are transferring or storing huge amounts of data.

Inefficiency: Base64 encoding is not the most effective method when storing or transmitting binary data. Its primary purpose is to make it compatible with systems that use text. Other encoding techniques, such as binary encoding or compression algorithms, can be better appropriate if performance is a top priority.

Security: Base64 encoding is not a safe method for safeguarding private information. The encoded data can be decoded back into its original binary form using this straightforward encoding technique. Base64 encoding is not a secure method to encrypt or safeguard data; instead, you should employ encryption techniques.

Encoding and decoding overhead: Binary data may incur additional CPU processing and memory usage while encoding into Base64 and decoding back to binary. In applications where performance is essential, this could be problematic.

Not all data types can use Base64 encoding: Not all binary data types can use Base64 encoding. For instance, employing Base64 can change the structure of binary data with a particular encoding that depends on binary values, making the data useless without the proper decoding.

Conclusion

Base64 encoding has drawbacks even though it's a valuable tool for textual representation of binary data. Because of these drawbacks, developers should consider whether Base64 encoding is the best option for their particular use case, mainly if efficiency, security, or speed are issues.

The extensions demonstrated in the article can be helpful; use them wisely.

If you like this post, please join me on LinkedIn. I'll see you there!


Similar Articles