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:test.be.fedict.eid.applet.RSATest.java

@Test
public void testPSS() throws Exception {
    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
    SecureRandom random = new SecureRandom();
    keyPairGenerator.initialize(new RSAKeyGenParameterSpec(1024, RSAKeyGenParameterSpec.F4), random);
    KeyPair keyPair = keyPairGenerator.generateKeyPair();
    PrivateKey privateKey = keyPair.getPrivate();
    PublicKey publicKey = keyPair.getPublic();

    Signature signature = Signature.getInstance("SHA256withRSA/PSS", "BC");

    byte[] data = "hello world".getBytes();

    signature.initSign(privateKey);//  w  ww .  jav a2  s  .  co m
    signature.update(data);
    byte[] signatureValue = signature.sign();

    LOG.debug("signature size: " + signatureValue.length);

    LOG.debug("signature value: " + new String(Hex.encodeHex(signatureValue)));

    signature.initVerify(publicKey);
    signature.update(data);
    boolean result = signature.verify(signatureValue);
    assertTrue(result);

    signature.initSign(privateKey);
    signature.update(data);
    byte[] signatureValue2 = signature.sign();

    LOG.debug("signature size: " + signatureValue2.length);

    LOG.debug("signature value: " + new String(Hex.encodeHex(signatureValue2)));

    assertFalse(Arrays.equals(signatureValue, signatureValue2));

    MessageDigest messageDigest = MessageDigest.getInstance("SHA-256", "BC");
    byte[] digest = messageDigest.digest(data);

    signature = Signature.getInstance("RAWRSASSA-PSS", "BC");
    signature.setParameter(new PSSParameterSpec("SHA-256", "MGF1", new MGF1ParameterSpec("SHA-256"), 32, 1));
    signature.initVerify(publicKey);
    signature.update(digest);
    result = signature.verify(signatureValue);
    assertTrue(result);
}

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

public boolean createKeyStoreWithSelfSignCert(final String keyStoreName, final String keyStorePwd,
        final String dName, final String keyAlias, final int validity) {
    try {//from w  ww . j a  va 2s.  c  om
        final KeyPairGenerator keyPairGenerator = KeyPairGenerator
                .getInstance(KeyStoreConstant.DEFAULT_KEY_ALG);
        keyPairGenerator.initialize(KeyStoreConstant.DEFAULT_KEY_SIZE);
        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(KeyStoreConstant.DEFAULT_SIGN_ALG);
        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 });
        final FileOutputStream fOutputStream = new FileOutputStream(workingDir + keyStoreName);
        ctlKeyStore.store(fOutputStream, keyStorePwd.toCharArray());
        LOG.info("{} is created", keyStoreName);
        return true;
    } catch (NoSuchAlgorithmException | InvalidKeyException | SecurityException | SignatureException
            | KeyStoreException | CertificateException | IOException e) {
        LOG.error("Fatal error creating key", e);
        return false;
    }
}

From source file:org.springframework.security.ldap.server.ApacheDsSSLContainer.java

public File getKeystore(File directory) throws Exception {

    KeyStore keyStore = KeyStore.getInstance("JKS");
    keyStore.load(null, null);/* ww  w. ja  va2  s  .c  o  m*/

    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
    keyPairGenerator.initialize(keysize);
    KeyPair keyPair = keyPairGenerator.generateKeyPair();
    X509Certificate[] chain = {
            getSelfCertificate(new X500Name(commonName, organizationalUnit, organization, city, state, country),
                    new Date(), (long) validity * 24 * 60 * 60, keyPair, "SHA256withRSA") };
    keyStore.setKeyEntry(alias, keyPair.getPrivate(), keyPass, chain);

    String keystoreName = "ldap.keystore";
    File keystore = new File(directory, keystoreName);
    if (!keystore.createNewFile()) {
        throw new FileNotFoundException("Unable to create file:" + keystore);
    }
    keyStore.store(new FileOutputStream(keystore, false), keyPass);
    return keystore;
}

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.cws.esolutions.security.dao.keymgmt.impl.FileKeyManager.java

