title: ECDH using Android KeyStore generated private key
body: <p>I'm trying to implement ECDH in Android using a private generated by Android KeyStore Provider. </p>
  
  <pre><code>public byte[] ecdh(PublicKey otherPubKey) throws Exception {
  
      try {
          ECPublicKey ecPubKey = (ECPublicKey) otherPubKey;
          KeyAgreement keyAgreement = KeyAgreement.getInstance("ECDH");
          PrivateKey pk = (PrivateKey) LoadPrivateKey("Backend");
          keyAgreement.init(pk);
          keyAgreement.doPhase(ecPubKey, true);
  
          return (keyAgreement.generateSecret());
      }
      catch (Exception e)
      {
          Log.e("failure", e.toString());
          return null;
      }
  }
  </code></pre>
  
  <p>However, this exception is catched in keyAgreement.init(pk) : </p>
  
  <blockquote>
    <p>E/failure: java.security.InvalidKeyException: cannot identify EC private key: java.security.InvalidKeyException: no encoding for EC private key</p>
  </blockquote>
  
  <p>I generated before successfully the "Backend" Public/Private key pair using:</p>
  
  <pre><code>public void GenerateNewKeyPair(String alias)
          throws Exception {
  
      if (!keyStore.containsAlias(alias)) {
          // use the Android keystore
          KeyPairGenerator keyGen = KeyPairGenerator.getInstance(KeyProperties.KEY_ALGORITHM_EC, ANDROID_KEYSTORE);
          keyGen.initialize(
                  new KeyGenParameterSpec.Builder(
                          alias,
                          KeyProperties.PURPOSE_SIGN | KeyProperties.PURPOSE_VERIFY | KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
                          .setAlgorithmParameterSpec(new ECGenParameterSpec("secp256r1"))
                          .setDigests(KeyProperties.DIGEST_SHA256,
                                  KeyProperties.DIGEST_SHA384,
                                  KeyProperties.DIGEST_SHA512)
                          .setRandomizedEncryptionRequired(true)
                          .build());
          // generates the keypair
          KeyPair keyPair = keyGen.generateKeyPair();
      }
  </code></pre>
  
  <p>}</p>
  
  <p>And I load the private key using:</p>
  
  <pre><code>public PrivateKey LoadPrivateKey(String alias) throws Exception {
      PrivateKey key = (PrivateKey) keyStore.getKey(alias, null);
      return key;
  }
  </code></pre>
  
  <p>Anyone has an idea what is happening and can help me to understand how to fix it? Thanks!</p>