BouncyCastle error: can't recognise key type in ECDSA based signer
I have been doing some simple testing with BouncyCastle's crypto library and RSA's crypto library. What I am doing is generating a private/public key pair like so:
KeyPairGenerator kpg = KeyPairGenerator.getInstance("EC", "JsafeJCE");
kpg.initialize(new ECGenParameterSpec("secp384r1"));
KeyPair kp = kpg.genKeyPair();
PrivateKey priv = kp.getPrivate();
PublicKey pub = kp.getPublic();
Then I generate the signature like so
Signature sig = Signature.getInstance("SHA384/ECDSA","BC");
and I try to sign the private key:
sig.initSign(priv);
All of this gets me the error:
java.security.InvalidKeyException: can't recognise key type in ECDSA based sign开发者_如何学JAVAer
When I BC and JsafeJCE, I get no error and everything is fine. Works also if both providers are BC. So why is it I can't sign the JsafeJCE generated key with the BC lib?
Bouncycastle requires that the private key used for its signing implementation must be one of its own. I don't know why you'd choose different providers for the various pieces in any event.
I solved the same issue by following the below steps:
1) Create static provider:
private static BouncyCastleProvider bouncyCastleProvider;
public static final BouncyCastleProvider BOUNCY_CASTLE_PROVIDER = new BouncyCastleProvider();
static {
bouncyCastleProvider = BOUNCY_CASTLE_PROVIDER;
}
2) Generate keyPair:
KeyPairGenerator g = KeyPairGenerator.getInstance("ECDSA", bouncyCastleProvider);
g.initialize(ecSpec, random);
KeyPair keyPair = g.generateKeyPair();
3) If you want to sign something using key:
Signature signature = Signature.getInstance("SHA256withECDSA", bouncyCastleProvider);
signature.initSign(privateKey);
signature.update(signedData);
signature.sign();
It worked for me, and will hopefully work for you as well.
精彩评论