Search code examples
stringsecurityencryptioncryptographycomparison

How always compare two strings of possibly different length in constant time?


I've read about this topic on the internet already but could only find ways where it only worked for 2 strings of the same length. In most cases, it looked pretty similar, like that:

string userinput;
string password;
int falsekey = 0;

if(userinput.length != password.length){
    return 1;
}

for(i = password.length-1; i>=0; i--){
    falsekey |= userinput[i] ^ password[i];
}
return falsekey; 

But this has only a constant-time-string-comparison if the two strings have the same length. So in case someone was looking for the length of a correct password, you could easily find it using a timing attack.

I tried to think of a way to fix that. Maybe by looking at the length of the userinput.

If that length is smaller than the password length, add random characters to the userinput string untill it has the same length of the password, then start the for loop in the code. If that length is greater than the password length, remove characters from the userinput string untill it has the same length of the password, then start the for loop in the code.

But then I think there would be a problem because in rare cases, by addint random characters, the program could accidently add those characters that give the user a correct input although it was a wrong one... : /

But how else could this work also having two different lengths?


Solution

  • In cryptographic, you need constant-time-string-comparison if you e.g. compare cryptographic keys (to prevent timing attacks), but this is not really the case with passwords, if done correctly. This is because passwords should not be stored in it original form.

    Instead a calculated hash of the password is stored, and a verification is then done by calculating the hash on the provided password and comparing to the stored password hash. This comparison against the stored password hash don't reveal any information about the original passwords length.

    Various techniques is used to prevent the passwords from being obtained, even if you have access to the stored password hashes, including one-way-hashes, hash salting, and the use of slow hashes to counter guessing the password by use of brute force.