title: How do I load and decrypt an encrypted key file for a cert in Go?
body: <p>I have a cert file and a key file where the key file is encrypted with a password. I am trying to decrypt the key file programmatically before loading the key pair.</p>
  <pre><code>// Key file and cert file path
  cf := filepath.Join(certPath, certFile)
  kf := filepath.Join(certPath, keyFile)
  
  //Read &amp; decode the encrypted key file with the pass to make tls work
  keyIn, err := ioutil.ReadFile(kf)
  if err != nil {
      log.Error(&quot;Read key error&quot;, err)
      return nil, err
  }
  
  // Decode and decrypt our PEM block
  decodedPEM, _ := pem.Decode([]byte(keyIn))
  decrypedPemBlock, err := x509.DecryptPEMBlock(decodedPEM, []byte(&quot;somepassword&quot;))
  if err != nil {
      log.Error(&quot;decrypt key error&quot;, err)
      return nil, err
  }
  
  // Load our decrypted key pair
  crt, err := tls.LoadX509KeyPair(cf, string(decrypedPemBlock))
  if err != nil {
      log.Error(&quot;load key pair error&quot;, err)
      return nil, err
  }
  </code></pre>
  <p>The original certs and key were generated using the following openssl parameters</p>
  <pre><code>openssl req -new -newkey rsa:2048 -x509 -keyout $CA_CERT.key -out $CA_CERT -days $validity -passin &quot;pass:$password&quot; -passout &quot;pass:$password&quot; -subj &quot;/C=$C/ST=$ST/L=$L/O=$O/CN=$CN/emailAddress=$EMAIL&quot;
  </code></pre>
  <p>The variables are substituted accordingly with $password being &quot;somepassword&quot;</p>
  <p>I have tried decrypting the key using <code>openssl rsa</code> from the command line and it works fine with the the password above.</p>
  <p>However in Go I get an error in <code>tls.LoadX509KeyPair</code> saying invalid argument.</p>
  <pre><code>time=&quot;2018-01-17T18:57:40Z&quot; level=error msg=&quot;load key pair error: open
  </code></pre>
  <p>My best guess is that the key encoding might be messed up and I was wondering if anything is wrong with my code.</p>
  <p>Update: Added error message and it seems like <code>tls.LoadX509KeyPair</code> can't understand the format as comments have pointed out below.</p>