i am trying to read private key from a file using the below code and getting an exception. is there any way to resolve it? generatePrivate() method throws invalidkeyspecexception.
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.spec.PKCS8EncodedKeySpec;
(...)
try {
Path path = Paths.get(THE_BINARY_ENCODED_FILE_PATH);
byte[] privKeyByteArray = Files.readAllBytes(path);
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privKeyByteArray);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PrivateKey privateKey= keyFactory.generatePrivate(keySpec);
} catch (Exception e) {
e.printStackTrace();
}
how to solvethis?
My key was invalid. tried with different file and it worked!