A ROT-13 implementation in CSharp

ROT-13 is a simple substitution cipher where the current character is rotated by 13 characters, which finds its symmetrical opposite in the modern English alphabet. This property allows the cipher to be reciprocal and therefore it can be used to obfuscate a clear text string and also transform the obfuscated string back into its original clear text equivalent.

I use the term obfuscation in the previous paragraph to emphasize the fact that the ROT-13 cipher is not secure and any obfuscated strings can be easily reversed simply by knowing that a ROT-13 cipher has been used.

The Implementation

The implementation of the cipher is really simple and there are many approaches that one can use to achieve the same outcome. The one I chose is based on a lookup table that I initially build and then use many times. This is basically the same approach used in the Python module this (enter import this on a python prompt). You can see the implementation by finding the this.py file that comes with your python implementation.

The lookup table that I use is implemented using a generic dictionary. When the Rot13 function is called, I check if the lookup table exists and if it doesn't, I'll build it. I use the seeds 65 and 97, which are the ASCII values for A and a respectively, and from there I move 26 values to the right while applying a modulo 26, which tells me if I need to wrap-around to the beginning.

Once the lookup table is built, I can use it by simply going over the string parameter passed into Rot13, and substituting each character in the string by the corresponding value in the lookup table. This is what it looks like:

private Dictionary<char, char> d = null;

