Search code examples
javahyperledger-fabricbouncycastleecdsa

Get java.security.PrivateKey from private key file generated by hyperledger ca


Using hyperledger-fabric-ca tool I got private key like following

-----BEGIN PRIVATE KEY-----
MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgrECQDuXL87QJKYDO
O/Z1TT+vzVPqF3106wT75dJF5OqhRANCAASsFuneE46/9JmUJCiQ14zWDKcFn6TL
kYl6mirTXefU7yYglu5hmehU0pD/PKKLkoTLNbPLn5RMdUe8aum3N1sZ
-----END PRIVATE KEY-----

By default that software uses ecdsa-with-SHA256 (prime256v1) Signature Algorithm

In my java application i need to have instance of java.security.PrivateKey that based on private key above.

I have tried following code

 public static void main(String[] args) throws Exception {

        String privateKeyString = "-----BEGIN PRIVATE KEY-----\n" +
                "MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgrECQDuXL87QJKYDO\n" +
                "O/Z1TT+vzVPqF3106wT75dJF5OqhRANCAASsFuneE46/9JmUJCiQ14zWDKcFn6TL\n" +
                "kYl6mirTXefU7yYglu5hmehU0pD/PKKLkoTLNbPLn5RMdUe8aum3N1sZ\n" +
                "-----END PRIVATE KEY-----\n";


        String privateKeyContent = privateKeyString.replaceAll("\\n|-----BEGIN PRIVATE KEY-----|-----END PRIVATE KEY-----", "");
        PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(privateKeyContent.getBytes());
        KeyFactory factory = KeyFactory.getInstance("EC");
        PrivateKey privateKey = factory.generatePrivate(spec);
    }

but I am getting

Exception in thread "main" java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException: invalid key format
    at sun.security.ec.ECKeyFactory.engineGeneratePrivate(ECKeyFactory.java:169)
    at java.security.KeyFactory.generatePrivate(KeyFactory.java:372)
    at QueryApp.main(QueryApp.java:36)
Caused by: java.security.InvalidKeyException: invalid key format
    at sun.security.pkcs.PKCS8Key.decode(PKCS8Key.java:330)
    at sun.security.pkcs.PKCS8Key.decode(PKCS8Key.java:356)
    at sun.security.ec.ECPrivateKeyImpl.<init>(ECPrivateKeyImpl.java:73)
    at sun.security.ec.ECKeyFactory.implGeneratePrivate(ECKeyFactory.java:237)
    at sun.security.ec.ECKeyFactory.engineGeneratePrivate(ECKeyFactory.java:165)
    ... 2 more

Solution

  • You must base64-decode the contents, e.g.

    String privateKeyContent = privateKeyString.replaceAll("\\n|-----BEGIN PRIVATE KEY-----|-----END PRIVATE KEY-----", "");
    PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(Base64.getDecoder().decode(privateKeyContent));
    KeyFactory factory = KeyFactory.getInstance("EC");