javaresourceskeystorejava-iojsse

Working with Java.io.file, when ever I try to read a cert from it it always points to wrong path


I am trying to read a cert with file IO , every time I try accessing my cert under

testApp/src/main/resources -> cert

it always reads

X:\workspace1\testApp\target\classes\cert\test.p12

And here is my code that I am using, It always exceptions out with null pointer.

// String fileName = "config/sample.txt";
    ClassLoader classLoader = App2.class.getClassLoader();

    File file = new File(classLoader.getResource("cert/test.p12").getFile());
    FileInputStream fm = new FileInputStream(file);
    KeyStore ks = KeyStore.getInstance("PKCS12");
    try {
        ks.load(fm, "test".toCharArray());
    }
    catch(Exception e) {
        e.printStackTrace();
    }
    Key key = ks.getKey("test", "test".toCharArray());
    Certificate cert = ks.getCertificate("test");
    PublicKey publicKey = cert.getPublicKey();
    System.out.println("Public key");
    System.out.println(Base64.getEncoder().encodeToString(publicKey.getEncoded()));
    fm.close();

I want to read this cert to extract public or private key.


Solution

  • this worked for me

    File file = new File(classLoader.getResource("./cert/test.p12").getFile());