Safe way to Password Equals Check in Java

Author: Shazin Sadakath

There will be times when you would need to compare some sensitive data in Java like passwords. May be you would need to implement your own password protection system in which you would need to compare two passwords and check whether they are equal.

So the most obvious way is to do the following;

 private static boolean checkPasswords(String passwordFromDb, String passwordFromInput) {
  return passwordFromDb.equalsIgnoreCase(passwordFromInput);

And many think this is perfectly fine and safe. Mmm, not really. If you look at the inputs you will see that they are of String type. Java as a String pool concept where it will maintain a pool of Strings in order to improve performance and keep memory in tact. But this means that your passwords will be kept in the String pool also for longer than you require it. This can be a safety concern if you application is vulnerable to outside intrusions. Ever wondered why JPasswordField.getPassword() returns a char array instead of a String? 

So how can we really compare two passwords safely. First of all we need to use CharSequence instead of String which is actually the super class of String. So we can pass a String to CharSequence safely. And we can use Java's XOR operator (^) to compare the characters in the two CharSequence one by one and use OR operator to (|) store the result in an int variable which will look like below;

 private static boolean checkPasswordsSafely(CharSequence passwordFromDb, CharSequence passwordFromInput) {  
  if(passwordFromDb.length() != passwordFromInput.length()) {
   return false;
  int value = 0;
  for(int i=0;i

In this method if the lengths are not equal then we can straight forward return false and if lengths are equals we can loop through each character and get the final result. At the end the value should always be 0 if both CharSequences are equal. 

Tags: Java Password Comparison Equals
Views: 1111
Register for more exciting articles


Please login or register to post a comment.

There are currently no comments.