如何在Java中读取rsa公钥文件?

时间:2018-08-06 11:17:25

标签: java security openssl rsa

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

dns.rdtypes.IN.SRV.SRV

我用java来阅读它:

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

然后我得到一个例外:

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

如何正确读取文件?有没有办法将此rsa公钥文件转换为Java可读格式?

2 个答案:

答案 0 :(得分:3)

尝试此方法:

 /**
 * 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);
}

来源:Load RSA public key from file

答案 1 :(得分:0)

这是我的实现;可以使用密钥或证书读取 PEM。 仅在 java11 中测试。


  /**
   * reads a public key from a file
   * @param f file to read
   * @return the read public key
   * @throws Exception
   */
  public static PublicKey getPublicKeyFromPem(File f)
     throws Exception
  {
    byte[] keyBytes = Files.readAllBytes(f.toPath());

    String temp = new String(keyBytes);
    String publicKeyPEM = temp;

    if(temp.contains("-----BEGIN PUBLIC KEY-----"))
    {
      publicKeyPEM = temp
         .replace("-----BEGIN PUBLIC KEY-----\n", "")
         .replace("-----END PUBLIC KEY-----", "")
         .trim();
    }
    else if(temp.contains("-----BEGIN RSA PUBLIC KEY-----"))
    {
      publicKeyPEM = temp
         .replace("-----BEGIN RSA PUBLIC KEY-----\n", "")
         .replace("-----END RSA PUBLIC KEY-----", "")
         .trim();
    }
    else if(temp.contains("-----BEGIN CERTIFICATE-----"))
    {
      CertificateFactory fact = CertificateFactory.getInstance("X.509");
      try (FileInputStream is = new FileInputStream(f))
      {
        X509Certificate cer = (X509Certificate) fact.generateCertificate(is);
        return cer.getPublicKey();
      }
    }

    Base64.Decoder b64 = Base64.getDecoder();
    byte[] decoded = b64.decode(publicKeyPEM);

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