First big gig

At last, I got the chance to play 4 hours at my favourit club. You`re all invited, just leave me a Message so you can get on the guestlist.

No Fear!

Gordon Freeman at LHC

Gordon Freeman spotted at the LHC.

How to Get Into Any Club

Just buy yourself a colorful hoodie,a record bag and the club is all yours. Now this is why we all are deejaying. :D
Via Bruce Schneier

Generating X.509 Certificates with C#

.NET provides the Namespace System.Security.Cryptography.X509 to handle certificates but unfortunately there is no built-in way to generate them. If you google on this topic a bit you will get the advice to use Process.Start( …) in combination with Makecert.exe which is a commandline tool shipped with .NET. This is a little bit of a hack in my opinion and the options are somewhat limited.

Doing further investigation I stumbled upon Bouncy Castle, a cryptographic-API for Java which also happens to have a .NET port. It seems to have far more posibilities then the native .NET cryptographic API: You can use exotic things like GOST,IDEA and Tiger for example. The API design is somewhat messy in my opinion. You have to use parameter strings alot (no enums) and there are a  bunch of namespaces that only contain one Class but that is really just beacause it`s a port from Java and the guys have sligtly diffrent framework design convetions over there.
Okay enough talk, you wanted to create certificates after all:

The Java guys seem to love namespaces.

using System;
using System.IO;
using System.Collections;
 
using Org.BouncyCastle.Asn1.X509;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Generators;
using Org.BouncyCastle.Math;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.X509;

This is the setup code which contais almost all the classes that we need for our task.

X509V3CertificateGenerator certgen = new X509V3CertificateGenerator();
 
//Create`s a cryptographic secure PRNG
SecureRandom srand = new SecureRandom();
 
//Generates Keypairs for Assymetric eliptic curve ciphers
ECKeyPairGenerator keygen = new ECKeyPairGenerator();
keygen.Init(new KeyGenerationParameters(srand,256));
AsymmetricCipherKeyPair keypair = keygen.GenerateKeyPair();

Certificate creation

X509Name issuer = new X509Name("ST=Germany,CN=FooBar Certification Division,O=FooBar Corporation,OU=Certification Division");
X509Name subject = new X509Name("ST=United States of America,CN=Bob Smith, O=BS Logistics Ltd., OU=Customers");
 
certgen.SetIssuerDN(issuer);
certgen.SetSubjectDN(subject);
 
//We use Eliptic Curve DSA with SHA512
certgen.SetSignatureAlgorithm("SHA512withECDSA");
 
//Valid from...
certgen.SetNotBefore(DateTime.Now);
//..to
certgen.SetNotAfter(DateTime.Now.AddYears(10)); //Valid for 10 Years
 
//Serial Number
BigInteger bi = new BigInteger( new byte[1]{1});
certgen.SetSerialNumber(bi);
 
//Set Public key
certgen.SetPublicKey(keypair.Public);
 
/*** Key usage (optional extension)  ***/
 
KeyUsage usage = new KeyUsage(KeyUsage.DigitalSignature | KeyUsage.KeyAgreement);
 
//Add extension
certgen.AddExtension(X509Extensions.KeyUsage, false, usage);
 
/***  Extended key usages (optional extension) ***/
ArrayList purpouses = new ArrayList();
purpouses.Add(KeyPurposeID.IdKPSmartCardLogon);
purpouses.Add(KeyPurposeID.IdKPIpsecUser);
 
ExtendedKeyUsage extended_usage = new ExtendedKeyUsage(purpouses);
 
//Add extension
certgen.AddExtension(X509Extensions.ExtendedKeyUsage, false, extended_usage);

Write certificate to disk

/*** GENERATION ***/
 
//Generate certificate
X509Certificate cert= certgen.Generate(keypair.Private,srand);
 
//Encode to ASN.1 and write to disk
byte[] asn = cert.GetEncoded();
File.WriteAllBytes("testcert.cer", asn);

.NET/Java Interop with IKVM.NET

Recently I decided to take a closer look at IKVM.NET, a project which implements a JVM on top of .NET Common Language Runtime. I was really suprised how well it works. In this Post we will write a simple Java Library and call its Methods from C# afterwards.

First things first: We need to make something up that we can call from C#. So here is a simple Calculator Class in Java:

//Compile as TestLib.jar
 
public class Calculator {
 
    private int a;
    private int b;
    private int result;
 
    public Calculator(int valueA,int valueB){
        a=valueA;
        b=valueB;
 
    }
 
    public void add(){
 
        result=a+b;
    }
 
