我已经创建了公钥和私钥。从php代码生成的公钥和私钥:
<?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);
读取这些键的Java源代码:
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);
}
}
它产生java.security.InvalidKeyException: invalid key format.
对此需要帮助。预先感谢。