Issue
How to get resource from folder resources/key?
I did like this:
String Key = new String(Files.readAllBytes(Paths.get(ClassLoader.getSystemResource("key/private.pem").toURI())));
And it doesn't work when I build the project into a jar. So I'm looking for another way to do this. Can you please tell me how to get the resource?
private PublicKey getPublicKey() throws NoSuchAlgorithmException, InvalidKeySpecException, IOException {
String key = getPublicKeyContent().replaceAll("\\n", "")
.replace("-----BEGIN PUBLIC KEY-----", "").replace("-----END PUBLIC KEY-----", "");
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(Base64.getDecoder().decode(key));
KeyFactory kf = KeyFactory.getInstance("RSA");
return kf.generatePublic(keySpec);
}
private PrivateKey getPrivateKey() throws NoSuchAlgorithmException, InvalidKeySpecException {
String key = getPrivateKeyContent().replaceAll("\\n", "")
.replace("-----BEGIN PRIVATE KEY-----", "").replace("-----END PRIVATE KEY-----", "");
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(Base64.getDecoder().decode(key));
KeyFactory kf = KeyFactory.getInstance("RSA");
return kf.generatePrivate(keySpec);
}
Solution
Try this util method which uses spring framework core and util packages.
public static String getResourceFileContent(String resourcePath) {
Objects.requireNonNull(resourcePath);
ClassPathResource resource = new ClassPathResource(resourcePath);
try {
byte[] bytes = FileCopyUtils.copyToByteArray(resource.getInputStream());
return new String(bytes);
} catch(IOException ex) {
log.error("Failed to parse resource file : " + resourcePath, ex);
}
}
Answered By - Kashinath
Answer Checked By - Cary Denson (JavaFixing Admin)