Example usage for java.security KeyPairGenerator generateKeyPair

List of usage examples for java.security KeyPairGenerator generateKeyPair

Introduction

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

Prototype

public KeyPair generateKeyPair() 

Source Link

Document

Generates a key pair.

Usage

From source file:org.psl.fidouaf.core.crypto.KeyCodec.java

public static KeyPair getRSAKeyPair()
        throws InvalidAlgorithmParameterException, NoSuchAlgorithmException, NoSuchProviderException {
    KeyPairGenerator g = KeyPairGenerator.getInstance("RSA", "BC");
    g.initialize(2048);// w  w  w  .  j  a v a2s .  c  om
    return g.generateKeyPair();
}

From source file:org.wisdom.framework.vertx.ssl.FakeKeyStore.java

private static void generateAndStoreKeyStore(KeyStore keyStore, File keyStoreFile) throws Exception {
    FileOutputStream out = null;//w w  w.  j  a  v a  2  s. co  m
    try {
        LOGGER.info("Generating HTTPS key pair in " + keyStoreFile.getAbsolutePath() + " - this may take some"
                + " time. If nothing happens, try moving the mouse/typing on the keyboard to generate some entropy.");

        // Generate the key pair
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        keyPairGenerator.initialize(1024);
        KeyPair keyPair = keyPairGenerator.generateKeyPair();

        // Generate a self signed certificate
        X509Certificate cert = createSelfSignedCertificate(keyPair);

        // Create the key store, first set the store pass
        keyStore.load(null, "".toCharArray());
        keyStore.setKeyEntry("wisdom-generated", keyPair.getPrivate(), "".toCharArray(),
                new X509Certificate[] { cert });

        keyStoreFile.getParentFile().mkdirs();
        out = new FileOutputStream(keyStoreFile);
        keyStore.store(out, "".toCharArray());

        LOGGER.info("Key Store generated in " + keyStoreFile.getAbsoluteFile());
    } finally {
        IOUtils.closeQuietly(out);
    }
}

From source file:org.wisdom.engine.ssl.FakeKeyStore.java

private static void generateAndStoreKeyStore(KeyStore keyStore, File keyStoreFile) throws Exception {
    FileOutputStream out = null;// w w w. jav  a 2 s .  c o m
    try {
        LOGGER.info("Generating HTTPS key pair in " + keyStoreFile.getAbsolutePath() + " - this may take some"
                + " time. If nothing happens, try moving the mouse/typing on the keyboard to generate some entropy.");

        // Generate the key pair
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        keyPairGenerator.initialize(1024);
        KeyPair keyPair = keyPairGenerator.generateKeyPair();

        // Generate a self signed certificate
        X509Certificate cert = createSelfSignedCertificate(keyPair);

        // Create the key store, first set the store pass
        keyStore.load(null, "".toCharArray());
        keyStore.setKeyEntry("wisdom-generated", keyPair.getPrivate(), "".toCharArray(),
                new X509Certificate[] { cert });

        out = new FileOutputStream(keyStoreFile);
        keyStore.store(out, "".toCharArray());

        LOGGER.info("Key Store generated in " + keyStoreFile.getAbsoluteFile());
    } finally {
        IOUtils.closeQuietly(out);
    }
}

From source file:org.apache.abdera.security.util.KeyHelper.java

public static KeyPair generateKeyPair(String type, int size)
        throws NoSuchAlgorithmException, NoSuchProviderException {
    KeyPairGenerator keyGen = KeyPairGenerator.getInstance(type);
    SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
    keyGen.initialize(size, random);/*from  ww  w  .jav  a2  s.  c  o  m*/
    random.setSeed(System.currentTimeMillis());
    return keyGen.generateKeyPair();
}

From source file:org.excalibur.core.util.SecurityUtils2.java

