Example usage for java.security KeyPairGenerator getInstance

List of usage examples for java.security KeyPairGenerator getInstance

Introduction

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

Prototype

public static KeyPairGenerator getInstance(String algorithm) throws NoSuchAlgorithmException 

Source Link

Document

Returns a KeyPairGenerator object that generates public/private key pairs for the specified algorithm.

Usage

From source file:org.apache.drill.cv.exec.server.rest.CvDrillWebServer.java

/**
 * Create an HTTPS connector for given jetty server instance. If the admin has specified
 * keystore/truststore settings they will be used else a self-signed certificate is generated and
 * used.//from  w w  w . ja  v  a2s.c o  m
 *
 * @return Initialized {@link ServerConnector} for HTTPS connectios.
 * @throws Exception
 */
private ServerConnector createHttpsConnector() throws Exception {
    CvDrillWebServer.logger.info("Setting up HTTPS connector for web server");

    final SslContextFactory sslContextFactory = new SslContextFactory();

    if (config.hasPath(ExecConstants.HTTP_KEYSTORE_PATH)
            && !Strings.isNullOrEmpty(config.getString(ExecConstants.HTTP_KEYSTORE_PATH))) {
        CvDrillWebServer.logger.info("Using configured SSL settings for web server");
        sslContextFactory.setKeyStorePath(config.getString(ExecConstants.HTTP_KEYSTORE_PATH));
        sslContextFactory.setKeyStorePassword(config.getString(ExecConstants.HTTP_KEYSTORE_PASSWORD));

        // TrustStore and TrustStore password are optional
        if (config.hasPath(ExecConstants.HTTP_TRUSTSTORE_PATH)) {
            sslContextFactory.setTrustStorePath(config.getString(ExecConstants.HTTP_TRUSTSTORE_PATH));
            if (config.hasPath(ExecConstants.HTTP_TRUSTSTORE_PASSWORD)) {
                sslContextFactory
                        .setTrustStorePassword(config.getString(ExecConstants.HTTP_TRUSTSTORE_PASSWORD));
            }
        }
    } else {
        CvDrillWebServer.logger.info("Using generated self-signed SSL settings for web server");
        final SecureRandom random = new SecureRandom();

        // Generate a private-public key pair
        final KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        keyPairGenerator.initialize(1024, random);
        final KeyPair keyPair = keyPairGenerator.generateKeyPair();

        final DateTime now = DateTime.now();

        // Create builder for certificate attributes
        final X500NameBuilder nameBuilder = new X500NameBuilder(BCStyle.INSTANCE)
                .addRDN(BCStyle.OU, "Apache Drill (auth-generated)")
                .addRDN(BCStyle.O, "Apache Software Foundation (auto-generated)")
                .addRDN(BCStyle.CN, workManager.getContext().getEndpoint().getAddress());

        final Date notBefore = now.minusMinutes(1).toDate();
        final Date notAfter = now.plusYears(5).toDate();
        final BigInteger serialNumber = new BigInteger(128, random);

        // Create a certificate valid for 5years from now.
        final X509v3CertificateBuilder certificateBuilder = new JcaX509v3CertificateBuilder(nameBuilder.build(), // attributes
                serialNumber, notBefore, notAfter, nameBuilder.build(), keyPair.getPublic());

        // Sign the certificate using the private key
        final ContentSigner contentSigner = new JcaContentSignerBuilder("SHA256WithRSAEncryption")
                .build(keyPair.getPrivate());
        final X509Certificate certificate = new JcaX509CertificateConverter()
                .getCertificate(certificateBuilder.build(contentSigner));

        // Check the validity
        certificate.checkValidity(now.toDate());

        // Make sure the certificate is self-signed.
        certificate.verify(certificate.getPublicKey());

        // Generate a random password for keystore protection
        final String keyStorePasswd = RandomStringUtils.random(20);
        final KeyStore keyStore = KeyStore.getInstance("JKS");
        keyStore.load(null, null);
        keyStore.setKeyEntry("DrillAutoGeneratedCert", keyPair.getPrivate(), keyStorePasswd.toCharArray(),
                new java.security.cert.Certificate[] { certificate });

        sslContextFactory.setKeyStore(keyStore);
        sslContextFactory.setKeyStorePassword(keyStorePasswd);
    }

    final HttpConfiguration httpsConfig = new HttpConfiguration();
    httpsConfig.addCustomizer(new SecureRequestCustomizer());

    // SSL Connector
    final ServerConnector sslConnector = new ServerConnector(embeddedJetty,
            new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.asString()),
            new HttpConnectionFactory(httpsConfig));
    sslConnector.setPort(getWebserverPort());

    return sslConnector;
}

From source file:org.kuali.rice.ksb.security.admin.service.impl.JavaSecurityManagementServiceImpl.java

