Programming in C#, Java, and god knows what not

Setting Android Environment

Illustration

Prerequisited

Before we start anything, we need two downloads:

Java SE Development Kit

This one is prerequisite for everything else. Just download it, run it and go wild on “Next”. Installation is as easy as it can be.

Installing Eclipse

Installing Eclipse is as easy as unpacking it. For purpose of this walk-through I will unpack it to root directory of drive D: (eclipse.exe will be located in directory D:\eclipse).

Installing Android SDK

Unpack archive to (D:\eclipse) and run “SDK setup.exe” (from “D:\eclipse\android-sdk-windows\SDK setup.exe”). Location is not set in stone but I like it in subdirectory of eclipse. If you desire some other location, just go for it.

As soon as you start it, it will attempt to download newest repository data. If you are behind proxy, this step will fail. In that case just go to “Settings” and fill proxy server and port fields. Often it is also necessary to check “Force https://… sources to be fetched using http://” for everything to download properly.

Once update is completed, you should get list of packages to install. I just leave it at default, check “Accept All”, and click on “Install”. Brace for lengthy download (around 800 MB for Android 2.2).

ADT Plugin for Eclipse

Once you start Eclipse go to “Help”, “Install new software”. Click “Add” once window opens. Now write “ADT Plugin for Eclipse” under site name (exact naming is not important) and “https://dl-ssl.google.com/android/eclipse/” under location. If your Internet access goes over proxy, you will need to use http location “http://dl.google.com/android/eclipse/”.

When packets are found (“Android DDMS” and “Android Development Tools”) I just select them both and click on “Next”/“I accept …”/“Finish” combo few times and download will start. After restart you need to go to “Window”, “Preferences”. There, under “Android” node, you need to select folder with unpacked Android SDK (in my case “D:\eclipse\android-sdk-windows”). All other things I left as default.

After one more restart (I am not really sure it is necessary) you will be able to create new project under “File”,“New”,“Project”:“Android\Android Project”.

Anything more

As you attempt to start project, you will get prompt to create emulator. If you would like audience as broad as possible, Android 1.6 is reasonable choice. If you want to target only newer devices, 2.1 is one that you should do your testing on. Those are only rule-of-thumb advices - do not take them too seriously.

If you intend to use command-line tools it would be good to add Android SDK tools to path (for me it is under “D:\eclipse\android-sdk-windows\tools”).

It is definitely not as easy as installing Windows Phone Developer Tools but it is not too bad.

Visual Basic 6.0 - Controls

I am preparing to clean my web site and I decided to remove all references to programming source samples. General idea is moving those samples to blog. Here I will start with my old VB 6 controls.

Download is here.

CmnDlg

Substitute for CommonDialog control.

Contain Containter for other controls.

Progress

Replacement for ProgressBar Common Control. Doesn’t use .ocx.

TextComplete

AutoComplete TextBox.

TrayIcon

Enables program icons in tray notification area.

P.S. Rest of old stuff can be found in this post.

Java Rfc2898DeriveBytes

I was creating Java port for one program of mine and I stumbled across little issue. Although C# and Java seem quite different, you can almost always rely on one-for-one feature compatibility. Of course I stumbled across one class that was not implemented in Java. That class was Rfc2898DeriveBytes (.NET PBKDF2 implementation).

To be totally correct, I did found quite a few classes that do implement RFC 2898 but they did not give same result as one I used in .NET. While those implementations were also correct ones, they did not ensure compatibility with my existing code.

.NET Reflector comes here as great debugging tool. Quick peek just discovered that core of .NET Rfc2898DeriveBytes class is HMAC SHA-1 algorithm. GetBytes method has some basic buffer management (data gets generated 20 bytes at time) and call to omnipotent Func method. It is in this method that real crypto-magic happens.

Fortunately, building blocks for this functionality is available to Java. Although syntax is somewhat different, general idea is same. Whole getBytes method needed only changes related to array copying. In .NET we would use Buffer.BlockCopy and in Java this translates perfectly to System.arraycopy. Really hard…

Crypto-core is hidden in function named “func”. Notable spot here is incrementing block counter. In C# this is unsigned int but in Java there is no such thing. That is reason for one extra check.

if (this._block == 2147483647) {
    this._block = -2147483648;
} else {
    this._block += 1;
}

With these few changes done our Java implementation of Rfc2898DeriveBytes was done. Source code can be downloaded here.

Requirements for Password Hashing

Illustration

Proper password hashing should satisfy few requirements.

First requirement is proper salting. I already wrote about this so check that post for explanation. I will just say here that properly implemented salting strengthens password against whole range of brute-force attacks. Storing password without salting is just not acceptable.

Second requirement would be using proven algorithm. Very often people (myself included) fall into trap of using easiest way there is. In case of password hashing this is usually just SHA-1 hash function. While this is definitely better than plain-text passwords, it is not ideal. Password hashing is just not that simple. Minimum would be support for RFC 2898 password derivation (both PBKDF1 and PBKDF2 will do). For this purpose .NET offers Rfc2898DeriveBytes class.

RFC 2898 also defines way to make your password hashing slow (via iteration count). Although every programmer wants code to run fast, exact opposite is required for password hashing. Idea behind it is to slow-down dictionary attacks. It is huge difference between trying out 10 and 1000000 passwords per second. Of course, you also need to think about users so some compromise is needed. There is no exact figure but I find anything sub-500 milliseconds acceptable to users.