public static UserKey generateUserKey() throws Exception {
    KeyPairGenerator kpg = SecurityUtils.getKeyPairGenerator("RSA");

    kpg.initialize(1024, new SecureRandom());
    java.security.KeyPair kp = kpg.generateKeyPair();

    String priv = getKeyMaterial(kp.getPrivate());

    byte[] encoded = encode((RSAPublicKey) kp.getPublic());

    //        String pub = getKeyMaterial(kp.getPublic()).replaceAll(PUBLIC_KEY_START, "").replaceAll(PUBLIC_KEY_END, "").trim();

    return new UserKey().setPrivateKeyMaterial(priv).setPublicKeyMaterial(new String(Base64.encode(encoded)))
            .setFingerPrint(getFingerPrint((RSAPublicKey) kp.getPublic()));
}

From source file:com.vmware.identity.sts.auth.impl.UserCertAuthenticatorTest.java

@BeforeClass
public static void setUp() throws Exception {
    // create key pair and client private key, certificate
    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
    keyGen.initialize(1024, new SecureRandom());
    KeyPair userKeyPair = keyGen.generateKeyPair();
    userPrivateKey = (RSAPrivateKey) userKeyPair.getPrivate();
    x509Certificate = generateCertificate(userKeyPair, "User");
}

From source file:br.com.ufjf.labredes.crypto.Cryptography.java

