Based on Read .DER value from GCP here in stackoverflow, I share my solution:
In my case. I have worked github Actions, Dockerfile, Kubernetes Engine:
then:
Step 1. In my Dockerfile, I create directory:
RUN mkdir my_certs
RUN chmod -R 777 my_certs
This directory will create in the POD.
Step 2. In my Spring code to call SM
fileName: my_certs/my_cert.p12
projectId: your_project_id (GCP project id)
secretCertName: your_secret_cert_name
Create void method.
try (SecretManagerServiceClient client = SecretManagerServiceClient.create()) {
//save inside .p12
File file = new File(fileName);
if (file.createNewFile()) {
SecretVersionName secretVersionName = SecretVersionName.of(projectId, secretCertName, "latest");
AccessSecretVersionResponse response = client.accessSecretVersion(secretVersionName);
byte[] certValue = response.getPayload().getData().toByteArray();
try (FileOutputStream stream = new FileOutputStream(file.getPath())) {
stream.write(Base64.getMimeDecoder().decode(Base64.getEncoder().encode(certValue)));
}
}
} catch (IOException e) {
e.printStackTrace();
}
Step 3. @SpringBootApplication set store values:
@PostConstruct
void postConstruct() {
setStoreParams();
}
private void setStoreParams() {
//first create the file
call your void method ("my_certs/my_cert.p12", projectId, secretCertName);
System.setProperty("javax.net.ssl.keyStore", "my_certs/my_cert.p12");
System.setProperty("javax.net.ssl.keyStorePassword", YOUR_Keystore_Password);
System.setProperty("javax.net.ssl.keyStoreType", "PKCS12");
}
Step 4. otherwise if you use @Configuration annotation with KeyStore then:
//first create the file
call your void method ("my_certs/my_cert.p12", projectId, secretCertName);
KeyStore keyStore = KeyStore.getInstance("PKCS12");
keyStore.load(new FileInputStream("my_certs/my_cert.p12"), YOUR_Keystore_Password.toCharArray());