Well, your first problem:
keyGen.genKeyPair().getPublic().getEncoded(); keyGen.genKeyPair().getPrivate().getEncoded();
You do not save the key pair, so you generate public and private keys that do not match. From javadocs, genKeyPair() behaves as follows:
This will generate a new key pair every time it is called.
Secondly, getEncoded () simply returns the key as an array of bytes. If your database can store binary values, just save it that way. Otherwise, you would probably be lucky to turn it into a String. For example, you can use base 64 with this neat little trick (perhaps more reliable than you do):
String keyAsString = new BigInteger(publicKey.getEncoded()).toString(64);
Subsequently, you can return the original bytes with:
byte[] bytes = new BigInteger(keyAsString, 64).toByteArray();
You say you get the same value every time you start (and make sure you worry about it before), and I'm not 100% sure why. You must have access to the parameters of the algorithm (you may need to impose a key on another type), try printing them to see if they match. Someone mentioned checking your random number generator, which might also be a good idea.
source share