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

Post-Quantum Cryptography - Round One

See also round 2 and round 3.


After NIST’s post-quantum crypthography call for proposal, we have quite a few submissions for round 1.

With almost 70 entries and considering these are all (almost) completely new algorithms, it’s hard to say which are going to be favorites. However, based on no science but name alone, I do have a few favorites.

First one is nod to Star Trek in form of CRYSTALS-DILITHIUM. It is a lattice-based scheme with slight performance advantage over other proposals. Sadly, it uses CryptoJedi as hosting for its white paper which I believe constitutes forbidden religion mix.

Further into the Jedi territory, there is a NewHope algorithm. As it’s unfortunately case with many proposal, there is no website for it, but there is a white paper. It’s again lattice-based algorithm with a focus toward forward secrecy. Not too bad and I would say quite a favorite considering it’s already present in Chrome.

One I like is NTRU Prime. It is (again) lattice-based, but it takes special care to avoid issues other lattice systems might have - the most important being constant-time execution to make classic side-channel attacks more difficult.

Another one to check might be Falcon. It is again lattice-based but with special care given to small memory footprint and stellar performance.

If lattice-based does not work, my money is on DAGS algorithm using quasi-dyadic codes. Its small key size compared to other code-based candidates and possibility of asymmetric key exchange where you get to fine-tune load on server as compared to client make it ideal for IoT (often both energy and performance deprived) applications.

Lastly, RLCE-KEM seems interesting as its RLCE-based encryption gives high performance - even when compared to traditional algorithms. It is a bit finicky algorithm, especially when it comes to padding, but its speed might make it worth.

It is way too early to make serious predictions but I personally really like thought that went into DAGS. It seems to be something that could nicely work for both current and post-quantum scenarios. And fine tuning of server/client work ratio seems to be god-given for battery operated devices. Of course, with great flexibility comes a great responsibility and (generally-speaking) more flexible algorithms allow security downgrades a bit more of a risk.

We shall see what round 2 brings next year. :)

Asterisk Be Damned

Illustration

Honestly, I almost lost hope this day will come. However, finally there is a download of Visual Studio Express 2017. Because no sunshine can happen without clouds here in Redmond, only Desktop edition is available. Moreover, Microsoft found it necessary to clarify it further with the following asterisk:

* Visual Studio Express 2017 is available for Windows Desktop developers. This will be the final version of Visual Studio Express, and there will not be a UWP or Web offering of Visual Studio Express 2017. We encourage all users to look at the free development options offered by Microsoft such as Visual Studio Code and Visual Studio Community for future development needs.

Yep, this is the last edition for the fans of Express. It has been a good ride I guess.

PS: And no, answer is not using Community as its licencing restrictions make it wildly unsuitable for the whole host of scenarios where Express was shining. For example, use in a bigger company is not really allowed - even if you are not using it for production software but only for internal tools.

Your Evaluation Period Has Ended

Illustration

There are no better ways to spend nice weekend morning than programming - I am sure you agree. ;)

So, one Saturday morning I started Visual Studio Community edition, only to be greeted with “Your evaluation period has ended” message. Somehow my license went “stale” even though I have been using Visual Studio 2017 for months now. Easy enough, there is “Check for an updated license” link immediately below. Unfortunately, that button did nothing except informing me that license couldn’t be downloaded.

Actual solution was to log into the Microsoft account. Once credentials have been verified, dialog simply disappeared. My best guess is that inability to log into account has been the cause for this license covfefe.

Although story has a happy ending, it might not been so if I didn’t have Internet. If this happened in the air, my options would be limited to crying and/or sleeping. Or, if I am lucky, paying exorbitant price of airplane WiFi.

I guess logging off and back onto my Microsoft account should become my standard preflight procedure.

But the question in the back of my mind is: Why the heck would you even put this check in development tool you give away for free?

Express 2017 for Windows Desktop

Illustration

Moment I’ve been waiting for since Visual Studio 2017 was released is finally (almost) here.