public string Rot13(string s) {
    if (d == null || d.Count == 0) {         // build the lookup table
        d = new Dictionary<char, char>();    //  if needed
        int[] sr = { 65, 97 };               // A=65; a=97; ASCII Codes
        foreach (int c in sr) {
            for (int i = 0; i < 26; i++) {   // 26 alpha chars
                d.Add((char)(i + c), (char)((i + 13) % 26 + c));

    StringBuilder sb = new StringBuilder();
    foreach (var item in s.ToCharArray()) {
        if (d.ContainsKey(item))             // Worry only about alpha characters
            sb.Append(d[item]);              //  leave number, etc. untouched

    return sb.ToString();

Using the Algorithm

To use the ROT-13 cipher algorithm above, you simply have to call the Rot13 function and send it a string parameter which represents the string you want to obfuscate. In the example code below the Main function uses a command line argument passed in:

static void Main(string[] args) {
    if (args.Length == 0) {
        WL("Please provide a string to obfuscate using the ROT 13 cypher.");

    Program p = new Program();

    WL(String.Format("Original String: {0}", args[0]));
    WL(String.Format("Obfuscated String: {0}", p.Rot13(args[0])));
    WL(String.Format("De-Obfuscated String: {0}", p.Rot13(p.Rot13(args[0]))));

    WL("\nPress enter to continue...");

static Func<string> RL = () => Console.ReadLine();
static Action<Object> WL = obj => Console.WriteLine(obj);</pre>

If you call the Rot13.exe program like this:

H:\>Rot13.exe HELLO

Your output will be the following:

Original String: HELLO
Obfuscated String: URYYB
De-Obfuscated String: HELLO
Press enter to continue...


I am teaching myself cryptography and security concepts and I am using this venue to write my notes and solidify my ideas on this topic. I will be filing these under the crypto and security tags.

Mounting a USB Stick in Linux

Here is a quick way to mount a USB thumb drive in Linux. Most distros will recognize the USB stick when you plug it in, but it case they don't then this command comes in handy:

sudo mount -t vfat /dev/sdf1 /mnt/cruzer/

Now you can access and browse the contents of the usb stick by change the current directory to /mnt/cruzer/. Your mileage may vary and your Linux distro may have a different file system hierarchy.

Errors with the prepopulate_from SlugField parameter in Django 1.2.1

I recently upgraded to Django version 1.2.1 and I immediatelly noticed that some of my models were broken with the following error:

C:\test&gt;python manage.py syncdb

Traceback (most recent call last):
  File "manage.py", line 11, in <module>
  File "C:\Python26\lib\site-packages\django-1.2.1-py2.6.egg\django\core\management\__init__.py", line 438, in execute_manager
  File "C:\Python26\lib\site-packages\django-1.2.1-py2.6.egg\django\core\management\__init__.py", line 379, in execute
  File "C:\Python26\lib\site-packages\django-1.2.1-py2.6.egg\django\core\management\base.py", line 191, in run_from_argv
    self.execute(*args, **options.__dict__)
  File "C:\Python26\lib\site-packages\django-1.2.1-py2.6.egg\django\core\management\base.py", line 217, in execute
  File "C:\Python26\lib\site-packages\django-1.2.1-py2.6.egg\django\core\management\base.py", line 245, in validate
    num_errors = get_validation_errors(s, app)
  File "C:\Python26\lib\site-packages\django-1.2.1-py2.6.egg\django\core\management\validation.py", line 28, in get_validation_errors
    for (app_name, error) in get_app_errors().items():
  File "C:\Python26\lib\site-packages\django-1.2.1-py2.6.egg\django\db\models\loading.py", line 146, in get_app_errors
  File "C:\Python26\lib\site-packages\django-1.2.1-py2.6.egg\django\db\models\loading.py", line 61, in _populate
    self.load_app(app_name, True)
  File "C:\Python26\lib\site-packages\django-1.2.1-py2.6.egg\django\db\models\loading.py", line 78, in load_app
    models = import_module('.models', app_name)
  File "C:\Python26\lib\site-packages\django-1.2.1-py2.6.egg\django\utils\importlib.py", line 35, in import_module
  File "..\tso\blog\models.py", line 50, in <module>
    class Category(models.Model):
  File "..\tso\blog\models.py", line 53, in Category
    slug = models.SlugField(unique=True, prepopulate_from=('title',), help_text='Used in the category URL. Must be unique')
  File "C:\Python26\lib\site-packages\django-1.2.1-py2.6.egg\django\db\models\fields\__init__.py", line 988, in __init__
    super(SlugField, self).__init__(*args, **kwargs)
  File "C:\Python26\lib\site-packages\django-1.2.1-py2.6.egg\django\db\models\fields\__init__.py", line 542, in __init__
    super(CharField, self).__init__(*args, **kwargs)
TypeError: __init__() got an unexpected keyword argument 'prepopulate_from'

So I did a little bit of research on this problem and I found the following explanation for what is going on:

Changed prepopulate_from to be defined in the Admin class, not database field classes

As of [4446], the prepopulate_from option to database fields no longer exists. It's been discontinued in favor of the new prepopulated_fields option on class Admin. The new prepopulated_fields option, if given, should be a dictionary mapping field names to lists/tuples of field names. This change was made in an effort to remove admin-specific options from the model itself. Here's an example comparing old syntax and new syntax:

# OLD:

class MyModel(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)
    slug = models.CharField(max_length=60, prepopulate_from=('first_name', 'last_name'))

    class Admin:

# NEW:

class MyModel(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)
    slug = models.CharField(max_length=60)

from django.contrib import admin

class MyModelAdmin(admin.ModelAdmin):
    prepopulated_fields = {'slug': ('first_name', 'last_name')}

admin.site.register(MyModel, MyModelAdmin)

The above is taken from the Django wiki page that talks about the newforms-admin branch

This is why the command line will never die

A while back I wrote about the address line of the browser being the new command line. It turns out I was wrong. The command line itself is the newcommand line.

I ran into this Google Code project today via my tweeter feed. GoogleCL allows the nerd in me to interact directly with several Google services from a shell prompt. It includes interfaces to Blogger, Picasa, Calendar, Contacts, Docs, and YouTube. You can find several scripting examples under the project's Wiki.

The fact that this is a python script and it's open source is really interesting to me. I am thinking that I need to integrate all of this into an Emacs mode.

CSharp: Testing a Generic Class

I just posted this question to StackOverflow and I am repeating it here for posterity as the pastebin code expires after a month:

More than a question, per se, this is an attempt to compare noteswith other people. I wrote a generic History class that emulatesthe functionality of a browser's history. I am trying to wrap myhead around how far to go when writing unit tests for it. I amusing NUnit. Please share your testing approaches below.

The full code for the History class is at pastebin.com: http://pastebin.com/ZGKK2V84. A full version of the code is also available below:

using System;
using System.Collections.Generic;

namespace Gorauskas.DataStructures {
    /// A history data structure that provides the same functionality
    /// as a browser history, but allows you to use any type
    /// The type parameter
    public class History<T> {

        private Stack<T> _forward = new Stack<T>();
        private Stack<T> _backward = new Stack<T>();

        private T _current;

        public History() { }

        /// This contructor set the Current pointer to an initial object of type T
        /// An item of type T
        public History(T item) {
            this._current = item;

        /// Returns the current item that it is pointing to
        /// Pushes the state of the current pointer into the backward stack
        /// and sets the new current item. If the forward stack has items in it
        /// then clear that too.
        public T Current {
            get {
                return this._current;

            set {

                if (!(this._current == null))

                this._current = value;

        /// Tells if the current pointer can be moved forward in history.
        public bool CanMoveForward {
            get { return this._forward.Count > 0; }

        /// Tells if the current pointer can be moved backward in history.
        public bool CanMoveBackward {
            get { return this._backward.Count > 0; }

        /// Moves the current pointer one item back in history
        /// The current item
        public T Back() {
            if (this.CanMoveBackward) {
                this._current = this._backward.Pop();

            return this._current;

        /// Moves the current pointer one item forward in history
        /// The current item
        public T Forward() {
            if (this.CanMoveForward) {
                this._current = this._forward.Pop();

            return this._current;

        /// Adds the entire history in chronological order to a list of T
        /// A ordered list of history items
        public List<T> Dump() {
            List<T> l = new List<T>();

            if (this.CanMoveForward)

            if (!(this.Current == null))

            if (this.CanMoveBackward)

            return l;

Automating Emacs Build and Install from Source

A little while back I wrote up my notes on how to build and install Emacs from souce on Ubuntu.

I have now automated the task in the form of the crude script provided below. The script takes one parameter: gui. This parameter tells the build whether you intend to do a GUI or command line only build of Emacs. It also writes out some messages to a file called emacs-build.log ... Enjoy!

echo "Building @`date`" | tee -a ~/emacs-build.log
mkdir ~/emacs-src
cd ~/emacs-src

echo "Installing pre-requisites" | tee -a ~/emacs-build.log
apt-get -q -y install build-essential gcc git-core texinfo libncurses5-dev

if [ "$1" = gui ]; then
    echo "Installing GUI pre-requisites" | tee -a ~/emacs-build.log
    apt-get -q -y install libgtk2.0-dev libtiff4-dev libgif-dev libjpeg62-dev libpng12-dev libxpm-dev

echo "Cloning Emacs Git Repo" | tee -a ~/emacs-build.log
git clone git://git.savannah.gnu.org/emacs.git

cd ./emacs

echo "Configuring build" | tee -a ~/emacs-build.log
if [ "$1" = gui ]; then
    ./configure --without-x

echo "Building source code" | tee -a ~/emacs-build.log
echo "Installing emacs" | tee -a ~/emacs-build.log
make install
echo "Clean up" | tee -a ~/emacs-build.log
cd ~/
rm -rf ~/emacs-src
echo "All Done!" | tee -a ~/emacs-build.log

Generate .NET Assemblies from Iron Python

The other day I was talking to a fellow programmer and the question of compiling Iron Python code into .NET assemblies came up. So what if you have an Iron Python script that you want to run and then have the ipy interpreter output an assembly that you can run on other machines. How do you do that?

There are several ways to approach the problem. One way is to use an IDE, but IDE support for Iron Python is still a bit lacking. One IDE that provides Iron Python great support is SharpDevelop create a Iron Python project, write your code as you normally would and then build your project. The compile assemblies can then be found in the build output folders for that project.

The other way to do this is through a tool that ships with IronPython called Pyc or the Python Command-Line Compiler. If you installed the latest version 2.6 of IronPython, then pyc.py will be available at C:\Program Files (x86)\IronPython 2.6\Tools\Scripts or wherever you installed IronPython on your system. If you have earlier versions of IronPython then pyc.py will be available as a separate download in the samples package.

With pyc.py you can create console or Windows assemblies from your python scripts. Basic usage looks like this:

ipy pyc.py /out:myprogram.exe /main:mainfile.py /target:exe program.py support.py

The above will generate an assembly called myprogram.exe (/out) which is a console application (/target) and will execute the code in mainfile.py first (/main) and will also include code from program.py and support.py in the assembly.

Postel's Robustness Principle

Interesting comment from the trenches:

After much testing, it's clear that Postel's advice to protocol designers ("be liberal in what you accept, and conservative in what you send") invites a natural-law repercussion for JS as "protocol":

"If you are liberal in what you accept, others will utterly fail to be conservative in what they send."

Found here: http://mxr.mozilla.org/mozilla-central/source/js/src/jsscan.cpp#1464 while looking at SpiderMonkey source code.

VMWare Server Doesn't Start After Upgrade

I have a Xubuntu 9.04 machine that is hosting some VMs running on VMWare Server. I recently upgraded a bunch of packages on the host machine and then I noticed that the VMWare Server was not starting automatically anymore. I tried running it manually and I got the error message: vmware is installed, but it has not been (correctly) configured for this system.

What happened is that one of the upgraded packages was the Linux Kernel and a new Kernel version will break VMWare because it originally compiled for the previous Kernel version that was on the machine. To fix this I had to run the /usr/bin/vmware-config.pl script to reconfigure and recompile several components. After running the script, VMWare server started up again as normal.

Let me know if you had this problem before.

Building and Installing Emacs from Source on Ubuntu

Every so often I have to setup a web development server and one of the first things I have to have on that server is Emacs. As an Emacs fanatic, I need to have the very latest bleeding-edge version. In order to ensure that, I clone the official git repository into my home directory and then I compile and build from there. Most of the time I will be performing the steps below on a Ubuntu Server distribution (these steps work on versions 8.10, 9.04, and 9.10) without X installed.

  1. I will assume you already have your Ubuntu server up and running.
  2. Install some packages needed for the build by running the following command:

    sudo apt-get install build-essential gcc git-core texinfo libncurses5-dev`
  3. Clone the latest Emacs from the GNU git repository by running this:

    git clone git://git.savannah.gnu.org/emacs.git`
  4. Configure, compile and install Emacs by running the following commands:

    cd ./emacs<br>    sudo ./configure --without-x
    sudo make
    sudo make install

Some notes: The need for the build-essentials, gcc, and git-core are pretty obvious; the texinfo package is needed for the make info dependency; and the libncurses5-dev is needed for the termcap.h dependency.

The above will also work on a desktop distro, but you will be limitedto a terminal version of Emacs. In order to install a graphical versionof Emacs you will also need to install the following extra packages:

sudo apt-get install libgtk2.0-dev libtiff4-dev libgif-dev libjpeg62-dev libpng12-dev libxpm-dev

The above line will also install a bunch of other dependencies neededby the libraries. Don't forget to also remove the --without-xparameter and run just this line:

sudo ./configure

Let me know how it works for you.