GEOTRANS in .NET and Java

GEOTRANS

GeoTrans (Geographic Translator) is a software that allows you to convert geographic coordinates among a variety of coordinate systems, map projections, and datums. It is made available by U.S. National Geospatial Intelligence Agency at no cost and free of copyright restrictions.

It is written in C (recent versions are in C++) and I've seen it used in software inside various surveying instruments. I worked on a supporting software for these devices and needed to do conversions of measured coordinates etc. So naturally, I wanted to use the tried and tested GeoTrans in my software as well. Only I needed to use it in .NET and Java…

Continue reading

.NET and Java: Generating Interoperable AES Key and IV

Let's assume we want to generate encryption key and initialization vector (IV) for AES encryption based on some passphrase. And we want to be able to generate the same key and IV for the same passphrase in .NET and Java - maybe we have Android app written in Java that needs to decrypt message from ASP.NET web app.

In .NET, Rfc2898DeriveBytes class is often used to derive keys of specified length according to given passphrase, salt, and iteration count (RFC2898 / PBKDF2). For 256-bit key and 128-bit key it is as simple as this:

var keyGen = new Rfc2898DeriveBytes(passwordBytes, 
    saltBytes, iterationCount);

byte[] key = keyGen.GetBytes(256 / 8);
byte[] iv = keyGen.GetBytes(128 / 8);

Fortunately, PBKDF2 implementation is also built-in in Java:

SecretKeyFactory factory = 
    SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
KeySpec spec = new PBEKeySpec(passwordChars, 
    saltBytes, iterationCount, 256);
SecretKey secretKey = factory.generateSecret(spec);
byte[] key = secretKey.getEncoded();

We have the same key byte array, albeit with some more typing. And how about the initialization vector now? One could think that creating new PBEKeySpec with a length of 128 is the way to go. I know I did.

However, you would just get the same bytes as for the key (the first half of them). This key derivation algorithm is deterministic so for the same inputs you get the same output. Each call of GetBytes of .NET's Rfc2898DeriveBytes just returns more and more bytes generated by the algorithm whereas Java implementation needs to know the total output length upfront. So for 256-bit key and 128-bit IV we need to create PBEKeySpec with the length of 384 and split the result between key and IV:

KeySpec spec = new PBEKeySpec(passwordChars, 
    saltBytes, iterationCount, 256 + 128);
SecretKey secretKey = factory.generateSecret(spec);

byte[] data = secretKey.getEncoded();
byte[] keyBytes = new byte[256 / 8];
byte[] ivBytes = new byte[128 / 8];

System.arraycopy(data, 0, keyBytes, 0, 256 / 8);
System.arraycopy(data, 256 / 8, ivBytes, 0, 128 / 8);		

Note: All the Java stuff was tested only with Android.

.NET and WPF Notes #1

I have been working in .NET and WPF lately. Of course, I ran into some issues and had to look up some solutions. I wrote some of it down, for "future reference" and for anyone who might be interested.

Design Time Data and Properties

When designing WPF data template for ListBox items I wanted some preview in design time with sample mock data for the items. Also, some simple way to override certain property values would be nice (e.g. when you bound brushes of path to some run time values but want to use fixed ones for design). To use the mock data you can use d:DataContext design time attribute. Some class with the sample data is created in code behind and then bound using this attribute.

public class MockMeasurementList
{
  private MeasurementList measurements = new MeasurementList();
  public MeasurementList Measurements { get { return measurements; } }

  public MockMeasurementList()
  {
    measurements.Add(new Measurement(
      new Position(49.3051356, 16.5607972, 358),
      new Vector(52.035075, 7.854967, 1492.690400));
  }
}
<UserControl.Resources>
    <mocks:MockMeasurementList x:Key="DesignList"/>
</UserControl.Resources>
<ListBox Name="ListMeasurements"
   d:DataContext="{Binding Source={StaticResource DesignList}}"
   ItemsSource="{Binding Measurements}">

WPF design time value for simple properties like brushes and sizes can be done for example using this approach of Marcin Najder. I use it for example for stroke and fill brushes of map markers:

<UserControl ... xmlns:dtools="clr-namespace:DesignTools">
  ...
  <Path Stroke="{Binding Stroke}" Fill="{Binding Fill}"
        dtools:d.Stroke="Navy" dtools:d.Fill="PowderBlue">
  ...

Events and Delegates Returning Bool

Suppose we have an event like this:

public event Func<bool> StoreMeasurementQuery;

and we want to do some action (e.g. store a measurement) only if all handlers subscribed to the event return true (Is the measurement valid? Is there enough storage?). Now if we raise the event the usual way (assuming StoreMeasurementQuery != null):

bool store = StoreMeasurementQuery();

the result won't be as one could expect as store will hold the return value of only the last handler executed. To get some sensible results we have to execute the handlers individually and check out their return values. Based on this SO answer I wrote two these extensions:

public static bool AllSubscribersReturnTrue(this Func<bool> evt)
{
  return evt.GetInvocationList().Cast<Func<bool>>().
    Select(func => func()).ToList().All(ret => ret);
}

public static bool AnySubscriberReturnsTrue(this Func<bool> evt)
{
  return evt.GetInvocationList().Cast<Func<bool>>().
    Select(func => func()).ToList().Any(ret => ret);
}

to get logical AND and OR of all event handlers return values.

Grid Mouse Interaction

By default, Grid and other Panel controls don't receive mouse events. If you want to use Grid for example as clickable container for list box items, you need to set some background to it. Background="Transparent" is good enough.