For any given alias only one of key
and cert
will be non-null. In this case evidently cert
was non-null and key was null. If there is an EC private key in your keystore you will need to work a little harder to find it. You can determine what kind of entry is at the alias by testing with isCertificateEntry
and isKeyEntry
.
EDIT 1
The error message is unfortunately confusing because it is actually coming from the bouncycastle library. The class referred to in ECDH key agreement requires ECPrivateKey
is not java.security.interfaces.ECPrivateKey
but rather org.bouncycastle.jce.interfaces.ECPrivateKey
The following short adaptation of the OPs sample code illustrates one way to overcome this.
import org.bouncycastle.jce.provider.JCEECPrivateKey;
import org.bouncycastle.jce.provider.JCEECPublicKey;
// ...
// . <original example code goes here>
// .
JCEECPrivateKey ecPrivKey = new JCEECPrivateKey((ECPrivateKey) key);
JCEECPublicKey ecPubKey = new JCEECPublicKey((ECPublicKey) cert.getPublicKey());
KeyPair kp = new KeyPair(ecPubKey, ecPrivKey);
KeyAgreement aKA = null;
aKA = KeyAgreement.getInstance("ECDH", "BC");
aKA.init(ecPrivKey);
aKA.doPhase(kp.getPublic(), true);
return aKA.generateSecret();
// ...