Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare PublicKey object in java

I have two PublicKey object.I want to compare both for equality or to check which is latest object using java security API or bouncy castle API.How can i achieve this?

like image 634
Swapnil Avatar asked Jan 20 '14 10:01

Swapnil


1 Answers

You can use equals

if (!key.equals(copyKey)){
    System.out.println("not equals!");
}

or check the hashcode of the keys

if (key.hashCode() != copyKey.hashCode())
{
    System.out.println("public key hashCode check failed");
}

or compare the hex string of the two public keys

String encodedKey1 = new String(Hex.encode(key1.getEncoded()));
String encodedKey2 = new String(Hex.encode(key2.getEncoded()));

if (!encodedKey1.equals(encodedKey2)){
    System.out.println("not equals!");
}

You have a lot of key comparision and check samples at Bouncy Castle Tests, take a look at the org.bouncycastle.jce.provider.test package for some code. BC is not strictly necesary you can do the comparision with the default java security classes.

like image 141
vzamanillo Avatar answered Oct 01 '22 14:10

vzamanillo