I am not sure what the exact question is but it looks like you want to write code that signs data using a private key from an HSM and have that work on AWS and Google Cloud. The steps to do that are:
- Load the provider
- Open the keystore
- Retrieve the private key
- Initialize a signing object with the private key (and update it with the data to sign)
- Sign
Step 1 can be done programmatically (via Security.addProvider, as you have written in your question) or statically in the java.security file. If you want your code to be agnostic to the cloud platform it is running on, you may want to consider doing this statically (although it is also possible to do it programmatically and keep things platform agnostic).
The rest of the steps just require pretty standard JCE code. Below is an example:
KeyStore keyStore = KeyStore.getInstance("type", "provider name");
PrivateKey privKey = (PrivateKey) keyStore.getKey("alias", null);
Signature sig = Signature.getInstance("transformation", "provider name");
sig.initSign(privKey);
sig.update(dataToSign);
byte[] signature = sig.sign();
You may want to read the provider name and keystore type from a (secured) configuration file, so those aren't hard-coded. After you get that working you'll want to look at how often you go to the keystore to retrieve key objects and possibly consider caching them because keystore retrievals can be expensive, depending on the HSM and provider library being used. That is going a bit beyond the scope of this question, or at least what I am interpreting the question to be, so I will stop there. Hope that helps.