Search code examples
javaencryptionecdsa

ECDSA byte array into Private Key Error


I want to save my private key in json file ( hex format ) then read it as PrivateKey.

Here Keys generate function

public void generateKeyPair() {
    try {
        Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
        KeyPairGenerator keyGen = KeyPairGenerator.getInstance("ECDSA", "BC");
        SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
        ECGenParameterSpec ecSpec = new ECGenParameterSpec("secp256k1");
        keyGen.initialize(ecSpec,random);
        KeyPair keyPair = keyGen.generateKeyPair();
        privateKey = keyPair.getPrivate();
        publicKey = keyPair.getPublic();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

This is how i save it into json file

        a.generateKeyPair();
        byte[] enc_key = a.privateKey.getEncoded();

        StringBuilder key_builder = new StringBuilder();
        for(byte b : enc_key){
            key_builder.append(String.format( "%02X",b));
        }

        String serialized_key = key_builder.toString();
        account.privateKey=serialized_key;
        try (Writer writer = new FileWriter("Output.json")) {
            Gson gson = new GsonBuilder().create();
            gson.toJson(account, writer);
        } catch (IOException e) {
            e.printStackTrace();
        }

And read it from file

        Gson gson = new GsonBuilder().create();
        try (Reader read1 = new FileReader("Output.json")) {
            account=gson.fromJson(read1,account.getClass());
            byte[] encoded_key=account.privateKey.getBytes();
            a.privateKey = getPrivateKey(encoded_key);

    public static PrivateKey getPrivateKey(byte[] privkey) throws NoSuchAlgorithmException, InvalidKeySpecException {
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
    EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(privkey);
    KeyFactory kf = null;
    try {
        kf = KeyFactory.getInstance("ECDSA", "BC");
    } catch (NoSuchProviderException e) {
        e.printStackTrace();
    }
    PrivateKey privateKey = kf.generatePrivate(privateKeySpec);
    return privateKey;
}

Function fail and i get error

java.security.spec.InvalidKeySpecException: encoded key spec not recognized: failed to construct sequence from byte[]: unknown tag 19 encountered

Solution

  • You are forgetting to hex decode the private key. Just performing getBytes won't do that.

    The encoded byte starts with a SEQUENCE, tag 0x30. This in hex will of course be "30" or, in ASCII: 0x33, 0x30: these are the two first bytes returned by getBytes. Now the decoder looks at the first byte with bit value 0b001_10011. The last 5 bits encode the tag value, which is 16 + 2 + 1 = 19. Hence the specific error.