Created
July 16, 2020 05:44
-
-
Save krnbr/5c9aecd9e1b3a2f949da17dc646978c8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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