Archive for the ‘Base64 Encoding’ Category
Implementing RSA asymmetric public-private key encryption in C#: encrypting under the public key
Following on from my last post on how to generate a public / private key pair in C#, this is the next post in my series on using RSA asymmetric encryption in .Net.
Now we have a public / private key pair, we can encrypt an arbitrary string using RSA encryption. To make this code more general, we are going to allow users to specify the bit length of the public key, allowing us to easily encrypt under 1024, 2048 and 4096 bit keys. To this end, I am reusing the RsaKeyLengths enumeration from the last post containing three common bit lengths: 1024, 2048 and 4096.
Performing RSA Encryption is not particularly difficult, but neither is it straightforward.
Displaying a Base64-encoded string as an image in a view
Following on from my previous posts covering the server-side code to display a base64-encoded string as an image in MVC, I thought it would be useful to show how to write a View to actually display the re-hydrated image. What hoops will we have to jump through, what arcane secrets must be learnt?
Decoding a Base64-encoded string into a JPG
In a previous post, I discussed using MVC’s FileResult action return type to return an Image re-hydrated from a Base64-encoded string. So how exactly do you go from a Base64-encoded string to a FileResult object?
There are several, fairly straight forward steps:
- Convert the base64-encoded string to a byte array
- Use the byte array to instantiate a new object of type FileContentResult, which inherits from FileResult.
FileContentResult expects two parameters in its constructor: a byte array representing the contents of the file, and a string representing the file format.
Encoding an image as a Base64 string in C#
Following on from yesterday’s post, exactly how do you encode a .Net Image object as a Base64 string?
Again, it’s reasonably straightforward: Instantiate a memory stream, save the image to the memory stream, convert the memory stream to a byte array and finally, convert the byte array to a base64 string.
Simples, once again.
Base64-encoded strings and the Image tag
I have recently come across a situation where I wanted to have an image tag in a View but want to use a Base64-encoded string containing the image data rather than a URI to an image file. Chrome and Firefox both support using a Base64-encoded string in the src attribute of the image tag but Internet Explorer, naturally enough, does not and while I would dearly love to drop Internet Explorer support from my web sites, I cannot.
ASP.Net MVC to the rescue!
It turns out the answer is simple enough: create a Controller Action method with a return type of FileResult and build and return a FileContentResult object at run-time from a Base64-encoded string, which can come from anywhere, including being auto-generated.
Simples.