/**
 * @see com.cws.esolutions.security.dao.keymgmt.interfaces.KeyManager#createKeys(java.lang.String)
 *///  w  w w  .  j  av  a2s .co  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.jenkinsci.remoting.protocol.ProtocolStackLoopbackLoadStress.java

public ProtocolStackLoopbackLoadStress(boolean nio, boolean ssl)
        throws IOException, NoSuchAlgorithmException, CertificateException, KeyStoreException,
        UnrecoverableKeyException, KeyManagementException, OperatorCreationException {
    KeyPairGenerator gen = KeyPairGenerator.getInstance("RSA");
    gen.initialize(2048); // maximum supported by JVM with export restrictions
    keyPair = gen.generateKeyPair();

    Date now = new Date();
    Date firstDate = new Date(now.getTime() + TimeUnit.DAYS.toMillis(10));
    Date lastDate = new Date(now.getTime() + TimeUnit.DAYS.toMillis(-10));

    SubjectPublicKeyInfo subjectPublicKeyInfo = SubjectPublicKeyInfo
            .getInstance(keyPair.getPublic().getEncoded());

    X500NameBuilder nameBuilder = new X500NameBuilder(BCStyle.INSTANCE);
    X500Name subject = nameBuilder.addRDN(BCStyle.CN, getClass().getSimpleName()).addRDN(BCStyle.C, "US")
            .build();/* www  .j  a  v a 2  s .c  o  m*/

    X509v3CertificateBuilder certGen = new X509v3CertificateBuilder(subject, BigInteger.ONE, firstDate,
            lastDate, subject, subjectPublicKeyInfo);

    JcaX509ExtensionUtils instance = new JcaX509ExtensionUtils();

    certGen.addExtension(X509Extension.subjectKeyIdentifier, false,
            instance.createSubjectKeyIdentifier(subjectPublicKeyInfo));

    ContentSigner signer = new JcaContentSignerBuilder("SHA1withRSA").setProvider(BOUNCY_CASTLE_PROVIDER)
            .build(keyPair.getPrivate());

    certificate = new JcaX509CertificateConverter().setProvider(BOUNCY_CASTLE_PROVIDER)
            .getCertificate(certGen.build(signer));

    char[] password = "password".toCharArray();

    KeyStore store = KeyStore.getInstance("jks");
    store.load(null, password);
    store.setKeyEntry("alias", keyPair.getPrivate(), password, new Certificate[] { certificate });

    KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    kmf.init(store, password);

    context = SSLContext.getInstance("TLS");
    context.init(kmf.getKeyManagers(),
            new TrustManager[] { new PublicKeyMatchingX509ExtendedTrustManager(keyPair.getPublic()) }, null);

    hub = IOHub.create(executorService);
    serverSocketChannel = ServerSocketChannel.open();
    acceptor = new Acceptor(serverSocketChannel, nio, ssl);
}

From source file:org.wso2.carbon.keystore.mgt.KeyStoreGenerator.java

