首页 > 解决方案 > 如何在 java 中读取 rsa 公钥文件?

问题描述

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

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

我用java来阅读它:

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 可读格式?

标签: javasecurityopensslrsa

解决方案


试试这个方法:

 /**
 * 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 公钥


推荐阅读