title: Convert elliptic curve private key to (unencrypted) PKCS#8 format
body: <p>I am trying to convert EC private key</p>
  <pre><code>-----BEGIN EC PRIVATE KEY-----
  MHcCAQEEIE2tzb8O0gBVw2IFOB/B8l1Ztjax3ut4DeNtuC3UMmZ6oAoGCCqGSM49
  AwEHoUQDQgAEayT6Tv8zZlpIUOKHEYnmsKZyTaqOHajL0InS4c5tK4fhkHZDSWUa
  3tPl1ibIXt0LvaxHk47h0Tc4SGr3Ex8Bhg==
  -----END EC PRIVATE KEY----- 
  </code></pre>
  <p>to Private Key</p>
  <pre><code> -----BEGIN PRIVATE KEY-----
  MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgTa3Nvw7SAFXDYgU4
  H8HyXVm2NrHe63gN4224LdQyZnqhRANCAARrJPpO/zNmWkhQ4ocRieawpnJNqo4d
  qMvQidLhzm0rh+GQdkNJZRre0+XWJshe3Qu9rEeTjuHRNzhIavcTHwGG
  -----END PRIVATE KEY-----
  </code></pre>
  <p>It's very easy when you execute openSsl command like this:</p>
  <pre><code>openssl pkcs8 -topk8 -nocrypt -in ec1.pem -out ec2.pem
  </code></pre>
  <p>But i want to do this in Java way and didn't find any solution (tried so many from stackoverflow).
  So i have for now following class:</p>
  <pre><code>        ECNamedCurveParameterSpec ecNamedCurveParameterSpec = ECNamedCurveTable.getParameterSpec(&quot;prime256v1&quot;);
          KeyPairGenerator keyPair = KeyPairGenerator.getInstance(&quot;ECDSA&quot;, &quot;BC&quot;);
  
          // Create a secure random number generator using the SHA1PRNG algorithm
          SecureRandom secureRandomGenerator = SecureRandom.getInstance(&quot;SHA1PRNG&quot;);
          keyPair.initialize(ecNamedCurveParameterSpec, secureRandomGenerator);
      
  </code></pre>
  <p>Then i generate KeyPair and get PrivateKey in ECPrivateKey Object:</p>
  <pre><code>KeyPair pair =keyPair.generateKeyPair();
  ECPrivateKey privateKey = (ECPrivateKey) pair.getPrivate();
  StringWriter sw = new StringWriter();
  
          try (JcaPEMWriter jcaPEMWriter = new JcaPEMWriter(sw);) {
              jcaPEMWriter.writeObject(privateKey);
          }
  
  String pemFormat = sw.toString();
  </code></pre>
  <p>This string pemFormat is actually PEM format that starts with <code>BEGIN EC PRIVATE KEY</code></p>
  <p>How can i convert it just to <code>BEGIN PRIVATE KEY</code>?</p>
  <p>I assume that should be a way if openSsl can do it.</p>