title: Reading a PKCS#1 or SPKI public key in Java without libraries
body: <p>I need to use a public key to verify some data in Java, but I can't seem to format the key in such a way that Java can use without third-party plugins.</p>
  
  <p>I'm generating the key with Node.js's <code>crypto</code> library, which gives me the option of <code>PKCS#1</code> or <code>SPKI</code>, and either .pem or .der file format.</p>
  
  <p>I've heard that Java doesn't support <code>PKCS#1</code> out-of-the box, and pretty much every other answer on StackOverflow recommends using BouncyCastle or similar, but in my case, I am writing an SDK, and simply cannot afford to use a library just to read this public key.</p>
  
  <p>So I'm currently reading the key in .der format as it saves having to strip the PEM headers and decode the key from base-64. When I run this, I get the error:</p>
  
  <pre><code>java.security.spec.InvalidKeySpecException: java.lang.RuntimeException: error:0c0000be:ASN.1 encoding routines:OPENSSL_internal:WRONG_TAG
  </code></pre>
  
  <p>Here's what I have (sorry, it's in Kotlin, not Java like the title suggests)</p>
  
  <pre><code>// Here's a key for convenience
  val key = Base64.getDecoder().decode("MFUCTgF/uLsPBS13Gy7C3dPpiDF6SYCLUyyl6CFqPtZT1h5bwKR9EDFLQjG/kMiwkRMcmEeaLKe5qdj9W/FfFitwRAm/8F53pQw2UETKQI2b2wIDAQAB");
  
  val keySpec = X509EncodedKeySpec(key)
  val keyFactory = KeyFactory.getInstance("RSA")
  val publicKey = keyFactory.generatePublic(keySpec) // error thrown here
  
  val cipher = Cipher.getInstance("RSA/NONE/PKCS1Padding")
  cipher.init(Cipher.DECRYPT_MODE, publicKey)
  </code></pre>
  
  <p>My best idea at the minute is to install a library on the Node.js side, which is less problematic, to support exporting the key as PKCS#8, but I thought I'd check first to see if I'm missing anything.</p>