Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Lambda generate identical cryptographic keys after initialization and how to fix it?

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?

like image 751
albogdano Avatar asked Mar 13 '26 18:03

albogdano


1 Answers

To answer my own question, the culprit was actually CloudFront. Even with API caching turned off in API Gateway, CloudFront still caches the responses for some API requests.

If someone comes across the same problem, the solution is to "bust" the CloudFront cache by appending a query parameter to the request URL:

GET /api/generateKeyPair?timestamp=1507843759370
like image 83
albogdano Avatar answered Mar 16 '26 07:03

albogdano



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!