Determining If Two Keys Are Equal
In many cases you would like to know if two keys are equal; however,
the default method
java.lang.Object.equals might
not give the desired result. The most provider-independent approach
is to compare the encoded keys. If this comparison isn't appropriate
(for example, when comparing an RSAPrivateKey and
an RSAPrivateCrtKey), you should compare each component.
The following code demonstrates this idea: 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 if
// an RSAPrivateKey and an RSAPrivateCrtKey are equal:
// if ((key1 instanceof RSAPrivateKey) &&
// (key2 instanceof RSAPrivateKey)) {
// if ((key1.getModulus().equals(key2.getModulus())) &&
// (key1.getPrivateExponent().equals(
// key2.getPrivateExponent()))) {
// return true;
// }
// }
return false;
}