I want to create jks file (keystore) file programmatically (some script on Java/Kotlin JVM) without using Android Studio. Is it possible?
I have a little code to create this file but how fill all the needed data to that key?
fun createJksFile() {
val keyFilePassword = "test"
val keyAlias = "test"
val keyPassword = "test"
val keyValidity = "100"
val CertificateFirstandLastName = "Test"
val CertificateOrganizationalUnit = "Test"
val CertificateOrganization = "Test"
val CertificateCityorLocality = "US"
val CertificateStateorProvince = "US"
val CertificateCountryCode = "US"
val ks = KeyStore.getInstance(KeyStore.getDefaultType())
val password = keyFilePassword.toCharArray()
ks.load(null, password)
// TODO: how to set all needed data?
FileOutputStream(File(projectDir, "_test_key.jks")).use { fos ->
ks.store(fos, password)
}
}
I decided to use this solution
val keystoreCommand = "keytool -genkey -noprompt \n" +
"-alias ${keyStore.keyAlias} \n" +
"-dname \"CN=${keyStore.certificateFirstandLastName}, OU=${keyStore.certificateOrganizationalUnit}, O=${keyStore.certificateOrganization}, L=${keyStore.certificateCityorLocality}, S=${keyStore.certificateStateorProvince}, C=${keyStore.certificateCountryCode}\" \n" +
"-keystore \"C:\\Users\\Desktop\\keystore.jks\" \n" +
"-storepass ${keyStore.keyFilePassword} \n" +
"-keypass ${keyStore.keyPassword}"
Runtime.getRuntime().exec(keystoreCommand).apply {
waitFor()
}
data class KeyStore(
val keyFilePassword: String,
val keyAlias: String,
val keyPassword: String,
val keyValidity: String,
val certificateFirstandLastName: String,
val certificateOrganizationalUnit: String,
val certificateOrganization: String,
val certificateCityorLocality: String,
val certificateStateorProvince: String,
val certificateCountryCode: String
)
Though we can do it without keytool but it's quite a lot of code to handle https://stackoverflow.com/a/45700785/7767664