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.forgerock.openidm.security.impl.SecurityResourceProvider.java

/**
 * Generates a self signed certificate using the given properties.
 *
 * @param commonName the subject's common name
 * @param organization the subject's organization name
 * @param organizationUnit the subject's organization unit name
 * @param stateOrProvince the subject's state or province
 * @param country the subject's country code
 * @param locality the subject's locality
 * @param algorithm the algorithm to use
 * @param keySize the keysize to use//from   w  ww  . j a v  a2s.  c o  m
 * @param signatureAlgorithm the signature algorithm to use
 * @param validFrom when the certificate is valid from
 * @param validTo when the certificate is valid until
 * @return The generated certificate
 * @throws Exception
 */
protected Pair<X509Certificate, PrivateKey> generateCertificate(String commonName, String organization,
        String organizationUnit, String stateOrProvince, String country, String locality, String algorithm,
        int keySize, String signatureAlgorithm, String validFrom, String validTo) throws Exception {

    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(algorithm); // "RSA","BC"
    keyPairGenerator.initialize(keySize);
    KeyPair keyPair = keyPairGenerator.generateKeyPair();

    // Generate self-signed certificate
    X500NameBuilder builder = new X500NameBuilder(BCStyle.INSTANCE);
    builder.addRDN(BCStyle.C, country);
    builder.addRDN(BCStyle.ST, stateOrProvince);
    builder.addRDN(BCStyle.L, locality);
    builder.addRDN(BCStyle.OU, organizationUnit);
    builder.addRDN(BCStyle.O, organization);
    builder.addRDN(BCStyle.CN, commonName);

    Date notBefore = null;
    Date notAfter = null;
    if (validFrom == null) {
        notBefore = new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30);
    } else {
        DateTime notBeforeDateTime = DateUtil.getDateUtil().parseIfDate(validFrom);
        if (notBeforeDateTime == null) {
            throw new InternalServerErrorException("Invalid date format for 'validFrom' property");
        } else {
            notBefore = notBeforeDateTime.toDate();
        }
    }
    if (validTo == null) {
        Calendar date = Calendar.getInstance();
        date.setTime(new Date());
        date.add(Calendar.YEAR, 10);
        notAfter = date.getTime();
    } else {
        DateTime notAfterDateTime = DateUtil.getDateUtil().parseIfDate(validTo);
        if (notAfterDateTime == null) {
            throw new InternalServerErrorException("Invalid date format for 'validTo' property");
        } else {
            notAfter = notAfterDateTime.toDate();
        }
    }

    BigInteger serial = BigInteger.valueOf(System.currentTimeMillis());

    X509v3CertificateBuilder v3CertGen = new JcaX509v3CertificateBuilder(builder.build(), serial, notBefore,
            notAfter, builder.build(), keyPair.getPublic());

    ContentSigner sigGen = new JcaContentSignerBuilder(signatureAlgorithm).setProvider(BC)
            .build(keyPair.getPrivate());

    X509Certificate cert = new JcaX509CertificateConverter().setProvider(BC)
            .getCertificate(v3CertGen.build(sigGen));
    cert.checkValidity(new Date());
    cert.verify(cert.getPublicKey());

    return Pair.of(cert, keyPair.getPrivate());
}

From source file:info.magnolia.cms.security.SecurityUtil.java

public static MgnlKeyPair generateKeyPair(int keyLength) throws NoSuchAlgorithmException {
    KeyPairGenerator kgen = KeyPairGenerator.getInstance(ALGORITHM);
    kgen.initialize(keyLength);// w w  w  . j  a  v a2s  .  com
    KeyPair key = kgen.genKeyPair();
    return new MgnlKeyPair(byteArrayToHex(key.getPrivate().getEncoded()),
            byteArrayToHex(key.getPublic().getEncoded()));
}

From source file:org.tolven.config.model.CredentialManager.java

private X509CertificatePrivateKeyPair createSelfSignedCertificate(X500Principal subjectX500Principal)
        throws GeneralSecurityException {
    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
    keyPairGenerator.initialize(1024);/* w ww. j  a  v a  2s  . co  m*/
    KeyPair keyPair = keyPairGenerator.generateKeyPair();
    X509Certificate certificate = signCertificate(subjectX500Principal, keyPair.getPublic(),
            subjectX500Principal, keyPair.getPrivate());
    return new X509CertificatePrivateKeyPair(certificate, keyPair.getPrivate());
}

From source file:test.unit.be.agiv.security.handler.WSSecurityHandlerTest.java

