views:

69

answers:

1

Hi All,

I have to read pem key files to get RSA Public key,and then use them to encrypt. I can do this using openssl and convert pem file to der file. and then load my key using X509EncodedKeySpec and PKCS8EncodedKeySpec. But I don't want to do this because pem is the user key exchange format. user can register it's own key can like this :

--BEGIN PUBLIC KEY-- MIGeMA0GCSqGSIb3DQEBAQUAA4GMADCBiAKBgGi0/vKrSIIQMOm4atiw+2s8tSojOKHsWJU3oPTm

b1a5UQIH7CM3NgtLvUF5DqhsP2jTqgYSsZSl+W2RtqCFTavZTWvmc0UsuK8tTzvnCXETsnpjeL13

Hul9JIpxZVej7b6KxgyxFAhuz2AGscvCXnepElkVh7oGOqkUKL7gZSD7AgMBAAE=

--END PUBLIC KEY--

and this key is store in a database in this format...

Here is the code I have tried..

File pubKeyFile=new File("D:/public_key.pem");
DataInputStream dis = new DataInputStream(new FileInputStream(pubKeyFile));
byte[] pubKeyBytes = new byte[(int)pubKeyFile.length()];
dis.readFully(pubKeyBytes);
dis.close();
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
X509EncodedKeySpec pubSpec = new X509EncodedKeySpec(pubKeyBytes);
RSAPublicKey pubKey = (RSAPublicKey) keyFactory.generatePublic(pubSpec);

I am getting exception as

java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException: invalid key format

As I am completely new to encryption concepts can anyone please help me to solve this exception?

Many thanks.

+1  A: 

With bouncycastle, it would be done this way:

CertificateFactory cf = CertificateFactory.getInstance("X509", "BC");
InputStream is = new FileInputStream("D:/public_key.pem");
X509Certificate certificate = (X509Certificate) cf.generateCertificate(is);
is.close();
RSAPublicKey pubKey = (RSAPublicKey)certificate.getPublicKey();
Maurice Perry
+1, I thought you had to use the PEMReader class, didn't realize you could just specify the "BC" provider to CeritificateFactory.
GregS
Yes, but in fact in this case, using the PEMReader would be simpler...
Maurice Perry