title: How to extract DH parameters from a DH key in PEM format
body: <p>I have generated a Diffie-Hellman key using certain <code>g</code> and <code>p</code> parameters, like this:</p>
  
  <pre><code>$ cat dhparam.pem
  -----BEGIN DH PARAMETERS-----
  MIIBCAKCAQEAnc5+uXl2K09Nrp1oxN/KbIcIYLg8HXCu9UNW7gFknkHil7OVAKHR
  Km0Dc8IjqhJpDfoNKFoDo2Vd0KB9moSkDmhFmidcXO7Q8zSq0Z4BXFTO61OMukdd
  dul1ovbleqfH4DcbCjH4LiZGICFUyGseiBakt3e2BORyjSA3IEg4hm9WvdCevWPW
  Njc9reFgL6Vua8HkOGkLB+EvRP1YT4v5hGGP/6A7WxRevx5EjF9VgojyDLMPN26C
  3c17KY2jNV0W1GEcKEciWS61QInUDBDPYNuQzTl0LucbOpJyV3BFr6pokRBaO3bI
  ZYUPhjA2WSxJUeeJboJfisr+CQa9kc1dYwIBAg==
  -----END DH PARAMETERS-----
  $ openssl genpkey -paramfile dhparam.pem -out dh.pem
  $ cat dh.pem
  -----BEGIN PRIVATE KEY-----
  MIICJgIBADCCARcGCSqGSIb3DQEDATCCAQgCggEBAJ3Ofrl5ditPTa6daMTfymyH
  CGC4PB1wrvVDVu4BZJ5B4pezlQCh0SptA3PCI6oSaQ36DShaA6NlXdCgfZqEpA5o
  RZonXFzu0PM0qtGeAVxUzutTjLpHXXbpdaL25Xqnx+A3Gwox+C4mRiAhVMhrHogW
  pLd3tgTkco0gNyBIOIZvVr3Qnr1j1jY3Pa3hYC+lbmvB5DhpCwfhL0T9WE+L+YRh
  j/+gO1sUXr8eRIxfVYKI8gyzDzdugt3NeymNozVdFtRhHChHIlkutUCJ1AwQz2Db
  kM05dC7nGzqScldwRa+qaJEQWjt2yGWFD4YwNlksSVHniW6CX4rK/gkGvZHNXWMC
  AQIEggEEAoIBAGJBY5qzXPRi62hzho+ebCeZMdVqGQrlc9h/1hmrlzXlna8Mu8WF
  0hp/ol8s3AAvuG2w8sMHH/D0kHj2Ptf92khH2WObWAzyybf3IubpVumw6d2KSe1j
  LhW0cJum/lbyhyGJNgdNrVlwyNcId2Z53K9TK1BQnb3/gJjM+cRZ1yyoPDTXZpLl
  1dmLz3lw+kmowyNXtl/wgzDclR16/w7JSvM+tOFCs4X1ZZF9TbQi7czc0ov101gP
  bJjbUaYNOLUQrI/vVEDmCzYIL3PDLV07gQu0FeLHnRChgdjal3xVIsp0oV+2cN7K
  /UX4xqCSBXp8ieAoJ+r7zZD44JqhMVF+d5A=
  -----END PRIVATE KEY-----
  </code></pre>
  
  <p>My understanding is that the key file <code>dh.pem</code> includes not only the secret part of the key, but also the non-secret <code>g</code> and <code>p</code> <em>parameters</em> with which it was generated — i.e., <code>dh.pem</code> is a superset of <code>dhparam.pem</code>.</p>
  
  <p>I would like to reconstruct <code>dhparam.pem</code>, given <em>only</em> <code>dh.pem</code>. That is, given a DH key file, dump its parameters in PEM format.</p>
  
  <p>It seems like <code>openssl</code> itself might not support this directly, but maybe there's some not-too-horrible way to extract the info with a shell script or something? <a href="https://www.openssl.org/docs/man1.0.2/man1/dhparam.html" rel="noreferrer">The man page for <code>openssl dhparam</code></a> says:</p>
  
  <blockquote>
    <p>This program manipulates DH parameters not keys.<br>
    BUGS: There should be a way to generate and manipulate DH keys.</p>
  </blockquote>
  
  <p>Related: <a href="https://superuser.com/questions/905557/openssl-display-dh-parameters">OpenSSL: Display DH Parameters</a> — but in that question they're starting with a <em>certificate</em>, not a private key. (And I don't know the incantation to turn my key into a certificate.)</p>