title: java.security.InvalidKeyException: invalid key format while reading from .CRT file
body: <p>I am trying to load the key from a .crt file. Below is my code</p>
  
  <pre><code>Path path = Paths.get(filePath);
  byte[] bytes;
  
  try {
      bytes = Files.readAllBytes(path);
  
      /* Generate public key. */
          X509EncodedKeySpec ks = new X509EncodedKeySpec(bytes);
          KeyFactory kf = KeyFactory.getInstance("RSA");
          PublicKey pubKey = kf.generatePublic(ks);
  </code></pre>
  
  <p>Exception thrown @kf.generatePublic(ks).</p>
  
  <p>Exception: java.security.InvalidKeyException: invalid key format</p>
  
  <p>Below is the .crt file contents</p>
  
  <pre><code>-----BEGIN CERTIFICATE-----
  MIIBpzCCAVECBEqbmP4wDQYJKoZIhvcNAQEEBQAwXTELMAkGA1UEBhMCVVMxDjAMBgNVBAgTBVRF
  //trimmed key
  -----END CERTIFICATE-----
  </code></pre>
  
  <p>I could not find what's wrong with my code. This key is used to RSA public encrypt a key (PBKDF2 key) in C code. </p>
  
  <pre><code>//openssl
  RSA_public_encrypt(msgLen, msg, encryptedMsg, rsaPubKey, RSA_PKCS1_PADDING)
  </code></pre>
  
  <p>I am trying to implement it in Java. Am I missing anything? Please guide</p>
  
  <p><strong>UPDATE 1:</strong></p>
  
  <p>Overcame the exception using the below code:</p>
  
  <pre><code>        InputStream inStream = null;
      try {
          inStream = RefundUtil.class.getClassLoader().getResourceAsStream("refund.crt");
  
          CertificateFactory cf = CertificateFactory.getInstance("X.509");
          X509Certificate cert = (X509Certificate) cf.generateCertificate(inStream);
          PublicKey pubKey = cert.getPublicKey();
  
          Cipher encryptCipher = Cipher.getInstance("RSA");
          encryptCipher.init(Cipher.ENCRYPT_MODE, pubKey);
  
          byte[] cipherText = encryptCipher.doFinal(sessionKey);
  
          inStream.close();
          return Base64.getEncoder().encodeToString(cipherText);
  
      } catch (IOException e) {
          LOGGER.error(e.getMessage());
      }
  </code></pre>