Example usage for java.security KeyPair KeyPair

List of usage examples for java.security KeyPair KeyPair

Introduction

In this page you can find the example usage for java.security KeyPair KeyPair.

Prototype

public KeyPair(PublicKey publicKey, PrivateKey privateKey) 

Source Link

Document

Constructs a key pair from the given public key and private key.

Usage

From source file:net.arccotangent.pacchat.filesystem.KeyManager.java

public static KeyPair loadRSAKeys() {
    try {//from w w w. j a v  a 2s  . c o  m
        km_log.i("Loading RSA key pair from disk.");
        byte[] privEncoded = Files.readAllBytes(privkeyFile.toPath());
        byte[] pubEncoded = Files.readAllBytes(pubkeyFile.toPath());

        X509EncodedKeySpec pubSpec = new X509EncodedKeySpec(Base64.decodeBase64(pubEncoded));
        PKCS8EncodedKeySpec privSpec = new PKCS8EncodedKeySpec(Base64.decodeBase64(privEncoded));

        KeyFactory keyFactory = KeyFactory.getInstance("RSA");

        PublicKey pubkey = keyFactory.generatePublic(pubSpec);
        PrivateKey privkey = keyFactory.generatePrivate(privSpec);

        return new KeyPair(pubkey, privkey);
    } catch (IOException | NoSuchAlgorithmException | InvalidKeySpecException e) {
        km_log.e("Error while loading keypair!");
        e.printStackTrace();
    }
    return null;
}

From source file:edu.umass.cs.msocket.gns.GnsIntegration.java

/**
 * Register any globally unique Human Readable Name in the GNS and create a
 * field with the same name in that GUID to store the InetSocketAddress
 * information./*from  ww  w.j  a  v  a 2 s.  c o m*/
 * 
 * @param name Human readable name of the service (needs to be unique
 *          GNS-wide)
 * @param saddr The IP address to store for this service
 * @param credentials The GNS credentials to use, usually the account GUID and
 *          default GNS (if null default GNS credentials are used)
 * @throws IOException
 */
public static void registerWithGNS(String name, InetSocketAddress saddr, GnsCredentials credentials)
        throws IOException {
    try {
        if (credentials == null)
            credentials = GnsCredentials.getDefaultCredentials();

        log.trace("Looking for entity " + name + " GUID and certificates...");

        GuidEntry myGuid = KeyPairUtils
                .getGuidEntryFromPreferences(credentials.getGnsHost() + ":" + credentials.getGnsPort(), name);
        final UniversalGnsClient gnsClient = credentials.getGnsClient();

        /*
         * Take a lock on the GNS connection object to prevent concurrent queries to
         * the GNS on the same connection as the library is not thread-safe from
         * that standpoint.
         */
        synchronized (gnsClient) {
            if (myGuid == null) {
                System.out.println("No keys found for service " + name + ". Generating new GUID and keys");
                // Create a new GUID
                myGuid = gnsClient.guidCreate(credentials.getGuidEntry(), name);

                // save keys in the preference
                System.out.println("saving keys to local");
                KeyPairUtils.saveKeyPairToPreferences(KeyPairUtils.getDefaultGnsFromPreferences(),
                        myGuid.getEntityName(), myGuid.getGuid(),
                        new KeyPair(myGuid.getPublicKey(), myGuid.getPrivateKey()));

                // storing alias in gns record, need it to find it when we have GUID
                // from group members
                gnsClient.fieldCreate(myGuid.getGuid(), GnsConstants.ALIAS_FIELD, new JSONArray().put(name),
                        myGuid);
            }

            // Put the IP address in the GNS
            String ipPort = saddr.getAddress().getHostAddress() + ":" + saddr.getPort();
            log.trace("Updating " + GnsConstants.SERVER_REG_ADDR + " GNSValue " + ipPort);
            gnsClient.fieldReplaceOrCreate(myGuid.getGuid(), GnsConstants.SERVER_REG_ADDR,
                    new JSONArray().put(ipPort), myGuid);
        }
    } catch (Exception ex) {
        throw new IOException(ex);
    }
}