/**
 * This method generates the keypair and stores it in the keystore
 *
 * @param keyStore A keystore instance//from www . j av a 2 s  . c om
 * @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(2048);
        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
        AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder()
                .find("MD5WithRSAEncryption");
        AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);
        AsymmetricKeyParameter privateKeyAsymKeyParam = PrivateKeyFactory
                .createKey(keyPair.getPrivate().getEncoded());
        SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded());
        ContentSigner sigGen = new BcRSAContentSignerBuilder(sigAlgId, digAlgId).build(privateKeyAsymKeyParam);

        Date notBefore = new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30);
        Date notAfter = new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 365 * 10));

        X509v3CertificateBuilder v3CertBuilder = new X509v3CertificateBuilder(new X500Name(commonName),
                BigInteger.valueOf(new SecureRandom().nextInt()), notBefore, notAfter, new X500Name(commonName),
                subPubKeyInfo);

        X509CertificateHolder certificateHolder = v3CertBuilder.build(sigGen);
        X509Certificate PKCertificate = new JcaX509CertificateConverter().setProvider("BC")
                .getCertificate(certificateHolder);

        //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: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.keycloak.testsuite.client.OIDCJwksClientRegistrationTest.java

@Test
public void testTwoClientsWithSameKid() throws Exception {
    // Create client with manually set "kid"
    OIDCClientRepresentation response = createClientWithManuallySetKid("a1");

    // Create client2
    OIDCClientRepresentation clientRep2 = createRep();

    clientRep2.setGrantTypes(Collections.singletonList(OAuth2Constants.CLIENT_CREDENTIALS));
    clientRep2.setTokenEndpointAuthMethod(OIDCLoginProtocol.PRIVATE_KEY_JWT);

    // Generate some random keys for client2
    KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
    generator.initialize(2048);//  www. j  ava2s  . c  om
    PublicKey client2PublicKey = generator.generateKeyPair().getPublic();

    // Set client2 with manually set "kid" to be same like kid of client1 (but keys for both clients are different)
    JSONWebKeySet keySet = new JSONWebKeySet();
    keySet.setKeys(new JWK[] { JWKBuilder.create().kid("a1").rs256(client2PublicKey) });

    clientRep2.setJwks(keySet);
    clientRep2 = reg.oidc().create(clientRep2);

    // Authenticate client1
    Map<String, String> generatedKeys = testingClient.testApp().oidcClientEndpoints().getKeysAsPem();
    assertAuthenticateClientSuccess(generatedKeys, response, "a1");

    // Assert item in publicKey cache for client1
    String expectedCacheKey = PublicKeyStorageUtils.getClientModelCacheKey(REALM_NAME, response.getClientId());
    Assert.assertTrue(testingClient.testing().cache(InfinispanConnectionProvider.KEYS_CACHE_NAME)
            .contains(expectedCacheKey));

    // Assert it's not possible to authenticate as client2 with the same "kid" like client1
    assertAuthenticateClientError(generatedKeys, clientRep2, "a1");
}

From source file:com.jonbanjo.cupsprint.CertificateActivity.java

public void doimport(View view) {
    try {//from   w  ww  . j a  v a 2  s . co  m
        String url = "https://" + host.getText().toString() + ":" + port.getText().toString();
        importButton.setEnabled(false);
        new importer().execute(url).get(3000, TimeUnit.MILLISECONDS);
    } catch (Exception e) {

    } finally {
        importButton.setEnabled(true);
    }
    if (certChain == null) {
        return;
    }

    for (X509Certificate cert : certChain) {
        try {
            cert.checkValidity();
        } catch (Exception e) {
            showToast(e.toString());
            return;
        }

    }
    String certString = certChain[0].toString();
    final String alias = certChain[0].getSubjectX500Principal().getName();
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle("Add Certificate?").setMessage(certString)
            .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    try {
                        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
                        keyPairGenerator.initialize(1024);
                        KeyPair keyPair = keyPairGenerator.generateKeyPair();
                        PrivateKey privateKey = keyPair.getPrivate();
                        trustStore.setKeyEntry(alias, privateKey, JfSSLScheme.password.toCharArray(),
                                certChain);
                        FileOutputStream outputStream = openFileOutput(JfSSLScheme.trustfile, MODE_PRIVATE);
                        trustStore.store(outputStream, JfSSLScheme.password.toCharArray());
                        outputStream.flush();
                        outputStream.close();
                        certListAdaptor.add(alias);
                    } catch (Exception e) {
                        System.out.println(e.toString());
                        return;
                    }
                }
            }).setNegativeButton("No", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    dialog.cancel();
                }
            });
    AlertDialog dialog = builder.create();
    dialog.show();

}