I am playing around with an idea I have for storing a public key for myself. For this I would need to transform the BigInteger in some sort of a variable and then recreate the BigInteger from that value.
I have searched through Stackoverflow to find the best way to do this is with byte[].
This is my code in Eclipse:
import java.math.BigInteger;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.interfaces.RSAPublicKey;
public class Vaja2 {
public static void main(String[] args){
try {
// Create RSA Keypair (to obtain a BigInteger)
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(1024);
KeyPair keypair = kpg.generateKeyPair();
// Extract the public key
RSAPublicKey publicKey = (RSAPublicKey) keypair.getPublic();
// Get the public Exponent from the public key, I have BigInteger now.
BigInteger pkPublicExBI = publicKey.getPublicExponent();
//Try this: BigInteger -> byte-> BigInteger
byte[] pkModByte = pkPublicExBI.toByteArray();
BigInteger pkPublicExBIrecreated = new BigInteger(pkModByte);
// Show Results
System.out.println("Original BigInteger: " + pkPublicExBI);
System.out.println("Recreated BigInteger: " + pkPublicExBIrecreated);
if (pkPublicExBI == pkPublicExBIrecreated) {
System.out.println("\nThey are equal");
}
else {
System.out.println("\nThey are NOT equal");
}
} catch (Exception e) {
// Nothing happens
}
}
}
And this is the result in shown in the Eclipse console.
Original BigInteger: 65537
Recreated BigInteger: 65537
They are NOT equal
The if statement tells me, that the two BigIntegers are not equal. Yet in the console, I see them as both being equal to 65537.
My questions:
Why does the "if" statement fail?
How would you recommend me to make the code different. Assuming the program will demand public key to be stored in notepad.exe or similar text-encoding program (ASCII will be used).
use this instead
pkPublicExBI.equals(pkPublicExBIrecreated)
.Use
.equals()
as opposed to==
when comparing objects.==
will compare the objects' references, whereas.equals()
will check to see if they have the same values. Since two objects will very rarely have the same reference you should never use==
except for comparing primitive types (int, char, but String is not a primitive type!) where it doesn't matter.So you want:
Instead of