Last requirement that I would add is using user name as part of hashing process. This is to protect us from “copy/paste” attacks if user names and hashes cannot be secured (e.g. in database table). If user name is not encoded, one could copy known password1 hash from user1 to user2 (overwriting password2 in progress). After that it will be possible to login as user2 with password1. That allows user1 to potentially create mess and blame everything on user2. If he restores old password2 afterward, you have security breach that is not easily traceable.

If you are not in mood for implementing this, you can download example of my implementation.

I opted for 9-byte salt and 20-byte key. That results in 30 bytes of output (first byte is iteration count). With base-64 encoding resulting string is exactly 40 bytes long.

8192 iterations should cause function to be around 500 milliseconds on most computers (@ 3GHz). This was selected as user’s psychological limit on waiting. Since number of iterations is stored in first byte of hash (12 for 4192 iterations, 13 for 8192, 14 for 16384 and so on) you can also speed-up (or slow-down) code by factors of two and retain compatibility among different versions.

User name string is converted to upper case before hashing (or checking). This causes user name to be case-insensitive even when encoded.

Passwords With a Grain of Salt

Illustration

90% of time that I see hashed password in database, it is result of MD-5, SHA-1 or similar hash algorithm. While this does satisfy bare minimum requirements for password storage it is not enough.

Problem lies in “rainbow table” attacks. While checking password against all possible combinations seems difficult, it becomes easier once you get one big file with all those combinations pre-computed. Cracking password becomes just searching for already existing hash. Yes, amount of data is quite big (hundreds of gigabytes) but any personal computer can handle this easily.

All you need is to download pre-existing rainbow table and check all entries against your hash. I checked this against some passwords I had access to and success rate was near to 100%. It was very scary experience. Fortunately, there is easy solution - just introduce salt.

Salt consists of few random bytes appended to password (8 bytes seems like nice number). Our hashing function then becomes:

hash = SHA1(password + salt)

This simple step invalidates all precomputed rainbow tables. Even better, since salt differs between users, each user must be attacked separately. Time for cracking just got increased significantly.

Cost on implementation side is just having another field for storing salt. Cost of few additional bytes per user seems reasonable.

Storing Passwords

More often than not I see big errors in how passwords are stored in database. Because of that I decided to make little series about passwords and how to handle them. In this first installment I will go over two biggest errors you can make as far as password storage is concerned.

Definitely worst thing to do is to store plain-text password in database. This is just unacceptable. If any user gains access to your database all your users are compromised. Since most users tend to use same password for multiple purposes and web sites, compromising password for some internal application could also mean compromising password for Amazon or PayPal account.

Almost as bad is storing passwords using reversible encryption (DES, AES or similar two-way algorithms). While data looks properly encrypted it is still possible to get original password. If your program can get to password, so can somebody else. Always assume worst.

For storing passwords you MUST use irreversible encryption. For properly hashed passwords bad guys must resort to dictionary and brute-force attacks. Losing hashed passwords is also not desirable but at least you buy some time.

Full Width Toolbar

As I ventured into WPF world, some things annoyed me more than others. One of those things was inability of toolbar to have no grip and to be full width.

After some time I found solution for grip problem. Just put toolbar in toolbar tray and set IsLocked attribute to true.

<ToolBarTray IsLocked="True">
    <ToolBar>
        ...
    </ToolBar>
</ToolBarTray>

Extending it’s width proved to be little bit more engaging. It took me a while to notice ActualWidth property of ToolbarTray control. As name says, it will return you actual width of ToolbarTray.

Since we want toolbar to span whole window, it should be inside DockPanel (and docked to top). Synchronizing ActualWidth of ToolbarTray and our Toolbar is then solved by simple data binding:

<DockPanel?
    <ToolBarTray IsLocked="True" DockPanel.Dock="Top">
        <ToolBar MinWidth="{Binding RelativeSource={RelativeSource AncestorType={x:Type ToolBarTray}}, Path=ActualWidth}">
            ...
        </ToolBar>
    </ToolBarTray>

    <Grid>
    </Grid>
</DockPanel>

Sample with everything done (and few things more) is here.

Got a Key?

Illustration

Starcraft II has it’s release date confirmed. It will be available for general public on 27th July. Of course that probably means that I (a resident of Croatia) will not get it until some time later.

Detecting 64-Bit in .NET 4.0

In previous versions of .NET we could check whether process is 64-bit or not. It is not obvious solution - we check length of pointers.

With .NET 4.0 there are two new properties in Environment class. Is64BitProcess returns true if we are currently running in 32-bit mode. It is equivalent to our old-style check of IntPtr.Size == 4.

Is64BitOperatingSystem is something completely new. It will return true if operating system is capable of running 64-bit programs. This opens possibility of detecting 64-bit environment even if we run in 32-bits ourself. It will not be used often but it is good thing to have when e.g. running other processes.

Windows Phone Developer Tools

Illustration

Some time ago Microsoft gave us CTP version (you might call it alpha) of Windows Phone development environment. Unfortunately, that version of Visual Studio 2010 Express for Windows Phone was not compatible with Visual Studio 2010 RTM.

Last days of April finally brought refreshed CTP with that particular problem solved.

Happy development.