如何在java中读取rsa公钥文件? [英] How to read a rsa public key file in java?

查看:151
本文介绍了如何在java中读取rsa公钥文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的 RSA 公钥文件:

I have a RSA public key file like this:

-----BEGIN RSA PUBLIC KEY-----
this is content
-----END RSA PUBLIC KEY-----

我用java来阅读它:

and i use java to read it:

KeyFactory factory = KeyFactory.getInstance("RSA");
KeySpec spec = new X509EncodedKeySpec(bytesFromThisFile); // bytesFromThisFile is created and filled correctly 
PublicKey publicKey = factory.generatePublic(spec);

然后我得到一个例外:

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

如何正确读取文件?有没有办法把这个rsa公钥文件转换成java可读的格式?

How to read the file properly? Is there a way to convert this rsa public key file to a java-readable format?

推荐答案

试试这个方法:

 /**
 * reads a public key from a file
 * @param filename name of the file to read
 * @param algorithm is usually RSA
 * @return the read public key
 * @throws Exception
 */
public  PublicKey getPemPublicKey(String filename, String algorithm) 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();

      String temp = new String(keyBytes);
      String publicKeyPEM = temp.replace("-----BEGIN PUBLIC KEY-----\n", "");
      publicKeyPEM = publicKeyPEM.replace("-----END PUBLIC KEY-----", "");


      BASE64Decoder b64 = new BASE64Decoder();
      byte[] decoded = b64.decodeBuffer(publicKeyPEM);

      X509EncodedKeySpec spec = new X509EncodedKeySpec(decoded);
      KeyFactory kf = KeyFactory.getInstance(algorithm);
      return kf.generatePublic(spec);
}

来源:从文件加载 RSA 公钥

这篇关于如何在java中读取rsa公钥文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