title: What is special for a private key to be PEM-formatted?
body: <p>I am trying to use the <a href="https://developers.google.com/identity/protocols/OAuth2ServiceAccount" rel="nofollow">Google API with a oAuth service account</a>, with Python 3.4. One of the steps is to <a href="https://developers.google.com/identity/protocols/OAuth2ServiceAccount#creatingjwt" rel="nofollow">generate a JSON Web Token</a>, for which I use <a href="https://github.com/jpadilla/pyjwt" rel="nofollow"><code>PyJWT</code></a>.</p>
  
  <p>My code for the generation is the following:</p>
  
  <pre><code># opening the certificate downloaded from the Google API console
  # it is password protected by the standard password ('notasecret')
  p12 = OpenSSL.crypto.load_pkcs12(open('certfromgoogle.p12', 'rb').read(), 'notasecret')
  
  # extracting the private key from the certificate and dumping it to a PEM
  # format (FILETYPE_PEM)
  private_key = OpenSSL.crypto.dump_privatekey(OpenSSL.crypto.FILETYPE_PEM, p12.get_privatekey())
  
  # at that stage, private_key contains the private key as
  # b'-----BEGIN PRIVATE KEY-----\nMIICdg(...)FIyw==\n-----END PRIVATE KEY-----\n'
  
  # trying to get the JWT
  encoded = jwt.encode(claim, private_key, algorithm='RS256', headers={"alg": "RS256", "typ": "JWT"})
  </code></pre>
  
  <p>The call to <code>jwt.encode</code> crashes with <code>TypeError: Expecting a PEM-formatted key</code>. The full traceback:</p>
  
  <pre><code>Traceback (most recent call last):
    File "C:/Users/w_000/PycharmProjects/syncmagazines/testcrypto.py", line 20, in &lt;module&gt;
      encoded = jwt.encode(claim, private_key, algorithm='RS256', headers={"alg": "RS256", "typ": "JWT"})
    File "C:\Python34\lib\site-packages\jwt\api.py", line 118, in encode
      key = alg_obj.prepare_key(key)
    File "C:\Python34\lib\site-packages\jwt\algorithms.py", line 170, in prepare_key
      raise TypeError('Expecting a PEM-formatted key.')
  TypeError: Expecting a PEM-formatted key.
  </code></pre>
  
  <p>The private key, however, seems to be extracted correctly.</p>
  
  <p>Why isn't this format correct?</p>