+
+ public static String readOrGeneratePK(File privateKeyFile) throws IOException {
+ if (privateKeyFile.exists() == false) {
+ // generate & save to file
+ try {
+ return generateTo(privateKeyFile);
+ } catch (Exception e) {
+ logger.error("Exception occurred while generating PEM string to {}", privateKeyFile, e);
+ throw new IllegalStateException("Error generating RSA key from file " + privateKeyFile);
+ }
+ } else {
+ // read from file
+ try (FileInputStream fis = new FileInputStream(privateKeyFile)) {
+ return IOUtils.toString(fis);
+ } catch (final IOException e) {
+ logger.error("Error reading RSA key from file {}", privateKeyFile, e);
+ throw new IOException("Error reading RSA key from file " + privateKeyFile, e);
+ }
+ }
+ }
+
+ /**
+ * Generate private key to a file and return its content as string.
+ *
+ * @param privateFile path where private key should be generated
+ * @return String representation of private key
+ * @throws IOException
+ * @throws NoSuchAlgorithmException
+ */
+ @VisibleForTesting