Skip to content

Instantly share code, notes, and snippets.

@krnbr
Created July 16, 2020 05:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save krnbr/5c9aecd9e1b3a2f949da17dc646978c8 to your computer and use it in GitHub Desktop.
Save krnbr/5c9aecd9e1b3a2f949da17dc646978c8 to your computer and use it in GitHub Desktop.
public class JKStoBase64String {
private static final int BUFFER_SIZE = 65535;
public static byte[] convertFileToByteArray(String certificateFilePath) throws Exception {
if (certificateFilePath == null || certificateFilePath.isEmpty()) {
throw new Exception("file path should not be null or empty");
}
File file = new File(certificateFilePath);
if (!file.exists()) {
throw new Exception("file not exist : " + file.getAbsolutePath());
}
if (file.isDirectory()) {
throw new Exception("File shouldn't be a directory : " + file.getAbsolutePath());
}
try (InputStream inputStream = new FileInputStream(file)) {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[BUFFER_SIZE];
int numberOfReadBytes;
while ((numberOfReadBytes = inputStream.read(buffer)) > 0) {
byteArrayOutputStream.write(buffer, 0, numberOfReadBytes);
}
byte[] certificateInBytes = byteArrayOutputStream.toByteArray();
Encoder encoder = Base64.getEncoder();
byte[] encodedBytes = encoder.encode(certificateInBytes);
return encodedBytes;
}
}
/**
* Convert the certificate into base64 encoded string.
*
* @param certificateFilePath
* @return
* @throws Exception
*/
public static String convertJKSToString(String certificateFilePath) throws Exception {
byte[] encodedBytes = convertFileToByteArray(certificateFilePath);
String str = new String(encodedBytes);
return str;
}
public static void main(String[] args) {
String certificateInfo;
try {
System.out.println("===============KEYSTORE================");
// for windows it would be like C:/path/to/file.jks
certificateInfo = JKStoBase64String.convertJKSToString("/path/to/client-keystore.jks");
System.out.println(certificateInfo);
System.out.println("===============TRUSTSTORE================");
// for windows it would be like C:/path/to/file.jks
certificateInfo = JKStoBase64String.convertJKSToString("/path/to/client-truststore.jks");
System.out.println(certificateInfo);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment