How to base 64 encode a string in C# and why would you do that.

Posted by

Recently I had to call a service with basic authentication. In order to make a request with a basic authentication, you need to add Authorization header in the HTTP headers collection containing base 64 hash of the user name and password. User name and Password should be written in a single line with a colon (:) as a separator. for example, if the username is “scott” and password is “tiger” then we need to write scott:tiger for encoding.

For quick testing your encoding and decoding you can check the following site.

https://www.base64encode.org/
https://www.base64decode.org/

so for scott as a user, we need to set the following header in the HTTP request headers.

Authorization: Basic c2NvdHQ6dGlnZXI=

You can easily reverse the hash to the original user name and password. Really? Yes. Then why would you need to do this, why not just pass the plain username:password string into the Authorization header. The answer is, It is not done for securing the username and password, and more as a means of escaping special characters, the intent of the encoding is to encode non-HTTP-compatible characters that may be in the user name or password into those that are HTTP-compatible.

Here is the sample code for doing it in C#.