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, SecureRandom random)
        throws InvalidAlgorithmParameterException 

Source Link

Document

Initializes the key pair generator with the given parameter set and source of randomness.

Usage

From source file:mitm.common.security.certificate.impl.StandardX509CertificateBuilderTest.java

@Test
public void testGenerateSelfSignedV3Certificate() throws Exception {
    X509CertificateBuilder certificateBuilder = new StandardX509CertificateBuilder("BC", "BC");

    KeyPairGenerator keyPairGenerator = securityFactory.createKeyPairGenerator("RSA");

    keyPairGenerator.initialize(2048, randomSource);

    KeyPair keyPair = keyPairGenerator.generateKeyPair();

    X500PrincipalBuilder issuerBuilder = new X500PrincipalBuilder();

    issuerBuilder.setCommonName("Martijn Brinkers");
    issuerBuilder.setCountryCode("NL");
    issuerBuilder.setEmail("test@example.com", "test2@example.com");
    issuerBuilder.setGivenName("Martijn");
    issuerBuilder.setSurname("Brinkers");
    issuerBuilder.setLocality("Amsterdam");
    issuerBuilder.setOrganisation("None");
    issuerBuilder.setState("NH");

    AltNamesBuilder altNamesBuider = new AltNamesBuilder();

    altNamesBuider.setRFC822Names("m.brinkers@pobox.com");
    altNamesBuider.setDNSNames("example.com");

    X500Principal issuer = issuerBuilder.buildPrincipal();
    GeneralNames altNames = altNamesBuider.buildAltNames();

    Set<KeyUsageType> keyUsage = new HashSet<KeyUsageType>();

    keyUsage.add(KeyUsageType.DIGITALSIGNATURE);
    keyUsage.add(KeyUsageType.KEYENCIPHERMENT);
    keyUsage.add(KeyUsageType.NONREPUDIATION);

    Set<ExtendedKeyUsageType> extendedKeyUsage = new HashSet<ExtendedKeyUsageType>();

    extendedKeyUsage.add(ExtendedKeyUsageType.CLIENTAUTH);
    extendedKeyUsage.add(ExtendedKeyUsageType.EMAILPROTECTION);

    Date notBefore = DateUtils.addHours(new Date(), -1);
    Date notAfter = DateUtils.addYears(new Date(), 10);

    certificateBuilder.setSubject(issuer);
    certificateBuilder.setIssuer(issuer);
    certificateBuilder.setAltNames(altNames, true);
    certificateBuilder.setKeyUsage(keyUsage, true);
    certificateBuilder.setExtendedKeyUsage(extendedKeyUsage, true);
    certificateBuilder.setNotBefore(notBefore);
    certificateBuilder.setNotAfter(notAfter);
    certificateBuilder.setPublicKey(keyPair.getPublic());
    certificateBuilder.setSerialNumber(new BigInteger("1"));
    certificateBuilder.setSignatureAlgorithm("SHA256WithRSA");
    certificateBuilder.setIsCA(true, true /* critical */);
    certificateBuilder.setPathLengthConstraint(5);

    Set<String> crlDistPoints = new HashSet<String>();
    crlDistPoints.add("http://example.com");
    crlDistPoints.add("123");

    certificateBuilder.setCRLDistributionPoints(crlDistPoints);

    X509Certificate certificate = certificateBuilder.generateCertificate(keyPair.getPrivate(), null);

    assertNotNull(certificate);//  www . j a  v a 2s. c om

    File file = new File(tempDir, "testGenerateSelfSignedV3Certificate.cer");

    CertificateUtils.writeCertificate(certificate, file);

    X509CertificateInspector certInspector = new X509CertificateInspector(certificate);

    assertEquals(
            "EMAILADDRESS=test2@example.com, EMAILADDRESS=test@example.com, GIVENNAME=Martijn, "
                    + "SURNAME=Brinkers, CN=Martijn Brinkers, O=None, L=Amsterdam, ST=NH, C=NL",
            certInspector.getSubjectFriendly());

    assertEquals(certInspector.getIssuerFriendly(), certInspector.getSubjectFriendly());

    AltNamesInspector altNamesInspector = new AltNamesInspector(certificate.getSubjectAlternativeNames());

    List<String> rFC822Names = altNamesInspector.getRFC822Names();

    assertEquals(1, rFC822Names.size());
    assertEquals("m.brinkers@pobox.com", rFC822Names.get(0));

    List<String> dNSNames = altNamesInspector.getDNSNames();

    assertEquals(1, dNSNames.size());
    assertEquals("example.com", dNSNames.get(0));

    assertEquals(3, certInspector.getKeyUsage().size());
    assertTrue(certInspector.getKeyUsage().contains(KeyUsageType.DIGITALSIGNATURE));
    assertTrue(certInspector.getKeyUsage().contains(KeyUsageType.KEYENCIPHERMENT));
    assertTrue(certInspector.getKeyUsage().contains(KeyUsageType.NONREPUDIATION));

    assertEquals(2, certInspector.getExtendedKeyUsage().size());
    assertTrue(certInspector.getExtendedKeyUsage().contains(ExtendedKeyUsageType.CLIENTAUTH));
    assertTrue(certInspector.getExtendedKeyUsage().contains(ExtendedKeyUsageType.EMAILPROTECTION));

    // we cannot compare the dates because of encoding we loose some detail so check if within 1 sec
    assertTrue(Math.abs(notAfter.getTime() - certificate.getNotAfter().getTime()) < 1000);
    assertTrue(Math.abs(notBefore.getTime() - certificate.getNotBefore().getTime()) < 1000);

    assertEquals("1", certInspector.getSerialNumberHex());

    assertEquals("SHA256WITHRSA", certificate.getSigAlgName());

    assertTrue(certInspector.isCA());
    assertEquals(5, certInspector.getBasicConstraints().getPathLenConstraint().intValue());

    Set<String> crlDistPointsCert = CRLDistributionPointsInspector
            .getURIDistributionPointNames(certInspector.getCRLDistibutionPoints());

    assertTrue(crlDistPointsCert.contains("http://example.com"));
    assertTrue(crlDistPointsCert.contains("123"));
}

