Library

 

Essentially a collection of some basic utilities I’ve been using. Most of these were built as I ever-so-slowly make my way towards a final and (as of yet) unnamed goal. This library has been used on several projects from the JiraSvn integration to the SslTunnel service.

Here is rundown of some key capabilities provided:

  • AppConfig – An implementation of UserSettings as a ConfigurationManager extension.
  • Bases – Base classes for IDisposable, IComparable, and IEquatable.
  • Cloning – A generic deep clone implementation for C# objects that may or may not be serializable.
  • Collections – Some collections classes what else?
  • Commands – Provides a CommandInterpreter for processing of command-line args.
  • Crypto – Some utilities around encrypting/decrypting data for the local user or machine.
  • Delegates – Provides a delegate wrapper to ensure thread-safety in WinForms.
  • Formatting – Various encoding formats for binary data.
  • Html – A regular expression xml/html parser and DOM object model.
  • Interfaces – A small collection of commonly needed interfaces.
  • IO – A collection of Stream utilities and derivations.
  • IpcChannel – An event-based message broadcast class for inter-process communication.
  • Processes – Provides a ProcessRunner utility class to capture output from a process.
  • Reflection – Reflection utilities for reading/writings fields & properties.
  • Serialization – Provides string-based storage serialization of name/value pairs.
  • Synchronization – A collection of Reader/Writer lock implementations sharing common interfaces.
  • Threading – Threaded work queues for delegates and similar classes.
  • Utils – general utility methods for file and string manipulation.
Links
 

In my previous post “Why GUID primary keys are a database’s worst nightmare” I spoke about some of downsides to using GUID primary keys. In this post I’m going to focus more specifically on the .NET Framework’s implementation of System.Guid. I have a few complaints about this class, let’s cover them…

1. Guid.ToByteArray()

This, IMHO, is one of the worst possible things about a Guid. First this method returns a byte array in little-endian format. Not only is this directly opposite the stated standard GUID format, but it also means the bytes do not compare the same as the structured value. Thus when you combine System.Guid with a sequential guid generation you wind up with either a structure that doesn’t compare sequentially, or a byte array that doesn’t compare sequentially. Yes you can always swap bytes (1,4), (2,3), (5,6), and (7,8), but really? should I have to?

The second issue I have with this method is that it absolutely requires me to allocate the bytes on the heap. While this may not sound like such a big deal, if you are moving large volumes of data and serializing those Guids the only way you can (as byte[]) it will thrash the GC. I’m hopeful that in some future version of .NET we will find a Guid with a ToByteArray(GuidFormatType, byte[], offset) where GuidFormatType would allow little-endian or big-endian formats.

2. Guid.GetHashCode()

This one does puzzle me. They choose to completely ignore bytes 9, 10, 12, 13, 14, and 15 when computing a Guid’s hash code. Ok so maybe with random Guids this really doesn’t matter, but when you start trying to use Guid with sequential values this starts to impact hash performance. If, as in my example on the previous post, bytes 1-8 are date-time, then your entire hash value amounts to the entropy introduced in bytes 11 and 16. To be specific, byte 11 xors with the MSB and byte 16 xors with the LSB.

3. Guid.NewSequentialGuid()

Don’t you wish that .NET could just do this for us? We’ve know this to be a problem, and have know of a resolution to it, since 2002. They’ve even added “NEWSEQUENTIALGUID()” to Sql Server. Wouldn’t you think they could get this done for us? I guess until they fix the endianness of ToByteArray it’s really a moot point anyway.

Of course one option is to just PInvoke UuidCreateSequential.

static class Win32
{
    [DllImport("rpcrt4.dll", SetLastError=true)]
    public static extern int UuidCreateSequential(out Guid guid);
}

4. Guid.(Missing Properties)

