So finally, after hours of research I came with a solution and finally could get read my public key from .pem file and generate an instance of this key. Hence, I managed to encrypt the data.
But I had to copy and paste the key content without any special character like '\n' and make a publicKeyString
with it
----------BEGIN RSA PUBLIC KEY---------
key content
----------END RSA PUBLIC KEY---------
static public PublicKey publicKey(String publicKeyString) {
try {
byte[] decodedPublicKey = Base64.decode(publicKeyString, 0);
ASN1InputStream in = new ASN1InputStream(decodedPublicKey);
ASN1Primitive obj = in.readObject();
RSAPublicKeyStructure keyStruct = RSAPublicKeyStructure.getInstance(obj);
RSAPublicKeySpec keySpec = new RSAPublicKeySpec(keyStruct.getModulus(), keyStruct.getPublicExponent());
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
return keyFactory.generatePublic(keySpec);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (InvalidKeySpecException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
I failed even when I tried to use PEMReader from bouncy castle. All the problems have something to do with keys generated in Ruby version prior 1.9.3 as described with details here.
Anyway, thanks a lot for the attention disposed.