Chris's coding blog

C# Symmetric encryption wrapper

July 24, 2009

The original class for this post can be found at codeproject.com. This class is a tidied up version (and disposes more aggressively). You may get issues with the GetLegalIV portion of the code, particularly with triple DES. This is because it pads the IV with spaces, and is not compatible with other implementations of the algorithm, such as the Perl one. The class uses UTF8.

class Program
{
static void Main(string[] args)
{
// Output:
//
// Invalid operation: Could not find file 'C:\this doesnt exist.txt'.
// Could not find file 'C:\this doesnt exist.txt'.
// Could not find file 'C:\this doesnt exist.txt'.
//
try
{
ThrowTest.ThrowNew();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
try
{
ThrowTest.Throw();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
try
{
ThrowTest.ThrowEx();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Console.ReadLine();
}
}
public class ThrowTest
{
public static void ThrowNew()
{
try
{
File.OpenText(@"C:\this doesnt exist.txt");
}
catch (IOException ex)
{
// InnerException is null, and the stacktrace starts at ThrowNew()
throw new InvalidOperationException("Invalid operation: " + ex.Message);
}
}
public static void Throw()
{
try
{
File.OpenText(@"C:\this doesnt exist.txt");
}
catch (IOException ex)
{
// This maintains the entire stacktrace, so will include the chain that occured inside the Framework,
// i.e. at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
throw;
}
}
public static void ThrowEx()
{
try
{
File.OpenText(@"C:\this doesnt exist.txt");
}
catch (IOException ex)
{
// InnerException is null, and the stacktrace starts at ThrowEx(). It's the least useful of the three.
throw ex;
}
}
}
view raw gistfile1.cs hosted with ❤ by GitHub

csharpencryption

I'm Chris Small, a software engineer working in London. This is my tech blog. Find out more about me via GithubStackoverflowResume