Reputation: 740
I generated a keystore using keytool with this command:
keytool -genkey -alias serverprivate -keystore serverprivate.jks -storetype JKS -keyalg RSA -sigalg SHA256withRSA -keysize 2048 -storepass doyouknowdewey
The key pass and store pass are the same. Then I extract the public key and insert it into it's own keystore:
keytool -export -alias serverprivate -keystore serverprivate.jks -file temp.key -storepass doyouknowdewey
keytool -import -noprompt -alias serverpublic -keystore serverpublic.jks -file temp.key -storepass public
Now I create an InputStream in java with a keystore and create a KeyStore object:
InputStream is = getClass().getResourceAsStream("keys/serverprivate.jks");
KeyStore serverPrivate = KeyStore.getInstance("JKS");
serverPrivate.load(is, "doyouknowdewey".toCharArray());
And I extract the key to make a cipher instance so can encrypt and decrypt the text:
Key key = serverPrivate.getKey("serverprivate", "douyouknowdewey".toCharArray());
This all works fine, and I can encrypt data with the private key. But if I try decrpyting/encrypting with the public key, the Key
object is null:
InputStream is = getClass().getResourceAsStream("keys/serverpublic.jks");
KeyStore serverPublic = KeyStore.getInstance("JKS");
serverPublic.load(is, "public".toCharArray());
Key key = serverPrivate.getKey("serverpublic", "public".toCharArray());
if(key == null) {
System.err.println("Key is null");
}
//returns null
So how do I make this work?
EDIT:
Apparently serverpublic isn't a key, but a certificate. I found out by running serverPublic.isKeyEntry("serverpublic");
, which returned false, while serverPublic.isCertificateEntry("serverpublic");
returned true. So I changed the code to this:
InputStream is = getClass().getResourceAsStream("keys/serverpublic.jks");
KeyStore serverPublic = KeyStore.getInstance("JKS");
serverPublic.load(is, "public".toCharArray());
Certificate cert = serverPrivate.getCertificate("serverpublic");
if(cert == null) {
System.err.println("Key is null");
}
This doesn't return null any longer. But when I run this, cipher.init
still throws a nullpointer exception:
Cipher cipher;
cipher.init(Cipher.ENCRYPT_MODE, cert);
Upvotes: 0
Views: 4974
Reputation: 740
serverpublic wasn't a key, but a certificate. I had to load it using
Certificate cert = serverPrivate.getCertificate("serverpublic");
and then call
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, cert);
Upvotes: 1