public static void geraChave() {
    try {/*from w w  w.  j  av  a 2  s.  co  m*/

        final KeyPairGenerator keyGen = KeyPairGenerator.getInstance(ALGORITHM_ASYM);
        keyGen.initialize(1024);
        final KeyPair key = keyGen.generateKeyPair();

        File chavePrivadaFileServer = new File(path, PATH_CHAVE_PRIVADA_SERVER);
        File chavePublicaFileServer = new File(path, PATH_CHAVE_PUBLICA_SERVER);

        // Cria os arquivos para armazenar a chave Privada e a chave Publica            
        if (chavePrivadaFileServer.getParentFile() != null) {
            chavePrivadaFileServer.getParentFile().mkdirs();
        }

        chavePrivadaFileServer.createNewFile();

        if (chavePublicaFileServer.getParentFile() != null) {
            chavePublicaFileServer.getParentFile().mkdirs();
        }

        chavePublicaFileServer.createNewFile();

        // Salva a Chave Pblica do servidor no arquivo
        ObjectOutputStream chavePublicaOSS = new ObjectOutputStream(
                new FileOutputStream(chavePublicaFileServer));
        chavePublicaOSS.writeObject(key.getPublic());
        chavePublicaOSS.close();

        // Salva a Chave Privada do servidor no arquivo
        ObjectOutputStream chavePrivadaOSS = new ObjectOutputStream(
                new FileOutputStream(chavePrivadaFileServer));
        chavePrivadaOSS.writeObject(key.getPrivate());
        chavePrivadaOSS.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:org.psl.fidouaf.core.crypto.KeyCodec.java

public static KeyPair getKeyPair()
        throws InvalidAlgorithmParameterException, NoSuchAlgorithmException, NoSuchProviderException {
    // ECGenParameterSpec ecGenSpec = new ECGenParameterSpec("prime192v1");
    ECGenParameterSpec ecGenSpec = new ECGenParameterSpec("secp256r1");
    KeyPairGenerator g = KeyPairGenerator.getInstance("ECDSA", "BC");
    g.initialize(ecGenSpec, new SecureRandom());
    return g.generateKeyPair();
}

From source file:org.apache.abdera.security.util.KeyHelper.java

public static KeyPair generateKeyPair(String type, int size, String provider)
        throws NoSuchAlgorithmException, NoSuchProviderException {
    KeyPairGenerator keyGen = KeyPairGenerator.getInstance(type, provider);
    SecureRandom random = SecureRandom.getInstance("SHA1PRNG", provider);
    keyGen.initialize(size, random);// ww w .j  a va2  s  .c  o  m
    random.setSeed(System.currentTimeMillis());
    return keyGen.generateKeyPair();
}

From source file:com.kixeye.chassis.transport.shared.JettyConnectorRegistry.java

/**
 * Register to listen to HTTPS.// ww  w. jav  a 2  s .  c om
 * 
 * @param server
 * @param address
 * @throws Exception 
 */
public static void registerHttpsConnector(Server server, InetSocketAddress address, boolean selfSigned,
        boolean mutualSsl, String keyStorePath, String keyStoreData, String keyStorePassword,
        String keyManagerPassword, String trustStorePath, String trustStoreData, String trustStorePassword,
        String[] excludedCipherSuites) throws Exception {
    // SSL Context Factory
    SslContextFactory sslContextFactory = new SslContextFactory();

    if (selfSigned) {
        char[] passwordChars = UUID.randomUUID().toString().toCharArray();

        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());

        keyStore.load(null, passwordChars);

        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        keyPairGenerator.initialize(1024);
        KeyPair keyPair = keyPairGenerator.generateKeyPair();

        X509V3CertificateGenerator v3CertGen = new X509V3CertificateGenerator();

        v3CertGen.setSerialNumber(BigInteger.valueOf(new SecureRandom().nextInt()).abs());
        v3CertGen.setIssuerDN(new X509Principal("CN=" + "kixeye.com" + ", OU=None, O=None L=None, C=None"));
        v3CertGen.setNotBefore(new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30));
        v3CertGen.setNotAfter(new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 365 * 10)));
        v3CertGen.setSubjectDN(new X509Principal("CN=" + "kixeye.com" + ", OU=None, O=None L=None, C=None"));

        v3CertGen.setPublicKey(keyPair.getPublic());
        v3CertGen.setSignatureAlgorithm("MD5WithRSAEncryption");

        X509Certificate privateKeyCertificate = v3CertGen.generateX509Certificate(keyPair.getPrivate());

        keyStore.setKeyEntry("selfSigned", keyPair.getPrivate(), passwordChars,
                new java.security.cert.Certificate[] { privateKeyCertificate });

        ByteArrayOutputStream keyStoreBaos = new ByteArrayOutputStream();
        keyStore.store(keyStoreBaos, passwordChars);

        keyStoreData = new String(Hex.encode(keyStoreBaos.toByteArray()), Charsets.UTF_8);
        keyStorePassword = new String(passwordChars);
        keyManagerPassword = keyStorePassword;

        sslContextFactory.setTrustAll(true);
    }

    KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());

    if (StringUtils.isNotBlank(keyStoreData)) {
        keyStore.load(new ByteArrayInputStream(Hex.decode(keyStoreData)), keyStorePassword.toCharArray());
    } else if (StringUtils.isNotBlank(keyStorePath)) {
        try (InputStream inputStream = new DefaultResourceLoader().getResource(keyStorePath).getInputStream()) {
            keyStore.load(inputStream, keyStorePassword.toCharArray());
        }
    }

    sslContextFactory.setKeyStore(keyStore);
    sslContextFactory.setKeyStorePassword(keyStorePassword);
    if (StringUtils.isBlank(keyManagerPassword)) {
        keyManagerPassword = keyStorePassword;
    }
    sslContextFactory.setKeyManagerPassword(keyManagerPassword);
    KeyStore trustStore = null;
    if (StringUtils.isNotBlank(trustStoreData)) {
        trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(new ByteArrayInputStream(Hex.decode(trustStoreData)), trustStorePassword.toCharArray());
    } else if (StringUtils.isNotBlank(trustStorePath)) {
        trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        try (InputStream inputStream = new DefaultResourceLoader().getResource(trustStorePath)
                .getInputStream()) {
            trustStore.load(inputStream, trustStorePassword.toCharArray());
        }
    }
    if (trustStore != null) {
        sslContextFactory.setTrustStore(trustStore);
        sslContextFactory.setTrustStorePassword(trustStorePassword);
    }
    sslContextFactory.setNeedClientAuth(mutualSsl);
    sslContextFactory.setExcludeCipherSuites(excludedCipherSuites);

    // SSL Connector
    ServerConnector connector = new ServerConnector(server,
            new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.toString()),
            new HttpConnectionFactory());
    connector.setHost(address.getHostName());
    connector.setPort(address.getPort());

    server.addConnector(connector);
}