Example usage for java.security KeyPairGenerator initialize

List of usage examples for java.security KeyPairGenerator initialize

Introduction

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

Prototype

public void initialize(AlgorithmParameterSpec params) throws InvalidAlgorithmParameterException 

Source Link

Document

Initializes the key pair generator using the specified parameter set and the SecureRandom implementation of the highest-priority installed provider as the source of randomness.

Usage

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

public static void geraChave() {
    try {//from  w  w w.ja  v a  2 s  . c om

        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:com.kixeye.chassis.transport.shared.JettyConnectorRegistry.java

/**
 * Register to listen to HTTPS./*w  ww  .j ava2  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);
}

From source file:io.vertx.config.vault.utils.Certificates.java

/**
 * See https://www.cryptoworkshop.com/guide/, chapter 3
 *
 * @return A 4096-bit RSA keypair/*w ww  .j a  va2 s .co m*/
 * @throws NoSuchAlgorithmException
 */
private static KeyPair generateKeyPair() throws NoSuchAlgorithmException {
    final KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA", new BouncyCastleProvider());
    keyPairGenerator.initialize(4096);
    return keyPairGenerator.genKeyPair();
}

From source file:cloudeventbus.pki.CertificateUtils.java

public static KeyPair generateKeyPair() {
    try {//from   w w w . ja  v a  2s  .c o  m
        final KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        keyPairGenerator.initialize(KEY_SIZE);
        return keyPairGenerator.generateKeyPair();
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    }
}

From source file:it.geosolutions.sfs.web.Start.java

private static void assureSelfSignedServerCertificate(String hostname, File keyStoreFile, String password)
        throws Exception {

    KeyStore privateKS = KeyStore.getInstance("JKS");
    if (keyStoreFile.exists()) {
        FileInputStream fis = new FileInputStream(keyStoreFile);
        privateKS.load(fis, password.toCharArray());
        if (keyStoreContainsCertificate(privateKS, hostname))
            return;
    } else {//from  w  w  w  .j a  v  a 2 s .  c om
        privateKS.load(null);
    }

    // create a RSA key pair generator using 1024 bits

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

    // cerate a X509 certifacte generator
    //       X509V3CertificateGenerator v3CertGen = new X509V3CertificateGenerator();  

    // set validity to 10 years, issuer and subject are equal --> self singed certificate
    int random = new SecureRandom().nextInt();
    if (random < 0)
        random *= -1;
    //       v3CertGen.setSerialNumber(BigInteger.valueOf(random));  
    //            v3CertGen.setIssuerDN(new X509Principal("CN=" + hostname + ", 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=" + hostname + ", OU=None, O=None L=None, C=None"));
    //                        
    //            v3CertGen.setPublicKey(KPair.getPublic());  
    //            v3CertGen.setSignatureAlgorithm("MD5WithRSAEncryption");   
    //            
    //            X509Certificate PKCertificate = v3CertGen.generateX509Certificate(KPair.getPrivate());
    //            
    // store the certificate containing the public key,this file is needed
    // to import the public key in other key store. 
    File certFile = new File(keyStoreFile.getParentFile(), hostname + ".cert");
    FileOutputStream fos = new FileOutputStream(certFile.getAbsoluteFile());
    //            fos.write(PKCertificate.getEncoded());  
    fos.close();

    //            privateKS.setKeyEntry(hostname+".key", KPair.getPrivate(),  
    //                    password.toCharArray(),  
    //                    new java.security.cert.Certificate[]{PKCertificate});
    //            
    //            privateKS.setCertificateEntry(hostname+".cert",PKCertificate); 

    privateKS.store(new FileOutputStream(keyStoreFile), password.toCharArray());
}

From source file:org.mitre.jwt.signer.service.impl.KeyStoreTest.java

/**
 * Create an RSA KeyPair and insert into specified KeyStore
 * /*from  w  w w .  j  ava 2 s.  c  o m*/
 * @param location
 * @param domainName
 * @param alias
 * @param keystorePassword
 * @param aliasPassword
 * @param daysNotValidBefore
 * @param daysNotValidAfter
 * @return
 * @throws GeneralSecurityException
 * @throws IOException
 */
public static java.security.KeyStore generateKeyPair(KeyStore keystore, String keyPairAlgorithm, int keySize,
        String signatureAlgorithm, String domainName, String alias, String aliasPassword,
        int daysNotValidBefore, int daysNotValidAfter) throws GeneralSecurityException, IOException {

    java.security.KeyStore ks;

    if (keystore != null) {
        ks = keystore.getKeystore();
    } else {
        ks = java.security.KeyStore.getInstance(java.security.KeyStore.getDefaultType());
        ks.load(null, null);
    }

    KeyPairGenerator rsaKeyPairGenerator = null;

    rsaKeyPairGenerator = KeyPairGenerator.getInstance(keyPairAlgorithm);

    rsaKeyPairGenerator.initialize(keySize);
    KeyPair rsaKeyPair = rsaKeyPairGenerator.generateKeyPair();

    // BC sez X509V3CertificateGenerator is deprecated and the docs say to
    // use another, but it seemingly isn't included jar...
    X509V3CertificateGenerator v3CertGen = createCertificate(domainName, daysNotValidBefore, daysNotValidAfter);

    PrivateKey privateKey = rsaKeyPair.getPrivate();

    v3CertGen.setPublicKey(rsaKeyPair.getPublic());
    v3CertGen.setSignatureAlgorithm(signatureAlgorithm);

    // BC docs say to use another, but it seemingly isn't included...
    X509Certificate certificate = v3CertGen.generateX509Certificate(privateKey);

    // if exist, overwrite
    ks.setKeyEntry(alias, privateKey, aliasPassword.toCharArray(),
            new java.security.cert.Certificate[] { certificate });

    if (keystore != null) {
        keystore.setKeystore(ks);
    }

    return ks;
}

From source file:com.github.aynu.mosir.core.standard.util.SecurityHelper.java

/**
 * RSA???/*from  w  w w  . ja va  2 s.  c o  m*/
 * <dl>
 * <dt>?
 * <dd>RSA??????2048??????
 * </dl>
 * @return RSA?
 */
public static KeyPair createKeyPair() {
    try {
        final KeyPairGenerator generator = KeyPairGenerator.getInstance(ALGO_KEY);
        generator.initialize(2048);
        final KeyPair pair = generator.generateKeyPair();
        if (LOG.isDebugEnabled()) {
            final RSAPublicKey publicKey = (RSAPublicKey) pair.getPublic();
            final RSAPrivateKey privateKey = (RSAPrivateKey) pair.getPrivate();
            LOG.debug("public-modulus={}", Base64.encodeBase64String(publicKey.getModulus().toByteArray()));
            LOG.debug("public-exponent={}",
                    Base64.encodeBase64String(publicKey.getPublicExponent().toByteArray()));
            LOG.debug("private-modulus={}", Base64.encodeBase64String(privateKey.getModulus().toByteArray()));
            LOG.debug("private-exponent={}",
                    Base64.encodeBase64String(privateKey.getPrivateExponent().toByteArray()));
        }
        return pair;
    } catch (final NoSuchAlgorithmException e) {
        throw new StandardRuntimeException(e);
    }
}

From source file:br.edu.ufcg.lsd.commune.network.signature.Util.java

public static KeyPair generateKeyPair() {
    KeyPairGenerator keyGen;
    try {/*  w ww  . j av a 2s.  c o m*/
        keyGen = KeyPairGenerator.getInstance(SignatureConstants.KEY_GEN_ALGORITHM);
    } catch (NoSuchAlgorithmException e) {
        //We're assuming that we are always using a valid algorithm
        throw new CommuneRuntimeException(e);
    }
    keyGen.initialize(SignatureConstants.KEYSIZE);
    return keyGen.genKeyPair();
}

From source file:org.kaaproject.kaa.common.endpoint.security.KeyUtil.java

/**
 * Generates a key pair./*from w ww.  j a  v  a  2s . com*/
 *
 * @return key pair
 * @throws NoSuchAlgorithmException no such algorithm
 */
public static KeyPair generateKeyPair() throws NoSuchAlgorithmException {
    KeyPairGenerator clientKeyGen = KeyPairGenerator.getInstance(RSA);
    clientKeyGen.initialize(2048);
    return clientKeyGen.genKeyPair();
}

From source file:com.github.aynu.yukar.framework.util.SecurityHelper.java

/**
 * ?????/*w w w. j  a va  2  s  .  co m*/
 * <dl>
 * <dt>?
 * <dd>EC??????256??????
 * </dl>
 * @return ?(???)
 */
public static KeyPair createSignKeyPair() {
    try {
        final KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("EC");
        keyPairGenerator.initialize(256);
        return keyPairGenerator.generateKeyPair();
    } catch (final NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    }
}