I would like to launch a Windows EC2 instance and programmatically get the admin password using Python. I know this can be done using the CLI like this, but I would prefer to decrypt locally to avoid sending my private key over the internet.
aws ec2 get-password-data --instance-id i-0d4d8273cadcae0a0 --priv-launch-key .ssh/elliott2.pem
After reading Cryptodome docs, I tried like this:
import boto3
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP
ec2 = boto3.resource('ec2', 'us-west-2')
i = ec2.Instance('i-028dee2acb533fc59')
encrypted_str = i.password_data()['PasswordData']
with open('mykey.pem') as fp:
key = RSA.importKey(fp.read())
cipher = PKCS1_OAEP.new(key)
print(cipher.decrypt(enc_str))
This fails with error:
Traceback (most recent call last):
File "test.py", line 14, in <module>
print(cipher.decrypt(encrypted_str))
File "/Users/elliott/Library/Python/3.8/lib/python/site-packages/Crypto/Cipher/PKCS1_OAEP.py", line 167, in decrypt
raise ValueError("Ciphertext with incorrect length.")
ValueError: Ciphertext with incorrect length.
I think cipherkey must be exactly 256 Bytes. But the password data is longer than this, so I'm not sure what to do.