I've noticed something weird when generating key pairs from AWS Lambda - every time I run the code it generates identical keys. I am aware that Lambda containers are frozen after each invocation and this is probably why the underlying JCE classes are loaded from memory and keep their initial state. The code in question is relatively simple:
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA", "BC");
keyPairGen.initialize(2048);
KeyPair keyPair = keyPairGen.generateKeyPair();
RSAPublicKey rsaPublicKey = (RSAPublicKey) keyPair.getPublic();
RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) keyPair.getPrivate();
return new RSAKey.Builder(rsaPublicKey).privateKey(rsaPrivateKey)
.keyID(kid).keyUse(KeyUse.SIGNATURE)
I tried both the vanilla provider and Bouncy Castle but the result is the same - identical key pairs when Lambda is "warm". Once the container is terminated and restarted from a "cold" state, I get a new and different set of keys.
I'm also using AWS Cognito and the service is served through both API Gateway and CloudFront.
Any ideas how to "refresh" the underlying JCE classes?