I have created the public and private key . The public and private key generated from php code :
<?php
require __DIR__ . '/vendor/autoload.php';
use phpseclib\Crypt\RSA;
$rsa = new RSA();
extract($rsa->createKey());
$rsa->setPrivateKeyFormat(RSA::PRIVATE_FORMAT_PKCS8);
$rsa->setPublicKeyFormat(RSA::PUBLIC_FORMAT_PKCS8);
file_put_contents("privateKey.pem",$privatekey);
file_put_contents("publicKey.pem", $publickey);
The java source code to read those keys:
import java.io.*;
import java.security.*;
import java.security.spec.*;
public class PublicKeyReader {
public static PublicKey get(String filename)
throws Exception {
File f = new File(filename);
FileInputStream fis = new FileInputStream(f);
DataInputStream dis = new DataInputStream(fis);
byte[] keyBytes = new byte[(int)f.length()];
dis.readFully(keyBytes);
dis.close();
X509EncodedKeySpec spec =
new X509EncodedKeySpec(keyBytes);
KeyFactory kf = KeyFactory.getInstance("RSA");
return kf.generatePublic(spec);
}
public static void main (String [] args) throws Exception {
PublicKeyReader publicKeyReader = new PublicKeyReader();
PublicKey publicKey = publicKeyReader.get("key/testPub.pem");
System.out.println(publicKey);
}
}
It produces java.security.InvalidKeyException: invalid key format.
Need help on this. Thanks in advance.