title: Using ECDSA private key in Java with BouncyCastle
body: <p>I'm trying to use ECDSA in Java with BouncyCastle library and the private key I get by reading the pkcs12 file in Java is different than what I see in the PEM file (which I got using openssl). I'm unsure if they should be the same but seems logical. Question is how do I get the same private key in Java using BC from a pkcs12 file as using openssl?</p>
  
  <p>The cert and the key was generated with</p>
  
  <pre><code>openssl ecparam -name secp521r1 -genkey -param_enc explicit -out private-key.pem
  openssl req -new -x509 -key private-key.pem -out server.pem -days 730              
  openssl pkcs12 -export -clcerts -in server.pem -inkey private-key.pem -out ecdsaCertificate.p12
  </code></pre>
  
  <p>Java code:</p>
  
  <pre><code> Public static void readCertificateData()
        throws KeyStoreException, NoSuchProviderException, NoSuchAlgorithmException, CertificateException,
        FileNotFoundException, IOException, UnrecoverableKeyException {
  
  System.out.println("Get KeyStore");
  KeyStore pkcs12Store = KeyStore.getInstance("pkcs12", "BC");
  System.out.println("Read File");
  pkcs12Store.load(new FileInputStream(CERT), PASSWORD.toCharArray());
  
  Enumeration aliasEnum = pkcs12Store.aliases();
  Key key = null;
  Certificate cert = null;
  
  while (aliasEnum.hasMoreElements()) {
  
        String keyName = (String) aliasEnum.nextElement();
        key = pkcs12Store.getKey(keyName, PASSWORD.toCharArray());
        ECPrivateKey ecKey = (ECPrivateKey) key;
  
        System.out.println("ecKey : \n" + ecKey.toString());
        System.out.println("privKeyToDER:\n" + privateKeyToDER((PrivateKey) key));
        cert = pkcs12Store.getCertificate(keyName);
        System.out.println("cert2 :\n" + Base64.toBase64String((cert.getEncoded())));
  
        StringToFile(DIR + "tempCert.pem", "-----BEGIN CERTIFICATE-----\n"
                + Base64.toBase64String((cert.getEncoded())) + "-----END CERTIFICATE-----\n");
        System.out.println("privKey Base64 : " + Base64.toBase64String(key.getEncoded()));
        cert = pkcs12Store.getCertificate(keyName);
  }
  }
  public static String privateKeyToDER(PrivateKey key) throws IOException {
      ByteArrayOutputStream bos = new ByteArrayOutputStream();
      JcaPEMWriter pemWriter = new JcaPEMWriter(new OutputStreamWriter(bos));
  
      pemWriter.writeObject(key);
      pemWriter.close();
  
      return new String(bos.toByteArray());
  }
  </code></pre>