Another annoyance is the lack of exposing the values of the Guid. Would it have really been that hard to expose the same integer, two shorts, and 8 bytes that we can pass to the constructor? One could then create an efficient binary serializer for the Guid type without a GC allocation and without worrying about byte-swapping little-endian values. In addition, the underlying randomization could then be reused without using the ToByteArray method. Maybe this isn’t a big deal for most people, but I’m still miffed that (AFAIK) there is not a single thread-safe means of creating a random value without allocating a byte[].

 

A few weeks ago I published NuGet packages for version 1.11.924.348.

 
I also managed to get protobuf-csharp-port on board. I absolutely live by protobuffers.

 
Finally I recently published a complete protobuf services rpc layer build on the RpcLibrary and protobuf-csharp-port. Of course much of the code there could be used with any raw transport like WCF, TCP, Named Pipes, etc so check it out. This library is also available on NuGet:

 
If you haven’t tried NuGet you should look at it. If you manage an open source library you really need to get published there. It has allowed me to publish projects that have dependencies without the need to check those dependencies into source control. This reduces the burden on source control, allows for smaller archives, and makes it easier to upgrade dependencies. So trash the binaries from your source control and get started with NuGet.

 

A very minor update to the library this past weekend.

  • Addition of Cyrpto.SecureTransfer to provide file transfers via shared public keys.
  • The Crypto.AESCryptoKey now has ToArray() and FromBytes() like other keys.
  • HashStream can now aggregate read/write calls to actual storage stream while computing the hash.
  • The Crypto.Hash class received a new method, Combine(…)
  • Html.XmlLightElement and related classes are now fully modifiable.
  • BPlusTree.Options now supports a ReadOnly property to ensure no writes at the file handle level.
 

Last year I ran across this 2009 post by Bruce Schneier entitled “Another New AES Attack“. It got me thinking about and dissecting the Rijndael algorithm which most of you know as AES (Advanced Encryption Standard). This research surprised me, I found that AES has only three variants. These variants are best known by their key sizes of 128, 192, or 256 bits, but they also specify the rounds, or iterations, made during the transformation. The surprise was the underlying algorithm, Rijndael, has no such limitation. Funny enough this is exactly Schneier’s recommendation from the above article:

… At this point, I suggest AES-128 at 16 rounds, AES-192 at 20 rounds, and AES-256 at 28 rounds. Or maybe even more; we don’t want to be revising the standard again and again.

Then today, two years later, another related post from the same author “New Attack on AES” with the same recommendation.

So what does this mean for me and my software?

Well that depends on how sensitive the data is, how long you intend to store it, and how accessible is the stored cipher.

For instance, SSL uses AES-128 after the initial key exchange; however, this does not mean SSL is broken (ok it is, but for other reasons). Since the SSL session key is short-lived, and the data is not stored anywhere (well, not suppose to be), there really isn’t a major concern here. The same is likely true even for your own software, transient data encrypted for short periods of time.

Well wait a minute you ask, “what about those credit cards I have encrypted in my database?” Frankly this still isn’t much of a concern. Credit cards actually aren’t that ‘sensitive’ to begin with, they get compromised all the time (Thanks Sony). Further most credit cards expire within two years, which is about how long the most gratuitously over optimistic attack could occur. So no, I would not reinvent the way you store credit cards. I would however make sure your not storing the encryption key in that database :)

So why would I concern myself with this? Well we are well within the era of SaSS/Cloud computing and often enough we need to encrypt and store data for our users. So we have to ask ourselves how sensitive this data is, how much damage can be done by accessing the data. Thinking of services like LastPass and 1Password, they store potentially sensitive data for long periods of time. Of course if I were going to attack those services, I’d likely go after the pass phrase, not the raw crypto key, but still. These services could easily benefit from extended rounds of Rijndael algorithm.

Another classic place to improve is locally encrypted storage. This was what I was playing with when I wrote the ModifiedRijndael class. It allows you to specify key sizes from 128~4k in 64bit increments, and any compatible number of Rounds. So if you want to play around with unlocking the Rijndael algorithm from the AES constraints try it out:

        ModifiedRijndael r = new ModifiedRijndael();
        r.BlockSize = 128;
        r.KeySize = 128;
        r.Rounds = 20;
        r.GenerateIV();
        r.GenerateKey();
        ICryptoTransform alg = r.CreateEncryptor();

