Windows instances on Amazon EC2 are given a random password. This post will show how to use Java to retrieve this
When starting a new Windows instance in Amazon EC2, the following steps happen on the first boot:
The EC2ConfigService starts up, and generates a random password for the Administrator account.
This password is then encrypted, using the public key part of the keypair given when starting the instance.
The encrypted data is placed into a special part of the instance metadata, where it can be retrieved through the
EC2 API GetPasswordData call.
So retrieving the Administrator password should simply be a case invoking GetPasswordData, and applying the private
key part of the keypair. As usual, there’s a couple of speed-bumps on the way - firstly, you have to present the
decryption key in the correct format, and you have to know exactly the right parameters to give to the decryption
If you ask Amazon to create a keypair for you, or you use a key generated by ssh-keygen, the key you get back is in
PEM format. The first problem is that the Java crypto framework can’t load keys in this format. Java can parse keys
encoded in DER format. Fortunately there’s not a big difference between the two - PEM is the
“ASCII-armoured” equivalent of a DER, consisting of the base-64 encoded DER binary data with an ASCII header
and footer (“-----BEGIN...“). To get at the DER data, strip off the header and footer, and base-64 decode
it. This can then be used as an input to new PKCS8EncodedKeySpec(...), from which you can ultimately get a PrivateKey
The second problem is the decryption parameters - if you get these wrong, all you get back is garbage. The data is
encrypted with RSA, with PKCS1 padding - so the magic invocation to give to JCE
Putting it all together, here is a complete example. Replace the “X”s and the private key with your own
data. This example uses the BouncyCastle crypto provider, but could be adapted to use others.