public KeyStore generateClientKeystore(String alias, String clientPassphrase) throws GeneralSecurityException {
    if (isAliasInKeystore(alias)) {
        throw new KeyStoreException("Alias '" + alias + "' already exists in module keystore");
    }//  w  ww  . j a v a  2s  .com
    //        Certificate[] clientCertificateChain = {};
    //        PrivateKey clientPrivateKey = null;
    KeyStore ks = null;
    try {
        // generate a key pair for the client
        KeyPairGenerator keyGen = KeyPairGenerator.getInstance(CLIENT_KEY_GENERATOR_ALGORITHM);
        //            SecureRandom random = SecureRandom.getInstance(CLIENT_SECURE_RANDOM_ALGORITHM);
        keyGen.initialize(CLIENT_KEY_PAIR_KEY_SIZE);
        //            keyGen.initialize(new RSAKeyGenParameterSpec(512,RSAKeyGenParameterSpec.F0));
        KeyPair pair = keyGen.generateKeyPair();

        //            PublicKey clientPublicKey = pair.getPublic();
        //            clientPrivateKey = pair.getPrivate();
        //            // generate the Certificate
        //            X509V3CertificateGenerator certificateGenerator = new X509V3CertificateGenerator();
        ////            X509Name nameInfo = new X509Name(false,"CN=" + alias);
        //            certificateGenerator.setSignatureAlgorithm("MD5WithRSA");
        //            certificateGenerator.setSerialNumber(new java.math.BigInteger("1"));
        //            X509Principal nameInfo = new X509Principal("CN=" + alias);
        //            certificateGenerator.setIssuerDN(nameInfo);
        //            certificateGenerator.setSubjectDN(nameInfo);                       // note: same as issuer
        //            certificateGenerator.setNotBefore(new Date());
        //            Calendar c = Calendar.getInstance();
        //            c.add(Calendar.DATE, CLIENT_CERT_EXPIRATION_DAYS);
        //            certificateGenerator.setNotAfter(c.getTime());
        //            certificateGenerator.setPublicKey(clientPublicKey);
        //            X509Certificate cert = certificateGenerator.generateX509Certificate(clientPrivateKey);
        //            clientCertificateChain = new Certificate[]{cert};
        //
        //            // generate client keyStore file
        //            ks = KeyStore.getInstance(getModuleKeyStoreType());
        //            ks.load(null, clientPassphrase.toCharArray());
        //            // set client private key on keyStore file
        //            ks.setEntry(alias, new KeyStore.PrivateKeyEntry(clientPrivateKey, clientCertificateChain), new KeyStore.PasswordProtection(clientPassphrase.toCharArray()));
        Certificate cert = generateCertificate(pair, alias);
        ks = generateKeyStore(cert, pair.getPrivate(), alias, clientPassphrase);

        // set the module certificate on the client keyStore file
        ks.setEntry(getModuleKeyStoreAlias(),
                new KeyStore.TrustedCertificateEntry(getCertificate(getModuleKeyStoreAlias())), null);

        // add the client certificate to the module keyStore
        addClientCertificateToModuleKeyStore(alias, cert);

        return ks;
    } catch (IOException e) {
        throw new RuntimeException("Could not create new KeyStore", e);
    }
}

From source file:net.nicholaswilliams.java.licensing.encryption.TestKeyFileUtilities.java

@Test
public void testPublicKeyEncryption02() throws Throwable {
    File file = new File("testPublicKeyEncryption02.key");

    if (file.exists())
        FileUtils.forceDelete(file);/*from w  ww  . java  2  s  .  c  o  m*/

    PublicKey publicKey = KeyPairGenerator.getInstance(KeyFileUtilities.keyAlgorithm).generateKeyPair()
            .getPublic();

    PublicKey otherKey = KeyPairGenerator.getInstance(KeyFileUtilities.keyAlgorithm).generateKeyPair()
            .getPublic();

    assertFalse("The keys should not be equal (1).", otherKey.equals(publicKey));

    KeyFileUtilities.writeEncryptedPublicKey(publicKey, file, "yourTestPassword02".toCharArray());

    PublicKey publicKey2 = KeyFileUtilities.readEncryptedPublicKey(file, "yourTestPassword02".toCharArray());

    assertNotNull("The key should not be null.", publicKey2);
    assertFalse("The objects should not be the same.", publicKey == publicKey2);
    assertEquals("The keys should be the same.", publicKey, publicKey2);

    assertFalse("The keys should not be equal (2).", otherKey.equals(publicKey2));

    FileUtils.forceDelete(file);
}

From source file:com.qut.middleware.crypto.impl.CryptoProcessorImpl.java

