Posts tagged with c - page 8

Calculating Elf-32 in C# and .NET

GitHub has the latest version of Elf32

Because you can never have enough hashing algorithms at your disposal this one is compatible with the elf_hash function that forms part of the Executable and Linkable Format.

using System;
using System.Security.Cryptography;

public class Elf32 : HashAlgorithm {
  private UInt32 hash;

  public Elf32() {
    Initialize();
  }

  public override void Initialize() {
    hash = 0;
  }

  protected override void HashCore(byte[] buffer, int start, int length) {
    hash = CalculateHash(hash, buffer, start, length);
  }

  protected override byte[] HashFinal() {
    byte[] hashBuffer = UInt32ToBigEndianBytes(hash);
    this.HashValue = hashBuffer;
    return hashBuffer;
  }

  public override int HashSize { get { return 32; } }

  public static UInt32 Compute(UInt32 polynomial, UInt32 seed, byte[] buffer) {
    return CalculateHash(seed, buffer, 0, buffer.Length);
  }

  private static UInt32 CalculateHash(UInt32 seed, byte[] buffer, int start, int size) {
    UInt32 hash = seed;

    for (int i = start; i < size; i++)
       unchecked {
          hash = (hash << 4) + buffer[i];
          UInt32 work = (hash & 0xf0000000);
          if (work != 0)
             hash ^= (work >> 24);
          hash &= ~work;
       }
    return hash;
  }

  private byte[] UInt32ToBigEndianBytes(UInt32 x) {
    return new byte[] {
       (byte)((x >> 24) & 0xff),
       (byte)((x >> 16) & 0xff),
       (byte)((x >> 8) & 0xff),
       (byte)(x & 0xff)
    };
  }
}

[)amien

Calculating CRC-64 in C# and .NET

Seeing how the CRC-32 C# class I posted some time ago continues to get lots of Google hits I thought I’d post a CRC-64 version which will no doubt be far less popular being the more limited use. Again, do not use this as a secure message signature, it’s really for backward compatibility with legacy systems.

This is the ISO-3309 version of CRC-64 algorithm. It is not compatible with the ECMA-182 algorithm.

GitHub has the latest version of Crc64

To use this or the CRC-32 class to compute the hash for a file simply:

Crc64 crc64 = new Crc64();
String hash = String.Empty;

using (FileStream fs = File.Open("c:\\myfile.txt", FileMode.Open))
  foreach (byte b in crc64.ComputeHash(fs)) hash += b.ToString("x2").ToLower();

Console.WriteLine("CRC-64 is {0}", hash);

Whilst writing this I considered if I should implement some more advanced hashing algorithms missing from .NET like RIPEMD320 only to stumble across The Legion of Bouncy Castles C# Cryptography APIs which also includes generating PKCS #12 files and a whole bunch of encryption algorithms (but nothing as weak as CRC-64 ;-)

[)amien

Dissecting a C# Application – Inside SharpDevelop

Cover of Dissecting a C# ApplicationThis great book shows you the process, thinking and code behind the open-source .NET IDE SharpDevelop that went on to branch into MonoDevelop.

It was not in print for very long but Apress bought Wrox when they closed down and made the book freely available on its site for download in PDF format.

Alas, with their most recent web redesign their free e-books section has disappeared so I am temporarily hosting it here after recommending it to somebody interested in writing their own syntax highlighting editor on the MSDN forums.

Download Dissecting a C# Application – Inside SharpDevelop (Adobe PDF) (3.8MB)

[)amien

Object Initializers in .NET 3.5

One compiler improvement in .NET 3.5 is the object initializers feature that lets you concisely set properties of an object as you create it.

If you’ve ever used VB.NET you may well have found and enjoyed the with keyword to write code such as:

Dim myObj As MyClass
myObj = New MyClass()
With myObj
  .ProductCode = "ABC123"
  .Quantity = 5
  .Cost = 567.89
End With

This is more concise than writing myObj several times over, especially if setting a large number of properties, but as C# has no such keyword many people resorted to providing helpful constructors to facilitate code like:

MyClass myObj = new MyClass("ABC123", 5, 567.89);

If all three of these properties are essential then this makes for a sensible constructor however many classes have a number of properties that are optional and class designers struggle to determine whether to make constructors that merely cut-down on typing and which of the various combinations of optional properties might make sense in having their own constructor.

Invariably the combination you might want doesn’t exist and if it does the chances of being able to understand which properties are being set from one of a number of constructors that take parameters of similar types is quite low unless you go and take a peek with the IntelliSense.

Using object initializers you can stick to creating constructors that reflect parameters necessary to ensure your object is in a valid state and forget about providing helpful ones for those optional parameters. In our example if we assume the ProductCode is essential and the others are optional we can write code like:

MyClass myObj = new MyClass("ABC123") { Quantity = 5, Cost = 567.89 };

Which is both concise and easy to understand. It also requires no work on the part of the class designer and therefore works with all your existing classes. You can also nest them to set properties that require more complex types such as:

MyClass myObj = new MyClass("ABC123") {
   Quantity = 5,
   Cost = 567.89,
   Category = new Category("A") { Description = "New machine" }
};

This feature is no use if your objects are immutable in which case constructors are your only friend.

[)amien