While Community edition is more capable, restrictions on its use within anything but the smallest (or opensource) companies are quite limiting. Whereas developers can (hopefully) get at least Professional or even Enterprise edition, the same cannot be said for people who might need access to code just occasionally or who enjoy making small internal tools. For them Express used to be god-given due to its quite permissive licence.

Preview version does have license restrictions on production use, but my expectation is that final version will have the same licence as 2015.

Sysadmins, rejoice!

[2017-10-17: Final release of Visual Studio Express 2017 is out.]

Visual Studio 15.3

Illustration

Behind Visual Studio’s slight version bump from 15.2 to 15.3, we have a major update.

First of all, .NET Core is finally here accompanied with .NET Standard 2.0. Both have greatly increased API coverage and hope is that they will help with greater acceptance of the whole new (open-source) ecosystem.

In addition there is C# 7.1 which is first time Microsoft updated a language in a minor Visual Studio version. True, there are not many changes to the language itself (albeit async Main was longed for) but it signals a new direction of decoupling Visual Studio, C#, .NET Standard releases.

I hope this .NET Standard 2.0 will do what .NET 2.0 did back in 2005 and unite fragmented developers around a new common denominator.

More details at Channel 9.

Weirdest Feature in C# 7

I love the new C# 7 candy. Some of them I use, some of them I will use rarely. However, there is one I don’t get at all.

Let’s imagine having a login class and a single method with kinda unusual out parameters:

public class Login {
    public string UserName { get; set; }
    public string Password { get; set; }

    public void Deconstruct(out string userName, out string password) {
        userName = UserName;
        password = Password;
    }
}

Normally you would expect to call this method as:

var login = new Login(...);

var userName, var password;
login.Deconstruct(out userName, out password);

With new out variables, this can be written a bit shorter and, in my opinion, more readable:

var login = new Login(...);
login.Deconstruct(out var userName, out var password);

What I wouldn’t expect for the life of me, would be a Tuple-like syntax:

(var userName, var password) = login;

Why?

Because it doesn’t use keyword, it doesn’t use interface, it doesn’t use attribute. Nope, it uses the magic method name. Yep method must be named Deconstruct and have two or more output parameters and the new syntax is yours to abuse.

And this is not me not liking tuples. I would be more than happy if this worked as a normal tuple returned from a more standard method call , e.g.:

(var userName, var password) = login.Deconstruct();
    public (string userName, string password) Deconstruct() {
        return (UserName, Password);
    }

I believe this magic name method is just simply a wrong way to introduce the new features. It is not discoverable, it doesn’t really read well, and it paves path for introduction of other magical method names. Didn’t IDispose and its Dispose() vs Dispose(bool) teach us anything?

I can just hope this single deviant feature among other sensible C# 7 features is just a price we pay for the night Hejlsberg got drunk. And I surely hope he will stay clean for C# 8. :)

Lazy<T>

Quite often in singleton classes you might find yourself doing the standard plumbing code like this:

private static MyClass _current = new MyClass();

public static MyClass Current {
    get { return _current; }
}

or a bit simpler with C# 7:

public static MyClass Current = new MyClass();

If class is a bit heavier (e.g. using lots of memory) you might do it lazily with a lock:

private static MyClass _current;

public static MyClass Current {
    get {
        lock(SyncRoot) {
            if (_current == null) { _current = new MyClass(); }
            return _current;
        }
    }
}

What almost never gets any love is Lazy construct known from .NET Framework 4:

private static Lazy<MyClass> _current = new Lazy<MyClass>();

public static MyClass Current {
    get { return _current.Value; }
}

This will initialize class on the first access, it is tread safe by default, and you can even use custom initializer if needed, e.g.:

private static Lazy<MyClass> _current = new Lazy<MyClass>(() =&gt; new MyClass(42));

public static MyClass Current {
    get { return _current.Value; }
}

Exactly what doctor prescribed. :)

