Last week I wrapped up the chapter on the crypto package in Go, The Standard Library

Within the crypto package we have the crypto/subtle package. This package contains functions for doing constant time operations which are an important part of cryptography.

Constant time functions help prevent timing attacks which are caused when operations take different amounts of time to complete a task based on some input. When the time something takes leaks information about what's going on.

Comparing Strings

Let's look at a standard string comparison algorithm. For every character in a string, compare it to the character at the same index in the other string. If they are equal, try the next character. If not, return false. Pretty straight forward, but if the first character doesn't match, the function returns immediately. If the first character matches but the second doesn't, the function takes just a little bit longer. This difference is enough to measure, even on web applications. See these two papers for more on that. The functions in the crypto/subtle package use some bit twiddling to perform operations in a constant time.

Let's look at how this would work in Go:

You can run this example with go run timing_attack.go -compare broken (output) and go run timing_attack.go -compare constant (output). In the broken form, we use the algorithm I described above. For each index, there is one letter that takes a noticeably longer amount of time. You can see the attack progress and eventually guess the password. Well, except for the last character, but when you get it down to one character it's pretty easy to figure out what it should be (especially in a case like the example). The timing differences in the constant time run are too small to worry about.

The call to comp(password, guess) could be anything. You could be hitting a web application's login action with your guess and then they'd be doing the comparison to password . I'm just calling the function to prove the point.

The More You Know

Cryptography is a tricky subject. Using constant time functions won't make everything crypto related you do magically work, but it's an important part nonetheless. For a better look at all things cryptography, I'd recommend Applied Cryptography by Bruce Schneier.

This example is from Go, The Standard Library. If you like it and want to support the book, head over to http://thestandardlibrary.com/ and get your copy. The book is in progress and I push updates as I go. Thanks for reading!