    public void div(){
 
        result= a/b;
    }
 
    public int getResult(){
 
        return result;
    }
}

As already mentioned IKVM implements a JVM on .NET. This means that you need to convert the resulting *.jar (TestLib.jar in this example) to a .NET Assembly by executing:

ikvmc TestLib.Jar

This will output a TestLib.dll.

Now create a new C# Console Project and copy the IKVM.OpenJDK.ClassLibrary.dll and IKVM.Runtime.dll which is included in the /IKVM.NET/bin directory to the /bin/Debug/ Folder of your C# Program (or add it to the GAC). This DLLs contain a .NET implementation of the Java Class Library. Now reference to the TestLib.dll and voila!, this should work:

static void Main(string[] args)
        {
            //All members are implicitly virtual (Java behavior)
            Calculator calc = new Calculator(10, 2);
            calc.add();
            Console.WriteLine(calc.getResult());
 
        }

The cool thing about the IKVM.OpenJDK.ClassLibrary.dll is that you can use a lot of the Java stuff if you like. Just browse it with the Object Browser…

I`d also like to mention that Swing an AWT is currently not supported. But who needs that GUI stuff anyway… ;)

Minimalistic Brainfuck Interpreter in C#

Brainfuck is a esoteric programming Language designed by Urban Müller. It works on a byte array (tape) of 30000 cells. The initial state is that all cells are zero. Your program moves a pointer (head) over the tape and modifies the content of the underlying cell.

  • <   Move head to previouse cell
  • >   Move head to next cell
  • +   Increase the value of the current cell by one (++)
  • -   Decrease the value of the current cell by one (++)
  • [    Jump past the matching ] if the cell under the pointer is 0
  • ]    Jump back to the matching [
  • .    Write value of the current cell to stdout
  • ,    Read value from stdin and save it to the current cell

This would be a “Hello World” in Brainfuck:

++++++++++[&gt+++++++&gt++++++++++&gt+++&gt+&lt&lt&lt&lt-]&gt++.&gt+.+++++++..+++.&gt++.&lt&lt+++++++++++++++.&gt.+++.------.--------.&gt+.&gt.

And here is the Interpreter:

/*
*  bint - Brainfuck Interpreter
*  Implements wrap-around for cells (if 255 is increased it becomes 0 and vice-versa)
*
*/
 
using System;
using System.IO;
 
namespace bint
{
    class Program
    {
         const short TAPE_SIZE=30000;
 
         static string program_code;                    //The Programcode is saved here
         static byte[] tape = new byte[TAPE_SIZE];      //Represents the Memory
         static short ptr = 0;                          //Memorypointer
         static short loop_ptr = 0;                     //looppointer
 
        static void Main(string[] args)
        {
 
            //***Programfile is passed by arg***
 
            //Check if any arguments where passed at all
            if (args.Length == 0)
            {
                PrintHelp();
                return;
            }
            else
            {
                //Check if passed file exists
                if (!File.Exists(args[0]))
                {
                    PrintHelp();
                    Console.WriteLine();
                    PrintError("IO_ERROR: Passed programfile not found!");
                    return;
                }
                else
                {   //Read passed programfile
                    program_code = File.ReadAllText(args[0]);
 
                    //Execute Program
                    //ip = instruction pointer
                    for (int ip = 0; ip &lt; program_code.Length; ip++)
                    {
                        switch (program_code[ip])
                        {
                            case '+':  //Increase value at pointer
                                {
                                    //Implement "Wrap-Around"
                                    if (tape[ptr] == byte.MaxValue)
                                    {
                                        tape[ptr] = byte.MinValue;
                                    }
                                    else
                                    {
                                        tape[ptr]++;
                                    }
                                    break;
                                }
                            case '-': //Decrease value at pointer
                                {
                                    //Implement "Wrap-Around"
                                    if (tape[ptr] == byte.MinValue)
                                    {
                                        tape[ptr] = byte.MaxValue;
                                    }
                                    else
                                    {
                                        tape[ptr]--;
                                    }
 
                                    break;
                                }
                            case '&gt;': //Increase pointer
                                {
                                    if (ptr == TAPE_SIZE)
                                    {
                                        PrintError("RUNTIME_ERROR: End of Tape.");
                                        return;
                                    }
                                    ptr++;
                                    break;
                                }
                            case '&lt;': //Decrease pointer
                                {
                                    if (ptr == 0)
                                    {
                                        PrintError("RUNTIME_ERROR: Pointer was decreased at Position 0.");
                                        return;
                                    }
 
                                    ptr--;
                                    break;
                                }
                            case '[': //jump forward to the command after the corresponding ] if the byte at the pointer is zero.
                                {
                                    if (tape[ptr] == 0)
                                    {
                                        ip++;
                                        while (loop_ptr &gt; 0 || program_code[ip] != ']')
                                        {
                                            if (program_code[ip] == '[')
                                            {
                                                loop_ptr++;
                                            }
                                            if (program_code[ip] == ']')
                                            {
                                                loop_ptr--;
                                            }
                                            ip++;
                                        }
                                    }
                                    break;
                                }
                            case ']':
                                {
                                    ip--;
                                    while (loop_ptr &gt; 0 || program_code[ip] != '[')
                                    {
                                        if (program_code[ip] == ']')
                                        {
                                            loop_ptr++;
                                        }
                                        if (program_code[ip] == '[')
                                        {
                                            loop_ptr--;
                                        }
                                        ip--;
                                    }
                                    ip--;
 
                                    break;
 
                                }
                            case '.': //Print value at pointer
                                {
                                  Console.Write(Convert.ToChar(tape[ptr]));
                                  Console.Out.Flush();
                                  break;
                                }
                            case ',': //Read value from Console and store it at pointer
                                {
                                    tape[ptr]=Convert.ToByte(Console.Read());
                                    break;
                                }
                            default:
                                {
                                    //Discard all other characters
                                    break;
                                }
                        }
                    }
                }
            }
 
        }
 
        static void PrintError(string errorMessage)
        {
            Console.ForegroundColor = ConsoleColor.Red;
            Console.WriteLine(errorMessage);
            Console.ForegroundColor = ConsoleColor.Gray;
 
        }
 
        static void PrintHelp()
        {
            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine("Brainfuck Interpreter");
            Console.WriteLine();
            Console.WriteLine("USAGE: bint [Programfile]");
        }
    }
}

Logic Gates with Domino

I found this one via Schokwellenreiter:

Loading Assemblies at Runtime

Sometimes you may want to load code dynamically to do a plugin interface or something like that. Here is a basic Codesnippet that acomplishes that task. Please be aware that this code is for demonstrational purposes and has almost no exception or error handling.

The following snippet scans the directory “Plugins” for *.dll files, and gets all types out of them which implement the “IPlugIn” Interface.

            //The current interogated assembly is loaded here
            Assembly tempasm;
            //All interrogated types are stored here
            Type[] asmtypes;
            //All IPlugIn interfaces are stored here
            Type[] interfaces;
            //And here the types which implement it
            List&lt;Type&gt; plugintypes = new List();
 
            //Get all files in
            foreach (string dll in DLLList)
            {
 
                    tempasm = tempasm = Assembly.LoadFile(dll);
 
                asmtypes=tempasm.GetTypes();
 
                //Get all types in file
                foreach (Type t in asmtypes)
                {
                    interfaces=t.GetInterfaces();
 
                    //Get all Itnerfaces
                    foreach (Type i in interfaces)
                    {
                        //If implements, then Add to list
                        if (i.Name == "IPlugIn")
                        {
                            plugintypes.Add(t);
 
                        }
                    }
                }
 
            }

After this code is executed all Types that implement “IPlugIn” are stored in the List<Type> plugintypes. Now lets say that you need to create an instance of the first type in that list.

//Find a constructor which takes one string.
 ConstructorInfo ctorinfo = plugintypes[0].GetConstructor(new Type[1]{typeof(string)});
//Invoke that constructor (constructor invoke, returns our instance)
 IPlugIn instance=(IPlugIn)ctorinfo.Invoke(new object[1] { "Hello World!" });

That wasn’t so hard, was it?

Finally… I`ve got em`!

The MOS Technology 6581 and 8580

I saw 2 C64 at the dump of our school, and could extract this beauties out of them, since I have no possibility to plug in the C64 directly (Monitor). For those of you who don`t know what the fuss is all about: Read here.

A Generic Deque Class

I posted a Deque<T> class a while ago at mycsharp.de and the guys over there gave some good feedback and a few hints for improvment. Now we have a full featured class which implements all the common intefraces to integrate smoothly with the other collections in the framework. So what is a deque anyway? A deque is a double sided Queue. You can add Items at the front and at the back. It`s as simple as that. :)

Usage:

EnqueueFront() //Adds a item to the front
DequeueFront() //Removes a item from the front
EnqueueBack() //Adds a item to the back
DequeueBack() //Removes a item from the back
PeekFront() //Returns the item at the front, without removing it
PeekBack() //Returns the item at the back, without removing it