Posts Tagged ‘Web’
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.
How to create a FileStreamResult from a string
I’ll return to my encryption posts shortly but in the meantime I just wanted to share a useful technique that allows you to return a string in FileStreamResult object from a Controller. The first step is to create a MemoryStream object and then use this to instantiate a FileStreamResult object.
So, to create a MemoryStream object from a string:
public static MemoryStream StringToMemoryStream(Encoding encoding, string source)
{
var content = encoding.GetBytes(source);
return new MemoryStream(content);
}
and to use this to instantiate a FileStreamResult object:
var mimeType = "text/plain";
var source = "String as MemoryStream";
var stream = StringToMemoryStream(Encoding.UTF8, source);
var fileStreamResult = new FileStreamResult(stream, mimeType);
Implementing RSA asymmetric public-private key encryption in C#: generating public / private key pair
I was originally planning a single post about implementing RSA-based encryption in C# but it quickly got unmanageable so I decided to split it into three separate posts on generating keys, encrypting and decrypting text. And so here is the first post: generating a public / private key pair in C#.
The .Net Framework makes this task remarkably easy for us: we need only instantiate the RSACryptoServiceProvider class passing the key length to use and then return the value of the ToXmlString method of the object. ToXmlString accepts a single parameter, includePrivateParameters, which is a Boolean value indicating whether to return a public / private key pair (includePrivateParameters = true) or just the public key (includePrivateParameters = false).
The key length passed to the constructor of the RSACryptoServiceProvider class is the number of bits to use and so must be a multiple of 8. As discussed in my last post, 1024 bit key length is now the minimum realistic key length to use, with 2048 or 4096 being preferable and much more secure.
Introduction to RSA asymmetric encryption
Protecting data has never been more important and yet in my experience a surprising number of people think that data protection starts and ends with SSL. But HTTPS only protects data in transit, not at either end of the pipeline. This becomes increasingly important once we are persisting sensitive data such as user passwords. Such data needs to be encrypted so that even if intercepted it cannot be used by an attacker, or the attacker can at least be put to an awful lot of trouble to decrypt the data.
AJAX post from window unload event not reaching controller
I hit an interesting problem today: an AJAX post sent using jQuery’s $.ajax method was failing to reach the controller action method but only intermittently. The kind of problem guaranteed to drive me nuts until I’ve figured it out …
What was happening was that I was building a queue that I then wanted to post to a controller once the queue reached a certain size or once the user navigated away from the current page. The page navigation feature was implemented using jQuery’s window unload event:
$(window).unload …
The postQueue function was always being hit whether it was called from the queue manager or the unload event but it was only managing to correctly post to the controller if called from the queue manager … a half day’s work was fast turning into one and a half days …
Turns out that the issue was that you cannot post asynchronously from a function called from the unload event because there is no longer a callback function in scope even if you are not actually using a callback handler …
The solution is to make sure that you only post synchronously from within the unload event by setting the async property of the ajax object to false.
Escaping the @ character in ASP.Net MVC Razor Views
The Razor view engine uses the ‘@’ character to identify code directives within the view. So, what do you do if you need to use an @ character within a Razor code statement block? You simply escape it with @@: @@ is the escape character for @ in Razor views.
Razor, like most things MVC, is actually pretty smart however and tries to work out from context when an ‘@’ is just an ‘@’ and where it marks C# (or VB.Net) code.
One of the main uses for this is to identify email addresses within a Razor view – it should not be necessary to escape the @ character in an email address.
Brief Introduction to Aspect Oriented Programming
One problem I have frequently encountered when developing enterprise systems is that of applying functionality that is required by many objects within a system but which is not core to the concerns of those objects, such as logging or transactional behaviour.
Aspect Oriented Programming, or AOP, refers to this type of functional requirements as cross-cutting concerns and is designed specifically to address this issue: if such requirements are met by coding the cross-cutting concern into objects throughout the system, we can easily end up with a messy, hard-to-maintain implementation split across many objects.
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?
Capturing the output of a View as a String
There are times when it is very useful to be able to capture the output of a View as a string, perhaps to log it or, in a case I recently encountered, in order to convert that HTML to PDF using an HTML-to-PDF conversion tool. So, for whatever reason, you need to capture the string output.
Once again, MVC makes this relatively straightforward even when using the Web Forms engine.
The basic task we have to accomplish is to swap the existing HttpContext object (which contains the HtmlTextWriter that is outputting to the response stream) for one which contains an HtmlTextWriter we control and which is outputting to a StringBuilder object instead, call the View’s ExecuteResult method and then swap it all back again afterwards …
Although straightforward in concept, this is slightly involved in practice, probably more so than it needs to be.
The best way to explain is doubtless with some well-commented sample code, so here goes …
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.