From source file:org.apache.karaf.shell.ssh.keygenerator.OpenSSHGeneratorKeyFileProviderTest.java

@Test
public void convertSimpleKey() throws Exception {
    File temp = File.createTempFile(this.getClass().getCanonicalName(), ".pem");
    temp.deleteOnExit();//from  w  w  w . j  a v  a 2s  .com

    SimpleGeneratorHostKeyProvider simpleGenerator = new SimpleGeneratorHostKeyProvider(temp);
    simpleGenerator.setKeySize(2048);
    simpleGenerator.setAlgorithm("DSA");
    List<KeyPair> keys = simpleGenerator.loadKeys();
    KeyPair simpleKeyPair = keys.stream().findFirst().get();

    Assert.assertEquals("DSA", simpleKeyPair.getPrivate().getAlgorithm());

    OpenSSHKeyPairProvider provider = new OpenSSHKeyPairProvider(temp, "DSA", 2048);
    KeyPair convertedKeyPair = provider.loadKeys().iterator().next();
    Assert.assertEquals("DSA", convertedKeyPair.getPrivate().getAlgorithm());

    Assert.assertArrayEquals(simpleKeyPair.getPrivate().getEncoded(),
            convertedKeyPair.getPrivate().getEncoded());
    Assert.assertArrayEquals(simpleKeyPair.getPublic().getEncoded(), convertedKeyPair.getPublic().getEncoded());

    //also test that the original file has been replaced
    PKCS8Key pkcs8 = new PKCS8Key(Files.newInputStream(temp.toPath()), null);
    KeyPair keyPair = new KeyPair(pkcs8.getPublicKey(), pkcs8.getPrivateKey());
    Assert.assertArrayEquals(simpleKeyPair.getPrivate().getEncoded(), keyPair.getPrivate().getEncoded());

}

From source file:org.asimba.wa.integrationtest.util.SignatureHelper.java

public KeyPair getKeyPairFromKeystore() {
    try {//from   w ww . j  a  va2s .  co  m
        PasswordProtection passwordProtected = new PasswordProtection(_keyPassword.toCharArray());
        Entry keyEntry = _keyStore.getEntry(_keyAlias, passwordProtected);

        if (!(keyEntry instanceof PrivateKeyEntry)) {
            // Invalid key entry
            return null;
        }
        PrivateKeyEntry pkEntry = (PrivateKeyEntry) keyEntry;
        return new KeyPair(pkEntry.getCertificate().getPublicKey(), pkEntry.getPrivateKey());

    } catch (KeyStoreException | NoSuchAlgorithmException | UnrecoverableEntryException e) {
        _logger.error("Exception when getting keypair: {}", e.getMessage(), e);
        return null;
    }
}

From source file:org.mitre.jwt.encryption.impl.KeyStore.java

/**
 * Returns a KeyPair for the alias given the password
 * //  w w  w.j  a  v a2  s .c om
 * @param alias
 *            the alias name
 * @param password
 *            the password for recovering the key pair
 * @return the key pair
 * @throws GeneralSecurityException
 */
public KeyPair getKeyPairForAlias(String alias, String password) throws GeneralSecurityException {

    Key key = keystore.getKey(alias, password.toCharArray());

    if (key instanceof PrivateKey) {

        // Get certificate of public key
        java.security.cert.Certificate cert = keystore.getCertificate(alias);

        // Get public key
        PublicKey publicKey = cert.getPublicKey();

        return new KeyPair(publicKey, (PrivateKey) key);
    }

    return null;
}

From source file:com.vexsoftware.votifier.util.rsa.RSAIO.java

/**
 * Loads an RSA key pair from a directory. The directory must have the files
 * "public.key" and "private.key"./*w ww  .ja va2 s .  c  om*/
 * 
 * @param directory
 *            The directory to load from
 * @return The key pair
 * @throws Exception
 *             If an error occurs
 */
