Retrieve private key from Azure Key Vault in Spring Boot app

2k Views Asked by At

I have a .pfx certificate in Azure Key Vault. I need to retrieve the private key from this to decrypt a string value in my Spring Boot application.

I have used the azure-spring-boot-starter-keyvault-certificates library to load the certificate to java key store, this seems to be working ok.

What I don't understand is how to retrieve the private key part. Any clues to what I am doing wrong?

    KeyStore azureKeyVaultKeyStore = KeyStore.getInstance("AzureKeyVault");
    KeyVaultLoadStoreParameter parameter = new KeyVaultLoadStoreParameter(
            System.getProperty("azure.keyvault.uri"),
            System.getProperty("azure.keyvault.tenant-id"),
            System.getProperty("azure.keyvault.client-id"),
            System.getProperty("azure.keyvault.client-secret"));
    azureKeyVaultKeyStore.load(parameter);

    // returns null!
    PrivateKey privateKey = (PrivateKey) azureKeyVaultKeyStore.getKey(environment.getProperty("azure.keyvault.alias"), "".toCharArray()); 

    // decrypt value
    Cipher c = Cipher.getInstance(privateKey.getAlgorithm());
    c.init(Cipher.DECRYPT_MODE, privateKey);
    c.update(DatatypeConverter.parseBase64Binary(cryptedMsg));
    String decryptedMessage = new String(c.doFinal());

Testing with the same certificate on my machine works doing like this:

        KeyStore keyStore = KeyStore.getInstance("pkcs12");
        keyStore.load(new FileInputStream(filename), password.toCharArray());

        PrivateKey privateKey = (PrivateKey) keyStore.getKey(alias, password.toCharArray());
2

There are 2 best solutions below

2
On

The private key can be retrieved using the GetSecret() method, otherwise you only get the public part.

See this article for details (Even tough its for .NET, I hope you can figure out how to do it in Java) or see the Java samples here

0
On

Usually, KMS disallow keys leaving the management boundaries. That means, getKey yields the public portion of a key. Keys marked with exportable can only be exported fully. If I'm correct, this can only be set during the creation time. For more information, https://learn.microsoft.com/en-us/rest/api/keyvault/keys/create-key/create-key?view=rest-keyvault-keys-7.4&tabs=HTTP#keyattributes