Example usage for com.amazonaws.services.ec2 AmazonEC2Client importKeyPair

List of usage examples for com.amazonaws.services.ec2 AmazonEC2Client importKeyPair

Introduction

In this page you can find the example usage for com.amazonaws.services.ec2 AmazonEC2Client importKeyPair.

Prototype

@Override
public ImportKeyPairResult importKeyPair(ImportKeyPairRequest request) 

Source Link

Document

Imports the public key from an RSA key pair that you created with a third-party tool.

Usage

From source file:org.apache.airavata.core.gfac.provider.impl.EC2Provider.java

License:Apache License

private void buildKeyPair(AmazonEC2Client ec2) throws NoSuchAlgorithmException, InvalidKeySpecException,
        AmazonServiceException, AmazonClientException, IOException {

    boolean newKey = false;

    File privateKeyFile = new File(privateKeyFilePath);
    File publicKeyFile = new File(privateKeyFilePath + ".pub");

    /*/*w  ww .j a  v  a 2  s .co m*/
     * Check if Keypair already created on the server
     */
    if (!privateKeyFile.exists()) {

        // check folder and create if it does not exist
        File sshDir = new File(System.getProperty("user.home") + "/.ssh/");
        if (!sshDir.exists())
            sshDir.mkdir();

        // Generate a 1024-bit RSA key pair
        KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
        keyGen.initialize(1024);
        java.security.KeyPair keypair = keyGen.genKeyPair();

        FileOutputStream fos = null;

        // Store Public Key.
        try {
            fos = new FileOutputStream(privateKeyFilePath + ".pub");
            // TODO
            //fos.write(Base64.encodeBytes(keypair.getPublic().getEncoded(), true).getBytes());
        } catch (IOException ioe) {
            throw ioe;
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                    fos = null;
                } catch (IOException ioe) {
                    throw ioe;
                }
            }
        }

        // Store Private Key.
        try {
            fos = new FileOutputStream(privateKeyFilePath);
            StringWriter stringWriter = new StringWriter();

            /*
             * Write in PEM format (openssl support)
             */
            PEMWriter pemFormatWriter = new PEMWriter(stringWriter);
            pemFormatWriter.writeObject(keypair.getPrivate());
            pemFormatWriter.close();
            fos.write(stringWriter.toString().getBytes());
        } catch (IOException ioe) {
            throw ioe;
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                    fos = null;
                } catch (IOException ioe) {
                    throw ioe;
                }
            }
        }

        privateKeyFile.setWritable(false, false);
        privateKeyFile.setExecutable(false, false);
        privateKeyFile.setReadable(false, false);
        privateKeyFile.setReadable(true);
        privateKeyFile.setWritable(true);

        // set that this key is just created
        newKey = true;
    }

    /*
     * Read Public Key
     */
    String encodedPublicKey = null;
    BufferedReader br = null;
    try {
        br = new BufferedReader(new FileReader(publicKeyFile));
        encodedPublicKey = br.readLine();
    } catch (IOException ioe) {
        throw ioe;
    } finally {
        if (br != null) {
            try {
                br.close();
                br = null;
            } catch (IOException ioe) {
                throw ioe;
            }
        }
    }

    /*
     * Generate key pair in Amazon if necessary
     */
    try {
        /*
         * Get current key pair in Amazon
         */
        DescribeKeyPairsRequest describeKeyPairsRequest = new DescribeKeyPairsRequest();
        ec2.describeKeyPairs(describeKeyPairsRequest.withKeyNames(KEY_PAIR_NAME));

        /*
         * If key exists and new key is created, delete old key and replace
         * with new one. Else, do nothing
         */

        if (newKey) {
            DeleteKeyPairRequest deleteKeyPairRequest = new DeleteKeyPairRequest(KEY_PAIR_NAME);
            ec2.deleteKeyPair(deleteKeyPairRequest);
            ImportKeyPairRequest importKeyPairRequest = new ImportKeyPairRequest(KEY_PAIR_NAME,
                    encodedPublicKey);
            ec2.importKeyPair(importKeyPairRequest);
        }

    } catch (AmazonServiceException ase) {
        /*
         * Key doesn't exists, import new key.
         */
        if (ase.getErrorCode().equals("InvalidKeyPair.NotFound")) {
            ImportKeyPairRequest importKeyPairRequest = new ImportKeyPairRequest(KEY_PAIR_NAME,
                    encodedPublicKey);
            ec2.importKeyPair(importKeyPairRequest);
        } else {
            throw ase;
        }
    }
}