PS: And stop using double-check locking.

My Most Favorite C# 7 Features

Illustration

With Visual Studio 2017 out and C# 7 in the wild we got a couple of new features. After using them for a while, here are my favorites.

Out Variables The change here is subtle and many would call it inconsequential but I love. Out variables can finally be declared inline instead of pre-declaring them above parsing statement. This small change makes code flow much smoother and, in my opinion, makes all the difference. For example, note the difference between these two code fragments:

int count;
if (int.TryParse(text, out count) && (count &gt; 1)) {
    //do something with count
}
if (int.TryParse(text, out **var** count) && (count &gt; 1)) {
    //do something with count
}

For rare cases when you don’t care about result you can also use underscore (_) character:

if (int.TryParse(text, out **var _**)) {
    //do something
}

Throw Expressions If you are creating classes for public consumption, quite often a big part of your code is boilerplate argument verification and throwing of exceptions. You can now merge usage of that argument with null coalescing or ternary operators. Again, nothing huge but makes code a bit more to the point:

if (text == null) { throw new ArgumentNullException(nameof(text), "Text cannot be null."); }
this.Text = text;

if (number &gt;= 2) { thrown new ArgumentOutOfRange(nameof(number), "Number must be 2 or more."); }
this.Number = number;
this.Text = text ?? **throw new ArgumentNullException(nameof(text), "Value cannot be null.")**;
this.Number = (number &gt;= 2) ? number : **throw new ArgumentOutOfRange(nameof(number), "Number must be 2 or more.")**;

Is Expressions Another change that seems small but it really improves code is just another style of as operator and it will probably cause its demise. It is a syntax candy allowing for inline variable declaration and a bit more readable code:

var comboBox = sender as ComboBox;
if (comboBox != null) {
    //do something with comboBox
}
if (sender is **ComboBox comboBox**) {
    /do something with comboBox
}

Local Functions And lastly, there are local functions. Again, these are nothing you couldn’t do before. I don’t think they are going to be used often most of the time. However, when you parse stuff or deal with state machines, they do come in handy as they do capture local variables.

Wish list

The only thing I still desire in C# as compared to other languages are enum methods. It is not a big thing but it would remove a whole set of helper methods and similar plumbing.

Parsing Double.MinValue

If you try converting double.MinValue to string and then back again, you will be greeted with OverflowException:

var text = double.MinValue.ToString(CultureInfo.InvariantCulture);
Console.WriteLine(text);
var number = double.Parse(text, NumberStyles.Float, CultureInfo.InvariantCulture);
Console.WriteLine(number);

Seemingly output string of -1.79769313486232E+308 is a bit lower than double would go despite the implicit promise minimum value makes: to be a minimum.

Reason for this is ToString() method not showing all the digits it can by default but actually a few less with a bit of rounding. This actually generally gives a better result (for example try 1.0/3). Last digit or two are noise anyhow due to the nature of double.

However, if we are emotionally connected to every possible digit or we need to parse stuff we give as output, there is a little thing called round-trip formatting. That works for Single, Double, and BigInteger data types and it consists of a single “r”:

var text = double.MinValue.ToString("r", CultureInfo.InvariantCulture);
Console.WriteLine(text);
var number = double.Parse(text, NumberStyles.Float, CultureInfo.InvariantCulture);
Console.WriteLine(number);

Now we get -1.7976931348623157E+308 as a text representation and parsing fails no more.

PS: Equivalent “issue” exists for .MaxValue.

Duplicates in Dictionary

If one needs to fill dictionary with bunch of keys while tracking only last value for each, a generic inner loop code might looks something like this:

if (dict.ContainsKey(key)) {
    dict[key] = value;
} else {
    dict.Add(key, value);
}

Code checks if key exists, if not it is added; otherwise the old value is replaced. Pretty straightforward.

Surprisingly, this code can be simplified - a lot:

dict[key] = value;

Dictionary’s indexed property will do exactly the same thing as code above - but in less lines.