The method java.lang.Object.equals()
, by default, is unable to compare composite objects such as cryptographic keys. Most Key
classes do not fail to provide an equals()
implementation that overrides Object
's default implementation.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 but the . The keys may compare unequal even when they represent the same value.
Code Block | ||
---|---|---|
| ||
private static boolean keysEqual(Key key1, Key key2) { if (key1.equals(key2)) { return true; } return false; } |
Compliant Solution
This compliant solution uses the {{ Wiki Markup equals()
}} method as a first test and then compares the encoded version of the keys to facilitate provider-independent behavior. For example, it can be checked if a {{RSAPrivateKey}} and {{RSAPrivateCrtKey}} are the same. \[[Sun 06|AA. Java References#Sun 06]\]behavior. It checks whether an RSAPrivateKey
and an RSAPrivateCrtKey
represent equivalent private keys [Oracle 2011b].
Code Block | ||
---|---|---|
| ||
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 ifwhether // 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; } |
Risk Assessment
Using Object.equals()
to compare cryptographic keys may not yield accurate results.
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
MSC35- J | high | unlikely | low | P9 | L2 |
Automated Detection
TODO
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
References
Wiki Markup |
---|
\[[API 06|AA. Java References#API 06]\]
\[[Sun 06|AA. Java References#Sun 06]\] [Determining If Two Keys Are Equal|http://java.sun.com/javase/6/docs/technotes/guides/security/crypto/CryptoSpec.html#Determining%20If%20Two%20Keys%20Are%20Equal] (JCA Reference Guide) |
Automated Detection
Tool | Version | Checker | Description | ||||||
---|---|---|---|---|---|---|---|---|---|
The Checker Framework |
| Interning Checker | Errors in equality testing and interning (see Chapter 5) |
Bibliography
[API 2013] | java.lang.Object.equals() , Object.equals() |
[Oracle 2011b] | Determining If Two Keys Are Equal (JCA Reference Guide) |
...
FIO36-J. Do not create multiple buffered wrappers on an InputStream 09. Input Output (FIO) 09. Input Output (FIO)