public KeyPair generateKeyPair() throws CryptoException {
    try {/* w  w w  .j  a  v a 2s.co  m*/
        KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
        keyGen.initialize(this.keySize);

        KeyPair keyPair = keyGen.generateKeyPair();
        return keyPair;
    } catch (NoSuchAlgorithmException e) {
        this.logger.error("NoSuchAlgorithmException thrown, " + e.getLocalizedMessage());
        this.logger.debug(e.toString());
        throw new CryptoException(e.getLocalizedMessage(), e);
    }
}

From source file:com.owncloud.android.util.EncryptionTestIT.java

@Test
public void generateCSR() throws Exception {
    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
    keyGen.initialize(2048, new SecureRandom());
    KeyPair keyPair = keyGen.generateKeyPair();

    assertFalse(CsrHelper.generateCsrPemEncodedString(keyPair, "").isEmpty());
    assertFalse(EncryptionUtils.encodeBytesToBase64String(keyPair.getPublic().getEncoded()).isEmpty());
}

From source file:edu.vt.alerts.android.library.tasks.RegistrationTask.java

private KeyPair generateKeyPair() throws Exception {
    KeyPairGenerator kpg = KeyPairGenerator.getInstance(KEYPAIR_ALGORITHM);
    kpg.initialize(KEYPAIR_KEYSIZE);//from  w  w  w.ja v  a  2  s .  co m
    return kpg.generateKeyPair();
}

From source file:cloud.google.com.windows.example.ExampleCode.java

private KeyPair generateKeys() throws NoSuchAlgorithmException {
    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");

    // Key moduli for encryption/decryption are 2048 bits long.
    keyGen.initialize(2048);/*from   w  w  w .j  av a 2  s .  co m*/

    return keyGen.genKeyPair();
}

From source file:org.iavante.sling.commons.services.impl.EncryptionServiceImpl.java

/**
 * Make a keypair (public for encryption and private for decrypt) with
 * RSA_KeySize bits size/*from   w  w  w.  j  a  v  a  2 s. c om*/
 * 
 * @throws NoSuchAlgorithmException
 * @throws NoSuchProviderException
 */
private void makeKey() throws NoSuchAlgorithmException, NoSuchProviderException {
    KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
    // Initialize the Key-Pair Generator
    SecureRandom random = SecureRandom.getInstance("SHA1PRNG", "SUN");
    kpg.initialize(defaultRsaKeySize, random);
    keyPair = kpg.generateKeyPair();
}

From source file:org.apache.xml.security.test.encryption.XMLCipherTester.java

/**
 * Test encryption using a generated AES 256 bit key that is
 * encrypted using an RSA key.  Reverse using KEK
 *//*from ww  w .j a  v a2s  . c om*/

public void testAES128ElementRSAKWCipherUsingKEK() throws Exception {

    Document d = document(); // source
    Document ed = null;
    Document dd = null;
    Element e = (Element) d.getElementsByTagName(element()).item(index());
    Element ee = null;

    String source = null;
    String target = null;

    if (haveISOPadding) {

        source = toString(d);

        // Generate an RSA key
        KeyPairGenerator rsaKeygen = KeyPairGenerator.getInstance("RSA");
        KeyPair kp = rsaKeygen.generateKeyPair();
        PrivateKey priv = kp.getPrivate();
        PublicKey pub = kp.getPublic();

        // Generate a traffic key
        KeyGenerator keygen = KeyGenerator.getInstance("AES");
        keygen.init(256);
        Key key = keygen.generateKey();

        cipher = XMLCipher.getInstance(XMLCipher.RSA_v1dot5);
        cipher.init(XMLCipher.WRAP_MODE, pub);
        EncryptedKey encryptedKey = cipher.encryptKey(d, key);

        // encrypt
        cipher = XMLCipher.getInstance(XMLCipher.AES_256);
        cipher.init(XMLCipher.ENCRYPT_MODE, key);
        EncryptedData builder = cipher.getEncryptedData();

        KeyInfo builderKeyInfo = builder.getKeyInfo();
        if (builderKeyInfo == null) {
            builderKeyInfo = new KeyInfo(d);
            builder.setKeyInfo(builderKeyInfo);
        }

        builderKeyInfo.add(encryptedKey);

        ed = cipher.doFinal(d, e);
        log.debug("Encrypted document");
        log.debug(toString(ed));

        //decrypt
        key = null;
        ee = (Element) ed.getElementsByTagName("xenc:EncryptedData").item(0);
        cipher = XMLCipher.getInstance(XMLCipher.AES_128);
        cipher.init(XMLCipher.DECRYPT_MODE, null);
        cipher.setKEK(priv);
        dd = cipher.doFinal(ed, ee);

        target = toString(dd);
        log.debug("Output document");
        log.debug(target);

        Assert.assertEquals(source, target);
    } else {
        log.warn("Test testAES128ElementRSAKWCipherUsingKEK skipped as necessary algorithms not available");
    }
}