public static KeyPair load(File directory) throws Exception {
    // Read the public key file.
    File publicKeyFile = new File(directory + "/public.key");
    FileInputStream in = null;
    byte[] encodedPublicKey;
    try {
        in = new FileInputStream(directory + "/public.key");
        encodedPublicKey = new byte[(int) publicKeyFile.length()];
        in.read(encodedPublicKey);
        encodedPublicKey = DatatypeConverter.parseBase64Binary(new String(encodedPublicKey));
    } finally {
        try {
            in.close();
        } catch (Exception exception) {
            // ignore
        }
    }

    // Read the private key file.
    File privateKeyFile = new File(directory + "/private.key");
    byte[] encodedPrivateKey;
    try {
        in = new FileInputStream(directory + "/private.key");
        encodedPrivateKey = new byte[(int) privateKeyFile.length()];
        in.read(encodedPrivateKey);
        encodedPrivateKey = DatatypeConverter.parseBase64Binary(new String(encodedPrivateKey));
    } finally {
        try {
            in.close();
        } catch (Exception exception) {
            // ignore
        }
    }

    // Instantiate and return the key pair.
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(encodedPublicKey);
    PublicKey publicKey = keyFactory.generatePublic(publicKeySpec);
    PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(encodedPrivateKey);
    PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec);
    return new KeyPair(publicKey, privateKey);
}

From source file:net.firejack.platform.web.security.x509.KeyUtils.java

public static KeyPair load(File keyStoreFile) {
    if (keyStoreFile != null) {
        try {// w ww .  j a  v a2s.  c  o  m
            KeyStore ks = KeyStore.getInstance("JKS", "SUN");
            if (keyStoreFile.exists()) {
                FileInputStream stream = new FileInputStream(keyStoreFile);
                ks.load(stream, SECRET);
                IOUtils.closeQuietly(stream);

                PrivateKey privateKey = (PrivateKey) ks.getKey(ALIAS, SECRET);
                if (privateKey == null)
                    return null;
                PublicKey publicKey = ks.getCertificate(ALIAS).getPublicKey();
                return new KeyPair(publicKey, privateKey);
            }
        } catch (Throwable th) {
            logger.error("Failed to initialize key store");
            throw new OpenFlameRuntimeException(th.getMessage(), th);
        }
    } else {
        throw new IllegalArgumentException("Key Store file should not be null.");
    }
    return null;
}

From source file:com.cws.esolutions.security.dao.keymgmt.impl.FileKeyManager.java

/**
 * @see com.cws.esolutions.security.dao.keymgmt.interfaces.KeyManager#returnKeys(java.lang.String)
 *///w  ww  .j a  v  a 2 s  . c om
public synchronized KeyPair returnKeys(final String guid) throws KeyManagementException {
    final String methodName = FileKeyManager.CNAME
            + "#returnKeys(final String guid) throws KeyManagementException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("Value: {}", guid);
    }

    KeyPair keyPair = null;
    InputStream pubStream = null;
    InputStream privStream = null;

    final File keyDirectory = FileUtils.getFile(keyConfig.getKeyDirectory() + "/" + guid);

    try {
        if (!(keyDirectory.exists())) {
            throw new KeyManagementException("Configured key directory does not exist and unable to create it");
        }

        File publicFile = FileUtils
                .getFile(keyDirectory + "/" + guid + SecurityServiceConstants.PUBLICKEY_FILE_EXT);
        File privateFile = FileUtils
                .getFile(keyDirectory + "/" + guid + SecurityServiceConstants.PRIVATEKEY_FILE_EXT);

        if ((publicFile.exists()) && (privateFile.exists())) {
            privStream = new FileInputStream(privateFile);
            byte[] privKeyBytes = IOUtils.toByteArray(privStream);

            pubStream = new FileInputStream(publicFile);
            byte[] pubKeyBytes = IOUtils.toByteArray(pubStream);

            // files exist
            KeyFactory keyFactory = KeyFactory.getInstance(keyConfig.getKeyAlgorithm());

            // generate private key
            PKCS8EncodedKeySpec privateSpec = new PKCS8EncodedKeySpec(privKeyBytes);
            PrivateKey privKey = keyFactory.generatePrivate(privateSpec);

            // generate pubkey
            X509EncodedKeySpec publicSpec = new X509EncodedKeySpec(pubKeyBytes);
            PublicKey pubKey = keyFactory.generatePublic(publicSpec);

            // make the keypair
            keyPair = new KeyPair(pubKey, privKey);
        } else {
            // files dont exist
            throw new KeyManagementException("Failed to locate user keys");
        }
    } catch (FileNotFoundException fnfx) {
        throw new KeyManagementException(fnfx.getMessage(), fnfx);
    } catch (InvalidKeySpecException iksx) {
        throw new KeyManagementException(iksx.getMessage(), iksx);
    } catch (IOException iox) {
        throw new KeyManagementException(iox.getMessage(), iox);
    } catch (NoSuchAlgorithmException nsax) {
        throw new KeyManagementException(nsax.getMessage(), nsax);
    } finally {
        if (privStream != null) {
            IOUtils.closeQuietly(privStream);
        }

        if (pubStream != null) {
            IOUtils.closeQuietly(pubStream);
        }
    }

    return keyPair;
}

