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) throws InvalidAlgorithmParameterException 

Source Link

Document

Initializes the key pair generator using the specified parameter set and the SecureRandom implementation of the highest-priority installed provider as the source of randomness.

Usage

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 {/*ww w  .ja  v a  2s.co 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: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 ww.j a v a2  s. c  o  m
 * @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:com.l2jfree.loginserver.manager.GameServerManager.java

/**
 * Load RSA keys/*  ww  w  .  j  ava2 s  .c  om*/
 * @throws NoSuchAlgorithmException
 * @throws InvalidAlgorithmParameterException
 */
private void loadRSAKeys() throws NoSuchAlgorithmException, InvalidAlgorithmParameterException {
    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
    RSAKeyGenParameterSpec spec = new RSAKeyGenParameterSpec(512, RSAKeyGenParameterSpec.F4);
    keyGen.initialize(spec);

    _keyPairs = new KeyPair[KEYS_SIZE];
    for (int i = 0; i < KEYS_SIZE; i++) {
        _keyPairs[i] = keyGen.genKeyPair();
    }
    _log.info("GameServerManager: Cached " + _keyPairs.length + " RSA keys for Game Server communication.");
}

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

private KeyPair generateKeyPair() throws NoSuchAlgorithmException, NoSuchProviderException {
    KeyPairGenerator gen = KeyPairGenerator.getInstance(encryptionAlgorithm);
    gen.initialize(keysize);
    return gen.generateKeyPair();
}

From source file:com.microsoft.azure.keyvault.cryptography.RsaKey.java

public RsaKey(String kid, int keySize, Provider provider) throws NoSuchAlgorithmException {

    if (Strings.isNullOrWhiteSpace(kid)) {
        throw new IllegalArgumentException("kid");
    }/*from   w w  w  .  jav  a2 s.co m*/

    final KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA", provider);

    generator.initialize(keySize);

    _kid = kid;
    _keyPair = generator.generateKeyPair();
    _provider = provider;
}

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  ww w.j  ava  2s  . co m
        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.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();/*www.  ja v  a  2s  .c o m*/

    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();

    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.forgerock.openidm.selfservice.impl.SelfService.java

private SnapshotTokenHandlerFactory newTokenHandlerFactory() {
    return new SnapshotTokenHandlerFactory() {
        @Override// w w w  .  j  a  v a2 s  . c om
        public SnapshotTokenHandler get(SnapshotTokenConfig snapshotTokenConfig) {
            switch (snapshotTokenConfig.getType()) {
            case JwtTokenHandlerConfig.TYPE:
                return createJwtTokenHandler((JwtTokenHandlerConfig) snapshotTokenConfig);
            default:
                throw new IllegalArgumentException("Unknown type " + snapshotTokenConfig.getType());
            }
        }

        private SnapshotTokenHandler createJwtTokenHandler(JwtTokenHandlerConfig config) {
            try {
                SigningManager signingManager = new SigningManager();
                SigningHandler signingHandler = signingManager.newHmacSigningHandler(config.getSharedKey());

                KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(config.getKeyPairAlgorithm());
                keyPairGen.initialize(config.getKeyPairSize());

                return new JwtTokenHandler(config.getJweAlgorithm(), config.getEncryptionMethod(),
                        keyPairGen.generateKeyPair(), config.getJwsAlgorithm(), signingHandler,
                        config.getTokenLifeTimeInSeconds());

            } catch (NoSuchAlgorithmException nsaE) {
                throw new RuntimeException("Unable to create key pair for encryption", nsaE);
            }
        }
    };
}