7

Base64 Encode and Decode in C#

 2 years ago
source link: https://code-maze.com/base64-encode-decode-csharp/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Base64 Encode and Decode in C#

Publisher Logo

We value your privacy

We and our store and/or access information on a device, such as cookies and process personal data, such as unique identifiers and standard information sent by a device for personalised ads and content, ad and content measurement, and audience insights, as well as to develop and improve products.With your permission we and our partners may use precise geolocation data and identification through device scanning. You may click to consent to our and our partners’ processing as described above. Alternatively you may click to refuse to consent or access more detailed information and change your preferences before consenting.Please note that some processing of your personal data may not require your consent, but you have a right to object to such processing. Your preferences will apply to this website only. You can change your preferences at any time by returning to this site or visit our privacy policy.

Base64 Encode and Decode in C#

Posted by Code Maze | Updated Date Jul 19, 2022 | 0

Code Maze Book Collection

Want to build great APIs? Or become even better at it? Check our Ultimate ASP.NET Core Web API program and learn how to create a full production-ready ASP.NET Core API using only the latest .NET technologies. Bonus materials (Security book, Docker book, and other bonus files) are included in the Premium package!

In this article, we will learn about how to Base64 encode and decode in C#.

To download the source code for this article, you can visit our GitHub repository.

Let’s dive in.

What is Base64 Encoding?

Base64 are symbols comprising of alphabets and numbers, with some special characters. What’s more, we can adopt these symbols to hold binary data in ASCII string format. Basically, each Base64 digit represents 6-bits of binary data stored as an 8-bits character in memory.

Encoding means manipulating data from one form to another. Based on this definition, we can define Base64 encoding as a group of schemes for converting binary data to ASCII format so that the data can be transferred in a text stream or saved as a document like XML.

Conversely, computer systems communicate through various channels with zeros and ones. When these systems are transmitting information, the data can get corrupted. Therefore, it is advisable to use Base64 to transmit sensitive and large data, like images, and email attachments, to mention a few.

What is Base64 Used For?

We can use Base64 to transmit a large amount of binary data within systems. Also, we can use Base64 to encode data inside files like HTML, CSS, and XML. Lastly, we can store files like XML and JSON in Base64.

Implement the Base64 Encoding in C# With ToBase64String()

The ToBase64String() method creates a Base64 encoded ASCII string from an array of 8-bit unsigned integers. This method has some overloads with a varying number of parameters.

The ToBase64String() has four parameters: 

  • inArray
  • offset
  • length
  • options

Let’s check out each one and see how it can help us.

InArray

inArray is a required parameter and it’s an array of 8-bit unsigned integers. For instance, if we want to convert “Hello world!” to Base64, we need to get the bytes first. The resulting Base64 output is:

var textBytes = Encoding.UTF8.GetBytes("Hello world!");
// after: 72 101 108 108 111 32 119 111 114 108 100 33
var base64String = Convert.ToBase64String(textBytes);
// after: SGVsbG8gd29ybGQh
var textBytes = Encoding.UTF8.GetBytes("Hello world!");
// after: 72 101 108 108 111 32 119 111 114 108 100 33 
var base64String = Convert.ToBase64String(textBytes);
// after: SGVsbG8gd29ybGQh

Offset

offset is an Int32 optional parameter. It states the position we want our encoding to start from. Using our last example of “Hello world!”, if we want to encode only “world!”, we will set our optional parameter to 6. We must pair this parameter with the length option to make it work. The 8-bit unsigned integer array for “world!” is  119 111 114 108 100 33.

Similarly, the Base64 output will be different from the result we got when all the value was encoded:

var textBytes = Encoding.UTF8.GetBytes("Hello world!");
// after: 72 101 108 108 111 32 119 111 114 108 100 33
var base64String = Convert.ToBase64String(textBytes, 6, 6);
// after: d29ybGQh
var textBytes = Encoding.UTF8.GetBytes("Hello world!"); 
// after: 72 101 108 108 111 32 119 111 114 108 100 33 
var base64String = Convert.ToBase64String(textBytes, 6, 6);
// after: d29ybGQh

Length

length is an optional Int32 parameter. This parameter works hand-in-hand with the offset parameter. We can use this parameter to state the number of elements or variables we want to encode. Using the last example, the value for this parameter was 6.

Options

We can use the options parameter to insert line breaks within our Base64 output. Line breaks can improve the readability of our Base64 text and also assist us while using tools that don’t deal well with long lines. The options parameter is optional. Conversely, the encoding scheme will add a line break for every 76 characters.

NOTE: A likely reason for line breaks on 76 characters was to provide a way to include binary files in e-mails and Usenet postings which was intended for humans using monitors with 80 characters width. Let us know if you know more about this in the comments section.

This value cannot be modified because the value was defined in RFC 2045. To see this in action, we’ll use a text with more characters:

var textBytes = Encoding.UTF8.GetBytes("The great crocodile of Queensland can attain a length of 30 feet");
var base64String = Convert.ToBase64String(textBytes, Base64FormattingOptions.InsertLineBreaks);
// after: VGhlIGdyZWF0IGNyb2NvZGlsZSBvZiBRdWVlbnNsYW5kIGNhbiBhdHRhaW4gYSBsZW5ndGggb2Yg
// MzAgZmVldA==
var textBytes = Encoding.UTF8.GetBytes("The great crocodile of Queensland can attain a length of 30 feet");
var base64String = Convert.ToBase64String(textBytes, Base64FormattingOptions.InsertLineBreaks);
// after: VGhlIGdyZWF0IGNyb2NvZGlsZSBvZiBRdWVlbnNsYW5kIGNhbiBhdHRhaW4gYSBsZW5ndGggb2Yg
//        MzAgZmVldA==

We can see that the value has been broken into two lines.

Decode the Base64 String in C# With FromBase64String()

This method is the opposite of the ToBase64String() method. It converts from Base64 to its equivalent 8-bit unsigned integer array. We are going to use the output from ToBase64String() conversion for “world!”, the base64String variable: 

// before: d29ybGQh
var base64EncodedBytes = Convert.FromBase64String(base64String);
// after: 119 111 114 108 100 33
var inputString = Encoding.UTF8.GetString(base64EncodedBytes);
// after: world!
// before: d29ybGQh
var base64EncodedBytes = Convert.FromBase64String(base64String);
// after: 119 111 114 108 100 33
var inputString = Encoding.UTF8.GetString(base64EncodedBytes);
// after: world!

Conclusion

In this article, we’ve learned how to Base64 encode and decode in C#. In addition, we’ve shown how to encode a string to Base64 and vice-versa.

Code Maze Book Collection

Want to build great APIs? Or become even better at it? Check our Ultimate ASP.NET Core Web API program and learn how to create a full production-ready ASP.NET Core API using only the latest .NET technologies. Bonus materials (Security book, Docker book, and other bonus files) are included in the Premium package!

Share:

Subscribe
guest
Label
0 Comments
booklet-200px-width-min.png

--- FREE eBook ---
Top 16 BEST PRACTICES
to improve API effectiveness 10x.
Find out how!

Leave this field empty if you're human:

© Copyright code-maze.com 2016 - 2022

wpDiscuz


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK