How to Create a Key Pair in AWS
A key pair is a set of public and private keys that you can use to securely connect to your AWS instances. The public key is a cryptographic code that can be used by anyone to encrypt data, while the private key is a secret code that can be used to decrypt the data.
To create a key pair using the AWS Management Console:
- Sign in to the AWS Management Console and open the Amazon EC2 console.
- In the navigation pane, under Network & Security, choose Key Pairs.
- Choose Create key pair.
- In the Create key pair dialog box, enter a name for your key pair and choose the file format. You can choose PEM or PPK for Windows or Linux instances.
- Choose Create key pair. The console will download the private key file to your computer. You must save this file in a secure location and never share it with anyone. You will need this file to connect to your instances later.
- You can view the public key of your key pair in the console by choosing the key pair name and then choosing View public key.
To create a key pair using the AWS CLI:
- Install and configure the AWS CLI on your computer.
- Run the following command to create a key pair and save the private key as a file named
my-key-pair.pem
:
aws ec2 create-key-pair --key-name my-key-pair --query 'KeyMaterial' --output text > my-key-pair.pem
- Change the permissions of the private key file to make it read-only for your user:
chmod 400 my-key-pair.pem
- You can view the public key of your key pair by running the following command:
aws ec2 describe-key-pairs --key-name my-key-pair --query 'KeyPairs[0].KeyFingerprint'
To create a key pair using the AWS SDKs:
Follow the documentation for your preferred programming language. For example, you can use the Java SDK to create a key pair with the following code:
Java
// Create an EC2 client
AmazonEC2 ec2 = AmazonEC2ClientBuilder.defaultClient();
// Create a key pair request
CreateKeyPairRequest request = new CreateKeyPairRequest();
request.setKeyName("my-key-pair" );
// Create a key pair
CreateKeyPairResult result = ec2.createKeyPair(request);
// Get the private key
String privateKey = result.getKeyPair().getKeyMaterial();
// Save the private key to a file
FileOutputStream out = new FileOutputStream("my-key-pair.pem" );
out.write(privateKey.getBytes());
out.close();
// Get the public key
String publicKey = result.getKeyPair().getKeyFingerprint();
I hope this is helpful! Let me know if you have any other questions.