0

I have ECDSA private key string in base64 (i check this string with regexp from this https://stackoverflow.com/a/8571649/7661555 answer).

And i try to generate PrivateKey instance from this string. I include SpongyCastle in my project, and try to generate it with this code:

        PKCS8EncodedKeySpec privKeySpec = new PKCS8EncodedKeySpec(encKey);

        KeyFactory keyFactory = KeyFactory.getInstance("ECDSA", "SC");

        PrivateKey priv = keyFactory.generatePrivate(privKeySpec);

But when i run this code, i get next Exception:

W/System.err: java.security.spec.InvalidKeySpecException: encoded key spec not recognised

Can you tell me what i do wrong ?

P.S. After generating PrivateKey, i want sign another string with it. For this purpose i find next code:

        Signature sig = Signature.getInstance("SHA256withECDSA");
        sig.initSign(priv);
        sig.update(token.getBytes());

Is this right way? Or something in this can lead to another exception ?

Community
  • 1
  • 1

1 Answers1

0

The regex which you have mentioned in your question, just checks whether a string is base64 encoded or not.

Can you share, how you are generating the base64 string from the EC private key?

    private String getBase64Value(PrivateKey privateKey) {
    return Base64.encodeToString(privateKey.getEncoded(), Base64.NO_WRAP);
}

private PrivateKey reconstructPrivateKey(String base64Value) throws InvalidKeySpecException, NoSuchAlgorithmException {
    KeyFactory kf = KeyFactory.getInstance("EC");
    byte[] bytes = Base64.decode(base64Value, Base64.NO_WRAP);
    return kf.generatePrivate(new PKCS8EncodedKeySpec(bytes));
}
ua741
  • 1,446
  • 15
  • 28