开发者

RSA encryption :InvalidKeyException: invalid key format

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.


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();


You were almost there, with the standard provider. You just need to strip the header and footer lines:

List<String> lines = Files.readAllLines(Paths.get(path), StandardCharsets.US_ASCII);
if (lines.size() < 2) 
    throw new IllegalArgumentException("Insufficient input");
if (!lines.remove(0).startsWith("--"))
    throw new IllegalArgumentException("Expected header");
if (!lines.remove(lines.size() - 1).startsWith("--")) 
    throw new IllegalArgumentException("Expected footer");
byte[] raw = Base64.getDecoder().decode(String.join("", lines));
KeyFactory factory = KeyFactory.getInstance("RSA");
PublicKey pub = factory.generatePublic(new X509EncodedKeySpec(raw));


try using bouncycastele's PemReader .

PublicKey getPublicKey(String pubKeyStr) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException { 
    PemObject pem = new PemReader(new StringReader(pubKeyStr)).readPemObject();
    byte[] pubKeyBytes = pem.getContent();
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    X509EncodedKeySpec pubSpec = new X509EncodedKeySpec(pubKeyBytes);
    RSAPublicKey pubKey = (RSAPublicKey) keyFactory.generatePublic(pubSpec);
    return pubKey;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