Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

The method java.lang.Object.equals() by default, is unable to compare composite objects such as cryptographic keys. Most Key classes fail to provide an equals() implementation that overrides Object.equals(). In such cases, the components of the composite object must be compared individually to ensure correctness.

Noncompliant Code Example

This noncompliant code example compares two keys using the equals() method. The keys may compare unequal even when they represent the same value.

Code Block
bgColor#FFCCCC
private static boolean keysEqual(Key key1, Key key2) {
  if (key1.equals(key2)) {
    return true;
  }
}

Compliant Solution

This compliant solution uses the equals() method as a first test and then compares the encoded version of the keys to facilitate provider-independent behavior. It checks whether an RSAPrivateKey and an RSAPrivateCrtKey represent equivalent private keys [Sun 2006].

Code Block
bgColor#ccccff
private static boolean keysEqual(Key key1, Key key2) {
  if (key1.equals(key2)) {
    return true;
  }

  if (Arrays.equals(key1.getEncoded(), key2.getEncoded())) {
    return true;
  }

  // More code for different types of keys here.
  // For example, the following code can check whether
  // an RSAPrivateKey and an RSAPrivateCrtKey are equal:
  if ((key1 instanceof RSAPrivateKey) &&
      (key2 instanceof RSAPrivateKey)) {
  
    if ((((RSAKey) key1).getModulus().equals(((RSAKey) key2).getModulus()))
       && (((RSAPrivateKey) key1).getPrivateExponent().equals(
           ((RSAPrivateKey) key2).getPrivateExponent()))) {
      return true;
    }
  }
  return false;
}

Automated Detection

Using Object.equals() to compare cryptographic keys may yield unexpected results.

Bibliography

[API 2011] java.lang.Object.equals(), Object.equals()
[Sun 2006]Determining If Two Keys Are Equal (JCA Reference Guide)

...