Base64 String Encoding and Decoding in C#
How to convert plain text string to base64 encoded string and vice versa in C#
Base64 is a radix-64 ASCII string format that represents binary data. Each digit of base64 encoded string represents exactly 6 bits of data.
It is designed to carry binary data across platforms that only support text content.
The usage is mostly popular in Web platform. For example it’s being used to embed image files inside HTML or embed font file inside CSS.
Even though the main purpose is to store binary data into a text content, base64 sometimes is being used to hide a text. For example to prevent the content of your website scraped by robot.
When I say to hide a text, that doesn’t mean it’s cryptographically secure. So you shouldn’t use it to store sensitive data like password or PIN.
String to Base64 Encoding C# Method
C# has built-in Base64 encoding method. But it only accepts binary data represented in array of bytes. To encode a plain text into a base64-encoded string, we need to convert it to array of bytes first. Then we can generate base64 encoded string from it.
Base64 to String Decoding C# Method
C# also has built-in Base64 decoding method. But it only produces array of bytes. To get the original plain text from a base64-encoded string, we need to convert the array of bytes to string.
To use the base64 string encoding method, simply pass a plain text as parameter.
For base64 string decoding, simply pass a valid base64 string as parameter.
Please note that if it isn’t a valid base64 string, it will throw an exception.
So, better to wrap it in
That’s all I can write today. Thank you for reading!