From source file:org.artifactory.security.crypto.CryptoHelper.java

static KeyPair createKeyPair(byte[] encodedPrivateKey, byte[] encodedPublicKey) {
    try {//from w w  w.j  a va 2s . com
        EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(encodedPrivateKey);
        KeyFactory generator = KeyFactory.getInstance(ASYM_ALGORITHM);
        PrivateKey privateKey = generator.generatePrivate(privateKeySpec);

        EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(encodedPublicKey);
        PublicKey publicKey = generator.generatePublic(publicKeySpec);
        return new KeyPair(publicKey, privateKey);
    } catch (Exception e) {
        throw new IllegalArgumentException("Failed to create KeyPair from provided encoded keys", e);
    }
}

From source file:com.emc.vipr.services.s3.S3ClientFactory.java

/**
 * Creates an EncryptionClient for testing.  Loads the public and private keys from
 * the properties file (not suitable for production).
 *
 * @return// www . java 2  s .co  m
 * @throws IOException
 */
public static AmazonS3EncryptionClient getEncryptionClient() throws IOException {
    try {
        Properties props = ViprConfig.getProperties();

        String accessKey = ViprConfig.getPropertyNotEmpty(props, ViprConfig.PROP_S3_ACCESS_KEY_ID);
        String secretKey = ViprConfig.getPropertyNotEmpty(props, ViprConfig.PROP_S3_SECRET_KEY);
        String endpoint = ViprConfig.getPropertyNotEmpty(props, ViprConfig.PROP_S3_ENDPOINT);
        String publicKey = ViprConfig.getPropertyNotEmpty(props, ViprConfig.PROP_PUBLIC_KEY);
        String privateKey = ViprConfig.getPropertyNotEmpty(props, ViprConfig.PROP_PRIVATE_KEY);

        byte[] pubKeyBytes = Base64.decodeBase64(publicKey.getBytes("US-ASCII"));
        byte[] privKeyBytes = Base64.decodeBase64(privateKey.getBytes("US-ASCII"));

        X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(pubKeyBytes);
        PKCS8EncodedKeySpec privKeySpec = new PKCS8EncodedKeySpec(privKeyBytes);

        PublicKey pubKey;
        PrivateKey privKey;
        try {
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            pubKey = keyFactory.generatePublic(pubKeySpec);
            privKey = keyFactory.generatePrivate(privKeySpec);
        } catch (GeneralSecurityException e) {
            throw new RuntimeException("Could not load key pair: " + e, e);
        }

        EncryptionMaterials keys = new EncryptionMaterials(new KeyPair(pubKey, privKey));

        BasicAWSCredentials creds = new BasicAWSCredentials(accessKey, secretKey);
        AmazonS3EncryptionClient client = new AmazonS3EncryptionClient(creds, keys);
        client.setEndpoint(endpoint);

        checkProxyConfig(client, props);

        return client;
    } catch (Exception e) {
        log.info("Could not load configuration: " + e);
        return null;
    }
}