title: Java: Convert DKIM private key from RSA to DER for JavaMail
body: <p>I'm using <a href="http://www.agitos.de/produkte/open-source-development/dkim-for-javamail/" rel="nofollow noreferrer">DKIM for JavaMail</a> to sign outgoing mail with DKIM.<br>
  My private DKIM key is generated with <code>opendkim-genkey -s default -d example.com</code> and looks like this:  </p>
  
  <pre><code>-----BEGIN RSA PRIVATE KEY-----
  ABCCXQ...[long string]...SdQaZw9
  -----END RSA PRIVATE KEY-----
  </code></pre>
  
  <p>The DKIM for JavaMail library needs the private DKIM key in DER format as stated in their readme file:</p>
  
  <blockquote>
    <p>DKIM for JavaMail needs the private key in DER format, you can
    transform a PEM key
         with openssl:</p>
    
    <p><code>openssl pkcs8 -topk8 -nocrypt -in private.key.pem -out private.key.der -outform der</code></p>
  </blockquote>
  
  <p>I am looking for a way to avoid having to use openssl to convert my key to DER format. Instead I would like to do the conversion in Java directly.<br>
  I have tried different suggestions <a href="https://stackoverflow.com/questions/21173929/java-convert-rsa-pem-key-string-to-der-byte">(1</a>, <a href="https://stackoverflow.com/questions/4032985/how-do-we-convert-a-string-from-pem-to-der-format">2</a>, <a href="https://stackoverflow.com/questions/7216969/getting-rsa-private-key-from-pem-base64-encoded-private-key-file">3</a>) but nothing has worked so far.<br>
  DKIM for Java processes the DER file like this:</p>
  
  <pre><code>    File privKeyFile = new File(privkeyFilename);
  
      // read private key DER file
      DataInputStream dis = new DataInputStream(new FileInputStream(privKeyFile));
      byte[] privKeyBytes = new byte[(int) privKeyFile.length()];
      dis.read(privKeyBytes);
      dis.close();
  
      KeyFactory keyFactory = KeyFactory.getInstance("RSA");
  
      // decode private key
      PKCS8EncodedKeySpec privSpec = new PKCS8EncodedKeySpec(privKeyBytes);
      RSAPrivateKey privKey = (RSAPrivateKey) keyFactory.generatePrivate(privSpec);
  </code></pre>
  
  <p>So in the end what I need is the <code>RSAPrivateKey</code>.  </p>
  
  <p><strong>How can I easily generate this <code>RSAPrivateKey</code> that DKIM for JavaMail requires from my RSA private key?</strong></p>