From source file:com.kuzumeji.platform.standard.SecurityService.java

/**
 * RSA?(?/?)??// w w w.ja v  a 2  s.  c om
 * <dl>
 * <dt>?
 * <dd>RSA?(?/?)??(?=2048)
 * </dl>
 * @return ?
 */
public KeyPair generateKeyPair() {
    try {
        final KeyPairGenerator keygen = KeyPairGenerator.getInstance(RSA_ALGO_NAME);
        keygen.initialize(KEYSIZE, SECURE_RANDOM);
        return keygen.generateKeyPair();
    } catch (final NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.vmware.identity.openidconnect.sample.RelyingPartyInstaller.java

void install(String[] redirectEndpointUrls, String[] postLogoutRedirectUrls, String logoutUrl)
        throws Exception {
    String domainControllerFQDN = this.relyingPartyConfig.getOpFQDN();
    int domainControllerPort = Integer.parseInt(this.relyingPartyConfig.getOpListeningPort());
    String tenant = this.relyingPartyConfig.getTenant();

    // retrieve OIDC meta data
    MetadataHelper metadataHelper = new MetadataHelper.Builder(domainControllerFQDN)
            .domainControllerPort(domainControllerPort).tenant(tenant).keyStore(this.keyStore).build();

    ProviderMetadata providerMetadata = metadataHelper.getProviderMetadata();
    RSAPublicKey providerPublicKey = metadataHelper.getProviderRSAPublicKey(providerMetadata);

    // create a non-registered OIDC client and get bearer tokens by admin user name/password
    ConnectionConfig connectionConfig = new ConnectionConfig(providerMetadata, providerPublicKey,
            this.keyStore);
    ClientConfig clientConfig = new ClientConfig(connectionConfig, null, null);
    OIDCClient nonRegisteredClient = new OIDCClient(clientConfig);
    TokenSpec tokenSpec = new TokenSpec.Builder(TokenType.BEARER)
            .resourceServers(Arrays.asList("rs_admin_server")).build();
    OIDCTokens oidcTokens = nonRegisteredClient.acquireTokensByPassword(
            this.relyingPartyConfig.getAdminUsername(), this.relyingPartyConfig.getAdminPassword(), tokenSpec);

    // create a private/public key pair, generate a certificate and assign it to a solution user name.
    Security.addProvider(new BouncyCastleProvider());
    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA", "BC");
    keyGen.initialize(1024, new SecureRandom());
    KeyPair keypair = keyGen.generateKeyPair();
    String solutionUserName = this.relyingPartyConfig.getClientPrefix() + UUID.randomUUID().toString();
    X509Certificate clientCertificate = generateCertificate(keypair, solutionUserName);

    // create REST idm client
    IdmClient idmClient = createIdmClient(oidcTokens.getAccessToken(), domainControllerFQDN,
            domainControllerPort);/* ww  w. j av  a  2 s.co m*/

    VmdirClient vmdirClient = createVMdirClient(oidcTokens.getAccessToken(), domainControllerFQDN,
            domainControllerPort);

    // create a solution user
    CertificateDTO certificateDTO = new CertificateDTO.Builder()
            .withEncoded(convertToBase64PEMString(clientCertificate)).build();
    SolutionUserDTO solutionUserDTO = new SolutionUserDTO.Builder().withName(solutionUserName)
            .withDomain(tenant).withCertificate(certificateDTO).build();
    vmdirClient.solutionUser().create(tenant, solutionUserDTO);

    // add the solution user to ActAs group
    List<String> members = Arrays.asList(solutionUserName + "@" + tenant);
    vmdirClient.group().addMembers(tenant, "ActAsUsers", tenant, members,
            com.vmware.directory.rest.common.data.MemberType.USER);

    // register a OIDC client
    OIDCClientMetadataDTO oidcClientMetadataDTO = new OIDCClientMetadataDTO.Builder()
            .withRedirectUris(Arrays.asList(redirectEndpointUrls))
            .withPostLogoutRedirectUris(Arrays.asList(postLogoutRedirectUrls)).withLogoutUri(logoutUrl)
            .withTokenEndpointAuthMethod("private_key_jwt")
            .withCertSubjectDN(clientCertificate.getSubjectDN().getName())
            .withAuthnRequestClientAssertionLifetimeMS(2 * 60 * 1000L).build();
    OIDCClientDTO oidcClientDTO = idmClient.oidcClient().register(tenant, oidcClientMetadataDTO);

    // persist data involved installation in files so they can be picked up in case server reboots
    savePublicKey(this.relyingPartyConfig.getOpPublickeyFile(), providerPublicKey);
    savePrivateKey(this.relyingPartyConfig.getRpPrivatekeyFile(), keypair.getPrivate());
    writeObject(this.relyingPartyConfig.getRpCertificateFile(), clientCertificate);
    writeObject(this.relyingPartyConfig.getRpInfoFile(), oidcClientDTO.getClientId());
    writeObject(this.relyingPartyConfig.getRpListeningPortFile(), this.relyingPartyConfig.getRpListeningPort());
}

From source file:sernet.verinice.encryption.test.CryptoTest.java

KeyPair generateKeyPair() throws NoSuchAlgorithmException, NoSuchProviderException {
    KeyPairGenerator keyGen;
    keyGen = org.bouncycastle.jce.provider.asymmetric.ec.KeyPairGenerator.getInstance("RSA",
            BouncyCastleProvider.PROVIDER_NAME);
    keyGen.initialize(1024, new SecureRandom());
    return keyGen.generateKeyPair();
}

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

/**
 * @see com.cws.esolutions.security.dao.keymgmt.interfaces.KeyManager#createKeys(java.lang.String)
 *///from  w  w  w  .  j  a va 2s .  c  o  m
public synchronized boolean createKeys(final String guid) throws KeyManagementException {
    final String methodName = FileKeyManager.CNAME
            + "#createKeys(final String guid) throws KeyManagementException";

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

    boolean isComplete = false;
    OutputStream publicStream = null;
    OutputStream privateStream = null;

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

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

        keyDirectory.setExecutable(true, true);

        SecureRandom random = new SecureRandom();
        KeyPairGenerator keyGenerator = KeyPairGenerator.getInstance(keyConfig.getKeyAlgorithm());
        keyGenerator.initialize(keyConfig.getKeySize(), random);
        KeyPair keyPair = keyGenerator.generateKeyPair();

        if (keyPair != null) {
            File privateFile = FileUtils
                    .getFile(keyDirectory + "/" + guid + SecurityServiceConstants.PRIVATEKEY_FILE_EXT);
            File publicFile = FileUtils
                    .getFile(keyDirectory + "/" + guid + SecurityServiceConstants.PUBLICKEY_FILE_EXT);

            if (!(privateFile.createNewFile())) {
                throw new IOException("Failed to store private key file");
            }

            if (!(publicFile.createNewFile())) {
                throw new IOException("Failed to store public key file");
            }

            privateFile.setWritable(true, true);
            publicFile.setWritable(true, true);

            privateStream = new FileOutputStream(privateFile);
            publicStream = new FileOutputStream(publicFile);

            IOUtils.write(keyPair.getPrivate().getEncoded(), privateStream);
            IOUtils.write(keyPair.getPublic().getEncoded(), publicStream);

            // assume success, as we'll get an IOException if the write failed
            isComplete = true;
        } else {
            throw new KeyManagementException("Failed to generate keypair. Cannot continue.");
        }
    } catch (FileNotFoundException fnfx) {
        throw new KeyManagementException(fnfx.getMessage(), fnfx);
    } catch (IOException iox) {
        throw new KeyManagementException(iox.getMessage(), iox);
    } catch (NoSuchAlgorithmException nsax) {
        throw new KeyManagementException(nsax.getMessage(), nsax);
    } finally {
        if (publicStream != null) {
            IOUtils.closeQuietly(publicStream);
        }

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

    return isComplete;
}

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   www  . j a  v  a2 s.com*/
 * 
 * @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: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:com.owncloud.android.util.EncryptionTestIT.java

@Test
public void encryptPrivateKey() throws Exception {
    String keyPhrase = "moreovertelevisionfactorytendencyindependenceinternationalintellectualimpress"
            + "interestvolunteer";
    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
    keyGen.initialize(4096, new SecureRandom());
    KeyPair keyPair = keyGen.generateKeyPair();
    PrivateKey privateKey = keyPair.getPrivate();
    byte[] privateKeyBytes = privateKey.getEncoded();
    String privateKeyString = EncryptionUtils.encodeBytesToBase64String(privateKeyBytes);

    String encryptedString = EncryptionUtils.encryptPrivateKey(privateKeyString, keyPhrase);
    String decryptedString = EncryptionUtils.decryptPrivateKey(encryptedString, keyPhrase);

    assertEquals(privateKeyString, decryptedString);
}

From source file:org.apache.drill.exec.server.rest.WebServer.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.
 *
 * @return Initialized {@link ServerConnector} for HTTPS connectios.
 * @throws Exception//from  www.ja v  a2 s  .co  m
 */
private ServerConnector createHttpsConnector() throws Exception {
    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))) {
        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 {
        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(config.getInt(ExecConstants.HTTP_PORT));

    return sslConnector;
}

From source file:gov.nih.nci.firebird.service.signing.DigitalSigningHelper.java

/**
 * Generate a random 1024 bit RSA key pair.
 *
 * @throws DigitalSigningException//from  w ww  .jav a2 s . c  o  m
 *             Customized exception with error message.
 *
 * @return a random KeyPair.
 */
KeyPair generateKeyPair() throws DigitalSigningException {

    KeyPairGenerator kpGen = null;
    try {
        kpGen = KeyPairGenerator.getInstance("RSA", BOUNCY_CASTLE_PROVIDER);
        kpGen.initialize(KEYSIZE, new SecureRandom());
        return kpGen.generateKeyPair();
    } catch (NoSuchAlgorithmException e) {
        throw new DigitalSigningException(KEYPAIR_GENERATION_ERROR_MESSAGE, e);
    } catch (NoSuchProviderException e) {
        throw new DigitalSigningException(KEYPAIR_GENERATION_ERROR_MESSAGE, e);
    }
}