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:com.streamsets.datacollector.publicrestapi.TestCredentialsDeploymentResource.java

private KeyPair generateKeys() throws Exception {
    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
    SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
    keyGen.initialize(512, random);/*  w w  w  . ja va 2  s .c om*/
    return keyGen.generateKeyPair();
}

From source file:org.nuxeo.ecm.directory.ldap.LDAPDirectoryTestCase.java

/**
 * Method to create a X509 certificate used to test the creation and the update of an entry in the ldap.
 *
 * @return A X509 certificate//  w w  w  .j  a v a 2 s.c  o m
 * @throws CertificateException
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeyException
 * @throws SignatureException
 * @throws IllegalStateException
 * @since 5.9.3
 */
protected X509Certificate createCertificate(String dnNameStr) throws NoSuchAlgorithmException,
        CertificateException, InvalidKeyException, IllegalStateException, SignatureException {
    X509Certificate cert = null;

    // Parameters used to define the certificate
    // yesterday
    Date validityBeginDate = new Date(System.currentTimeMillis() - 24 * 60 * 60 * 1000);
    // in 2 years
    Date validityEndDate = new Date(System.currentTimeMillis() + 2 * 365 * 24 * 60 * 60 * 1000);

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

    // Define the content of the certificate
    X509V1CertificateGenerator certGen = new X509V1CertificateGenerator();
    X500Principal dnName = new X500Principal(dnNameStr);

    certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));
    certGen.setSubjectDN(dnName);
    certGen.setIssuerDN(dnName); // use the same
    certGen.setNotBefore(validityBeginDate);
    certGen.setNotAfter(validityEndDate);
    certGen.setPublicKey(keyPair.getPublic());
    certGen.setSignatureAlgorithm("SHA256WithRSA");

    cert = certGen.generate(keyPair.getPrivate());

    return cert;
}

From source file:org.apache.accumulo.test.util.CertUtils.java

private KeyPair generateKeyPair() throws NoSuchAlgorithmException, NoSuchProviderException {
    KeyPairGenerator gen = KeyPairGenerator.getInstance(encryptionAlgorithm);
    gen.initialize(keysize);/*  w ww.  ja v  a 2  s . co m*/
    return gen.generateKeyPair();
}

From source file:org.opendaylight.aaa.cert.impl.ODLMdsalKeyTool.java

public KeyStore createKeyStoreWithSelfSignCert(final String keyStoreName, final String keyStorePwd,
        final String dName, final String keyAlias, final int validity, final String keyAlg, final int keySize,
        final String signAlg) {
    try {//from w w w. j a  va  2  s .  c o m
        final KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(keyAlg);
        keyPairGenerator.initialize(keySize);
        final KeyPair keyPair = keyPairGenerator.generateKeyPair();
        final X509V3CertificateGenerator x509V3CertGen = new X509V3CertificateGenerator();
        x509V3CertGen.setSerialNumber(getSecureRandomeInt());
        x509V3CertGen.setIssuerDN(new X509Principal(dName));
        x509V3CertGen.setNotBefore(new Date(System.currentTimeMillis()));
        x509V3CertGen
                .setNotAfter(new Date(System.currentTimeMillis() + (KeyStoreConstant.DAY_TIME * validity)));
        x509V3CertGen.setSubjectDN(new X509Principal(dName));
        x509V3CertGen.setPublicKey(keyPair.getPublic());
        x509V3CertGen.setSignatureAlgorithm(signAlg);
        final X509Certificate x509Cert = x509V3CertGen.generateX509Certificate(keyPair.getPrivate());
        final KeyStore ctlKeyStore = KeyStore.getInstance("JKS");
        ctlKeyStore.load(null, keyStorePwd.toCharArray());
        ctlKeyStore.setKeyEntry(keyAlias, keyPair.getPrivate(), keyStorePwd.toCharArray(),
                new java.security.cert.Certificate[] { x509Cert });
        LOG.info("{} is created", keyStoreName);
        return ctlKeyStore;
    } catch (final NoSuchAlgorithmException | InvalidKeyException | SecurityException | SignatureException
            | KeyStoreException | CertificateException | IOException e) {
        LOG.error("Fatal error creating keystore", e);
        return null;
    }
}

From source file:net.maritimecloud.identityregistry.utils.CertificateUtil.java

/**
 * Generates a keypair (public and private) based on Elliptic curves.
 * //  ww  w.ja  v a 2  s.c  o m
 * @return The generated keypair
 */