Sum it up: The above articles and information is really only just that right now, information. I don’t see many people needing this kind of added security when encrypting data. A classic place for me to want something like this would be when uploading a file to something like DropBox. The problem is, I would likely generate the key from a password. The password is much easier to attack than the AES-128 algorithm. So until we can solve the password entropy issue there just doesn’t seem like much point in moving beyond AES for *most* cases.

 

The help site doesn’t suck as bad as did before. Make me feel better and take a look:

http://help.csharptest.net/

I’ll know if you don’t.

So I finally gave up on my last effort at getting help automated.  To recap my struggle: basically Sandcastle, the original help system I used, was a complete flop.  I spent days trying to get the thing to work and had untold nightmares working with it.  I think I only ever pushed one copy with it.  Then I thought I’d play around with Reflector.NET and build my own help generator that included the actual source code.  It actually worked pretty well although it was somewhat less aesthetically pleasing to view.  Trouble is Reflector.NET is no longer free and I’m a little upset by their choice.

Finally I needed to produce some documentation for work and needed a ‘real’ solution.  The API we were documenting at work had a rather unique need, the dll was generated from a COM import and had no source files.  So I went searching for a tool that could give me a WYSIWYG help editor for .NET assemblies.

I FOUND THE KILLER HELP APP!

Stumbling across Document! X was an absolute stroke of good fortune.  It did everything I needed for the project at work and I immediately knew I needed a copy for this project!  A little on the pricey side I requested an open-source license and they granted my request.

The results of Document! X I think speak for themselves so now go back and click on the help link before reading more.  I’ve been working with this product for almost a month now and I have to say I’m impressed by several aspects of it.  One of the grandest things is that all their templates are well laid out in a single ‘configurations’ folder.  A few personal preferences drove me to make a few tweaks here and there and it was easy and straight-forward to do.  Of course not every product is perfect and Document! X is no exception, but it is the best I’ve worked with since NDoc and FAR more capable.  My only real gripe is that the embedded source editor is not a text-area and I keep winding up with html getting pasted in there.  Still it’s a pleasure to work with, I didn’t have to learn anything new, just picked it up and started working.  Honestly this is a solid 9 out of 10 on my scale, so if you need documentation try it out.

 

Just published the latest release v1.10.1124.358 of the C# Library hosted on google code. Major new functionality in the form of the new assembly CSharpTest.Net.RpcLibrary. This library wraps PInvoke calls to the Win32 RPC APIs. This allows pure managed C# applications the ability to move byte arrays over the supported rpc protocols. The following is [...]

 

So first off this is not new, it’s been around for a long, long while. One issue I have with IDisposable is that for whatever reason .Net did not include a base class for handling the details… I admit you may not always be able to leverage it since you may have a base class, [...]

 

This one is actually something of a triviality, yet it can be very useful at times. Now a word of caution is due here, this object is built on System.Threading.Timer and should not be used to enqueue 12 million work items. Yet if you need to perform a simple task at some time in the [...]

 

Most people I’ve seen online compute a simple hash of password + salt for persistence and authentication. This is the accepted standard in a straight-forward solution: byte[] Hash(string password) { byte[] pass = System.Text.Encoding.UTF8.GetBytes(password); //Create the salt to use byte[] salt = new byte[32]; new RNGCryptoServiceProvider().GetBytes(salt); //Create the hash of password and salt HashAlgorithm hashAlgo [...]

 

So recently I’ve been working heavily with some of the cryptography stuff in .Net and adding a large amount of it to my open source library. One of the many things I needed to perform was simply encrypting and decrypting a piece of data with a password. It seems everyone out there is using Rfc2898DeriveBytes [...]