private KeyPair generateKeyPair(int keySize) throws Exception {
    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
    SecureRandom random = new SecureRandom();
    keyPairGenerator.initialize(new RSAKeyGenParameterSpec(keySize, RSAKeyGenParameterSpec.F4), random);
    KeyPair keyPair = keyPairGenerator.generateKeyPair();
    return keyPair;
}

From source file:netinf.common.security.impl.CryptographyTest.java

@Test
public void testBadPrivateKey() throws NetInfCheckedSecurityException {
    Attribute attribute = createTestAttribute();
    Attribute encryptedAttribute = crypto.encrypt(attribute, publicKeys);
    // String keyName = identityObject.getIdentifier().toString() + "?" + DefinedAttributeIdentification.PUBLIC_KEY.getURI();

    IdentityManager wrongIdentityManager = EasyMock.createMock(IdentityManager.class);
    EasyMock.expect(wrongIdentityManager.hasPrivateKey((String) EasyMock.anyObject())).andReturn(true)
            .anyTimes();// w w w  .j ava2s.c  o m
    EasyMock.expect(wrongIdentityManager.hasPrivateKey((String) EasyMock.anyObject(),
            (String) EasyMock.anyObject(), (String) EasyMock.anyObject())).andReturn(true).anyTimes();
    try {
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        keyPairGenerator.initialize(1024);
        KeyPair pair = keyPairGenerator.generateKeyPair();

        PrivateKey privateKey = pair.getPrivate();
        try {
            EasyMock.expect(wrongIdentityManager.getPrivateKey((String) EasyMock.anyObject()))
                    .andReturn(privateKey).anyTimes();
            EasyMock.expect(wrongIdentityManager.getPrivateKey((String) EasyMock.anyObject(),
                    (String) EasyMock.anyObject(), (String) EasyMock.anyObject())).andReturn(privateKey)
                    .anyTimes();
        } catch (NetInfCheckedException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
    } catch (Exception e) {
        throw new NetInfUncheckedException("error creating keys");
    }
    EasyMock.replay(wrongIdentityManager);

    try {
        // FIXME added dummy-port! needs adjustment!
        CryptographyImpl crypto = new CryptographyImpl(wrongIdentityManager, algorithm, factory,
                convenienceCommunicator);

        crypto.decrypt(encryptedAttribute);
        Assert.fail("Exception expected. Wrong private key given.");
    } catch (NetInfCheckedSecurityException securityException) {
        System.out.println(securityException.getMessage());
    }
}

From source file:org.apache.drill.yarn.appMaster.http.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.// ww w .  j  a v a2 s .  com
 * <p>
 * This is a shameless copy of
 * {@link org.apache.drill.exec.server.rest.Webserver#createHttpsConnector( )}.
 * The two should be merged at some point. The primary issue is that the Drill
 * version is tightly coupled to Drillbit configuration.
 *
 * @return Initialized {@link ServerConnector} for HTTPS connections.
 * @throws Exception
 */

private ServerConnector createHttpsConnector(Config config) throws Exception {
    LOG.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)))
    // {
    // LOG.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 {
    LOG.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, "Drill AM");

    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(jettyServer,
            new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.asString()),
            new HttpConnectionFactory(httpsConfig));
    sslConnector.setPort(config.getInt(DrillOnYarnConfig.HTTP_PORT));

    return sslConnector;
}

From source file:netinf.common.security.impl.CryptographyTest.java