public static KeyPair generateKeyPair() {
    ECGenParameterSpec ecGenSpec = new ECGenParameterSpec("secp384r1");
    KeyPairGenerator g;
    try {
        g = KeyPairGenerator.getInstance("ECDSA", BC_PROVIDER_NAME);
    } catch (NoSuchAlgorithmException | NoSuchProviderException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
    try {
        g.initialize(ecGenSpec, new SecureRandom());
    } catch (InvalidAlgorithmParameterException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
    KeyPair pair = g.generateKeyPair();
    return pair;
}

From source file:ie.peternagy.jcrypto.algo.EllipticCurveWrapper.java

/**
 * Generate a set of Elliptic Curve keys
 *//*w ww  . j a v  a 2  s .  co m*/
public void generateKeys() {
    tryLoadKeys();
    if (isInitialized(true) && isInitialized(false)) {
        return;
    }

    try {
        ECGenParameterSpec ecGenSpec = new ECGenParameterSpec(EC_CURVE);
        KeyPairGenerator g = KeyPairGenerator.getInstance(ALGORITHM_NAME);
        g.initialize(ecGenSpec, CryptoSecurityUtil.getSecureRandom());
        KeyPair pair = g.generateKeyPair();
        privateKey = pair.getPrivate();
        publicKey = pair.getPublic();

        writeKeys();
    } catch (NoSuchAlgorithmException | InvalidAlgorithmParameterException ex) {
        Logger.getLogger(EllipticCurveWrapper.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:org.apache.stratos.keystore.mgt.KeyStoreGenerator.java

/**
 * This method generates the keypair and stores it in the keystore
 *
 * @param keyStore A keystore instance//from   w w w.  ja v a  2 s. com
 * @return Generated public key for the tenant
 * @throws KeyStoreMgtException Error when generating key pair
 */
private X509Certificate generateKeyPair(KeyStore keyStore) throws KeyStoreMgtException {
    try {
        CryptoUtil.getDefaultCryptoUtil();
        //generate key pair
        KeyPairGenerator keyPairGenerator = null;
        keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        keyPairGenerator.initialize(1024);
        KeyPair keyPair = keyPairGenerator.generateKeyPair();

        // Common Name and alias for the generated certificate
        String commonName = "CN=" + tenantDomain + ", OU=None, O=None L=None, C=None";

        //generate certificates
        X509V3CertificateGenerator v3CertGen = new X509V3CertificateGenerator();
        v3CertGen.setSerialNumber(BigInteger.valueOf(new SecureRandom().nextInt()));
        v3CertGen.setIssuerDN(new X509Principal(commonName));
        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(commonName));
        v3CertGen.setPublicKey(keyPair.getPublic());
        v3CertGen.setSignatureAlgorithm("MD5WithRSAEncryption");
        X509Certificate PKCertificate = v3CertGen.generateX509Certificate(keyPair.getPrivate());

        //add private key to KS
        keyStore.setKeyEntry(tenantDomain, keyPair.getPrivate(), password.toCharArray(),
                new java.security.cert.Certificate[] { PKCertificate });
        return PKCertificate;
    } catch (Exception ex) {
        String msg = "Error while generating the certificate for tenant :" + tenantDomain + ".";
        log.error(msg, ex);
        throw new KeyStoreMgtException(msg, ex);
    }

}

From source file:org.sonatype.sisu.encryptor.RsaAesEncryptor.java

public void generateKeys(OutputStream publicKeyOut, OutputStream privateKeyOut)
        throws GeneralSecurityException, IOException {
    KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");

    SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
    generator.initialize(KEY_SIZE * 8, random);

    KeyPair keyPair = generator.generateKeyPair();

    OutputStream privateOut = new Base64OutputStream(privateKeyOut);
    PrivateKey privateKey = keyPair.getPrivate();
    privateOut.write(privateKey.getEncoded());
    IOUtil.close(privateOut);//from  w  w  w . ja v  a 2  s.c o m

    OutputStream publicOut = new Base64OutputStream(publicKeyOut);
    PublicKey publicKey = keyPair.getPublic();
    publicOut.write(publicKey.getEncoded());
    IOUtil.close(publicOut);
}

From source file:hudson.cli.Connection.java

public KeyAgreement diffieHellman(boolean side, int keySize) throws IOException, GeneralSecurityException {
    KeyPair keyPair;/*from w  w  w  .  j  a v a 2s  . c om*/
    PublicKey otherHalf;

    if (side) {
        AlgorithmParameterGenerator paramGen = AlgorithmParameterGenerator.getInstance("DH");
        paramGen.init(keySize);

        KeyPairGenerator dh = KeyPairGenerator.getInstance("DH");
        dh.initialize(paramGen.generateParameters().getParameterSpec(DHParameterSpec.class));
        keyPair = dh.generateKeyPair();

        // send a half and get a half
        writeKey(keyPair.getPublic());
        otherHalf = KeyFactory.getInstance("DH").generatePublic(readKey());
    } else {
        otherHalf = KeyFactory.getInstance("DH").generatePublic(readKey());

        KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("DH");
        keyPairGen.initialize(((DHPublicKey) otherHalf).getParams());
        keyPair = keyPairGen.generateKeyPair();

        // send a half and get a half
        writeKey(keyPair.getPublic());
    }

    KeyAgreement ka = KeyAgreement.getInstance("DH");
    ka.init(keyPair.getPrivate());
    ka.doPhase(otherHalf, true);

    return ka;
}