From source file:org.apache.airavata.gfac.ec2.util.EC2ProviderUtil.java

License:Apache License

/**
 * Builds a key pair with the given AmazonEC2Client and the generated key will have
 * the name keyPairName.//  w  ww.  j a va 2 s  .  c  o  m
 *
 * @param ec2 ec2client
 * @param keyPairName name for the generated key pair
 * @throws NoSuchAlgorithmException NoSuchAlgorithmException
 * @throws InvalidKeySpecException InvalidKeySpecException
 * @throws AmazonServiceException AmazonServiceException
 * @throws AmazonClientException AmazonClientException
 * @throws IOException IOException
 */
public static void buildKeyPair(AmazonEC2Client ec2, String keyPairName) throws NoSuchAlgorithmException,
        InvalidKeySpecException, AmazonServiceException, AmazonClientException, IOException {
    boolean newKey = false;

    String privateKeyFilePath = System.getProperty("user.home") + "/.ssh/" + keyPairName;
    File privateKeyFile = new File(privateKeyFilePath);
    File publicKeyFile = new File(privateKeyFilePath + ".pub");

    /* Check if Key-pair already created on the server */
    if (!privateKeyFile.exists()) {

        // check folder and create if it does not exist
        File sshDir = new File(System.getProperty("user.home") + "/.ssh/");
        if (!sshDir.exists())
            sshDir.mkdir();

        // Generate a 1024-bit RSA key pair
        KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
        keyGen.initialize(1024);
        KeyPair keypair = keyGen.genKeyPair();

        FileOutputStream fos = null;

        // Store Public Key.
        try {
            fos = new FileOutputStream(privateKeyFilePath + ".pub");
            fos.write(Base64.encodeBytes(keypair.getPublic().getEncoded(), true).getBytes());
        } catch (IOException ioe) {
            throw ioe;
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                    fos = null;
                } catch (IOException ioe) {
                    throw ioe;
                }
            }
        }

        // Store Private Key.
        try {
            fos = new FileOutputStream(privateKeyFilePath);
            StringWriter stringWriter = new StringWriter();

            /* Write in PEM format (openssl support) */
            PEMWriter pemFormatWriter = new PEMWriter(stringWriter);
            pemFormatWriter.writeObject(keypair.getPrivate());
            pemFormatWriter.close();
            fos.write(stringWriter.toString().getBytes());
        } catch (IOException ioe) {
            throw ioe;
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                    fos = null;
                } catch (IOException ioe) {
                    throw ioe;
                }
            }
        }

        privateKeyFile.setWritable(false, false);
        privateKeyFile.setExecutable(false, false);
        privateKeyFile.setReadable(false, false);
        privateKeyFile.setReadable(true);
        privateKeyFile.setWritable(true);

        // set that this key is just created
        newKey = true;
    }

    /* Read Public Key */
    String encodedPublicKey = null;
    BufferedReader br = null;
    try {
        br = new BufferedReader(new FileReader(publicKeyFile));
        encodedPublicKey = br.readLine();
    } catch (IOException ioe) {
        throw ioe;
    } finally {
        if (br != null) {
            try {
                br.close();
                br = null;
            } catch (IOException ioe) {
                throw ioe;
            }
        }
    }

    /* Generate key pair in Amazon if necessary */
    try {
        /* Get current key pair in Amazon */
        DescribeKeyPairsRequest describeKeyPairsRequest = new DescribeKeyPairsRequest();
        ec2.describeKeyPairs(describeKeyPairsRequest.withKeyNames(keyPairName));

        /* If key exists and new key is created, delete old key and replace
         * with new one. Else, do nothing */
        if (newKey) {
            DeleteKeyPairRequest deleteKeyPairRequest = new DeleteKeyPairRequest(keyPairName);
            ec2.deleteKeyPair(deleteKeyPairRequest);
            ImportKeyPairRequest importKeyPairRequest = new ImportKeyPairRequest(keyPairName, encodedPublicKey);
            ec2.importKeyPair(importKeyPairRequest);
        }

    } catch (AmazonServiceException ase) {
        /* Key doesn't exists, import new key. */
        if (ase.getErrorCode().equals("InvalidKeyPair.NotFound")) {
            ImportKeyPairRequest importKeyPairRequest = new ImportKeyPairRequest(keyPairName, encodedPublicKey);
            ec2.importKeyPair(importKeyPairRequest);
        } else {
            throw ase;
        }
    }
}