@Test
public void testBadPrivateKeyAlgorithm() throws NetInfCheckedSecurityException {
    Attribute attribute = createTestAttribute();
    Attribute encryptedAttribute = crypto.encrypt(attribute, publicKeys);

    IdentityManager wrongIdentityManager = EasyMock.createMock(IdentityManager.class);
    EasyMock.expect(wrongIdentityManager.hasPrivateKey((String) EasyMock.anyObject())).andReturn(true)
            .anyTimes();//from   ww  w  .  j  a  v a 2 s.  c o m
    EasyMock.expect(wrongIdentityManager.hasPrivateKey((String) EasyMock.anyObject(),
            (String) EasyMock.anyObject(), (String) EasyMock.anyObject())).andReturn(true).anyTimes();
    try {
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("DSA");
        keyPairGenerator.initialize(1024);
        KeyPair pair = keyPairGenerator.generateKeyPair();

        PrivateKey privateKey = pair.getPrivate();
        try {
            EasyMock.expect(wrongIdentityManager.getPrivateKey((String) EasyMock.anyObject()))
                    .andReturn(privateKey).anyTimes();
            EasyMock.expect(wrongIdentityManager.getPrivateKey((String) EasyMock.anyObject(),
                    (String) EasyMock.anyObject(), (String) EasyMock.anyObject())).andReturn(privateKey)
                    .anyTimes();
        } catch (NetInfCheckedException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
    } catch (Exception e) {
        throw new NetInfUncheckedException("error creating keys");
    }
    EasyMock.replay(wrongIdentityManager);

    try {
        // FIXME added dummy-port! needs adjustment!
        CryptographyImpl crypto = new CryptographyImpl(wrongIdentityManager, algorithm, factory,
                convenienceCommunicator);

        crypto.decrypt(encryptedAttribute);
        Assert.fail("Exception expected. Wrong private key given.");
    } catch (NetInfCheckedSecurityException securityException) {
        System.out.println(securityException.getMessage());
    }
}

From source file:org.forgerock.openidm.security.impl.SecurityResourceProvider.java

/**
 * Generates a CSR request.//www .  jav  a  2 s.c  om
 * 
 * @param alias
 * @param algorithm
 * @param signatureAlgorithm
 * @param keySize
 * @param params
 * @return
 * @throws Exception
 */
protected Pair<PKCS10CertificationRequest, PrivateKey> generateCSR(String alias, String algorithm,
        String signatureAlgorithm, int keySize, JsonValue params) throws Exception {

    // Construct the distinguished name
    StringBuilder sb = new StringBuilder();
    sb.append("CN=").append(params.get("CN").required().asString().replaceAll(",", "\\\\,"));
    sb.append(", OU=").append(params.get("OU").defaultTo("None").asString().replaceAll(",", "\\\\,"));
    sb.append(", O=").append(params.get("O").defaultTo("None").asString().replaceAll(",", "\\\\,"));
    sb.append(", L=").append(params.get("L").defaultTo("None").asString().replaceAll(",", "\\\\,"));
    sb.append(", ST=").append(params.get("ST").defaultTo("None").asString().replaceAll(",", "\\\\,"));
    sb.append(", C=").append(params.get("C").defaultTo("None").asString().replaceAll(",", "\\\\,"));

    // Create the principle subject name
    X509Principal subjectName = new X509Principal(sb.toString());

    //store.getStore().

    // Generate the key pair
    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(algorithm);
    keyPairGenerator.initialize(keySize);
    KeyPair keyPair = keyPairGenerator.generateKeyPair();
    PublicKey publicKey = keyPair.getPublic();
    PrivateKey privateKey = keyPair.getPrivate();

    // Generate the certificate request
    PKCS10CertificationRequest cr = new PKCS10CertificationRequest(signatureAlgorithm, subjectName, publicKey,
            null, privateKey);

    // Store the private key to use when the signed cert is return and updated
    logger.debug("Storing private key with alias {}", alias);
    storeKeyPair(alias, keyPair);

    return Pair.of(cr, privateKey);
}

From source file:org.metaeffekt.dcc.commons.pki.CertificateManager.java

private KeyPair generateKeyPair() throws NoSuchAlgorithmException {
    String keyAlgorithm = getProperty(PROPERTY_KEY_ALGORITHM, DEFAULT_KEY_ALGORITHM);
    int keySize = getProperty(PROPERTY_KEY_SIZE, DEFAULT_KEY_SIZE);

    final KeyPairGenerator keyGenerator = KeyPairGenerator.getInstance(keyAlgorithm);
    keyGenerator.initialize(keySize);//from   ww  w .  j a  v  a 2s.  c  o m
    return keyGenerator.generateKeyPair();
}

From source file:test.integ.be.fedict.commons.eid.client.JCATest.java

@Test
public void testSoftwareRSAKeyWrapping() throws Exception {
    final KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
    final KeyPair keyPair = keyPairGenerator.generateKeyPair();

    final KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
    final SecretKey secretKey = keyGenerator.generateKey();
    LOG.debug("secret key algo: " + secretKey.getAlgorithm());

    final Cipher cipher = Cipher.getInstance("RSA");
    cipher.init(Cipher.WRAP_MODE, keyPair.getPublic());
    LOG.debug("cipher security provider: " + cipher.getProvider().getName());
    LOG.debug("cipher type: " + cipher.getClass().getName());
    final byte[] wrappedKey = cipher.wrap(secretKey);

    cipher.init(Cipher.UNWRAP_MODE, keyPair.getPrivate());
    final Key resultKey = cipher.unwrap(wrappedKey, "AES", Cipher.SECRET_KEY);

    assertArrayEquals(secretKey.getEncoded(), resultKey.getEncoded());

}