Sahit
Sahit

Reputation: 520

How to fetch certificate stored in Azure KeyVault using Java

I had stored a .pfx file in Azure Keyvault. I have the values of "Certificate Identifier", "Key Identifier" , "Secret Identifier". I want to use .pfx file in a java program. How could I fetch the file from Keyvault?

I had searched internet and found that we can get certificate using Keyvault

KeyVaultClient keyVaultClient = new KeyVaultClient(credentials);
keyVaultClient.getCertificate(this.keyVaultUri, certificateName, '');

1) How to pass credentials to KeyVaultClient?

2) Do I have to use Azure login credentials in the KeyVaultClient?

KeyStore keyStore = KeyStore.getInstance("JKS");

//I have to get this .pfx file from Azure Keyvault

keyStore.load(new FileInputStream(".pfx file"), 
keyPassphrase.toCharArray());

SSLContext sslContext = SSLContexts.custom()
    .loadKeyMaterial(keyStore, keyPassphrase.toCharArray())
    .build();

HttpClient httpClient = 
HttpClients.custom().setSSLContext(sslContext).build();

Upvotes: 4

Views: 7208

Answers (3)

shwkumar
shwkumar

Reputation: 68

For future reference, if your Java application is running within App Service or any other Azure resource which has a Managed Identity, there is an easier way to do this:

First enable the system-assigned managed identity or user-assigned managed identity of the specified resource. Using the object ID you obtained when enabling the managed identity, specify it in the access policy of the key vault & assign it the necessary permissions. In this case, you would assign the managed identity an access policy of 'get' for certificates. Once all this is configured, you need to specify the keyvault url in your application.properties.

azure.keyvault.uri= # url of the keyvault

Then in your Java class where you want to fetch the certificate do the following:

  1. Import the following packages:
     import com.microsoft.azure.AzureEnvironment;
     import com.microsoft.azure.credentials.AppServiceMSICredentials;
     import com.microsoft.azure.credentials.AzureTokenCredentials;
     import com.microsoft.azure.keyvault.models.CertificateBundle;
  1. To pass credentials, you need to add the following lines:

    AzureTokenCredentials credentials = new AppServiceMSICredentials(AzureEnvironment.AZURE);
    KeyVaultClient keyVaultClient = new KeyVaultClient(credentials);
    CertificateBundle certificateBundle = KeyVaultClient.getCertificate(certificateIdentifier);

The first line here will automatically allow App Service to authenticate with Azure Keyvault, if you followed the previous steps.

Using that, when you call KeyVaultClient.getCertificate, it will return you a CertificateBundle in which you can find the certificate contents.

With this approach, you don't have to specify credentials anywhere.

Upvotes: 2

Codev
Codev

Reputation: 1160

I could not find any information on how to fetch certificates from a key vault in java. My workaround was: I converted my pfx to base64 (e.g. using openssl)

$ openssl base64 -in <infile> -out <outfile>

From the resulting string in I removed all line breaks. This cleaned base64 string I put as a normal string secret into the vault. I give it the key "cert-base64"

I recieve the secret with java spring:

@Value("${cert.base64}") private String CERT_BASE64;

In order to use the file, I decode base64 to byte[]:

final byte[] keyStoreData = Base64.getDecoder().decode(CERT_BASE64);

And then I load it into keystore:

KeyStore keyStore = KeyStore.getInstance("JKS");
keyStore.load(new ByteArrayInputStream(keyStoreData), "pw".toCharArray());

Actually I used a .jks file instead of .pfx. But this process of storing secret files as string is absolutely generic. (Except some size limit I guess. I tested up to 3KB which worked.)

Upvotes: 0

George Chen
George Chen

Reputation: 14334

I believe you have already known the Microsoft Azure Key Vault SDK for Java, in this github page there are many samples. There is sample is Java Azure Key Vault Deploy Certificates to Vault and Certificate based Authenication.

This Sample describes how to create a vault, and put keys and secrets in the vault. It then shows how to inject into a VM at deployment a pfx file from the vault using a template. The sample also shows signing and verification of signature with both Java Security and Azure Key Vault REST used for verfiying the signature. The code calls the vault for the keys and secrets and writes these values to console. This sample also shows how to authenicate using a pfx file.

Update: if you don't have an app in azure, you could authenticate with service principal and a self-signed certificate.

You need create an Azure service principal, if you wish to authenticate with the certificate authenticator the certificate should be saved locally.

**Note:**For ADAL authentication, AZURE_CLIENT_ID and AZURE_CLIENT_SECRET also must be set.

And, yes the pathPfx is the Certificate Identifier url, the JavaKeyVaultAuthenticator has param define about the path, pfxPassword and clineId.

Upvotes: 0

Related Questions