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:org.jenkinsci.remoting.engine.HandlerLoopbackLoadStress.java

public HandlerLoopbackLoadStress(Config config)
        throws IOException, NoSuchAlgorithmException, CertificateException, KeyStoreException,
        UnrecoverableKeyException, KeyManagementException, OperatorCreationException {
    this.config = config;
    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();/*from  w w  w  .j  a  v  a 2  s  .  c om*/

    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 BlindTrustX509ExtendedTrustManager() }, null);

    mainHub = IOHub.create(executorService);
    // on windows there is a bug whereby you cannot mix ServerSockets and Sockets on the same selector
    acceptorHub = File.pathSeparatorChar == 59 ? IOHub.create(executorService) : mainHub;
    legacyHub = new NioChannelHub(executorService);
    executorService.submit(legacyHub);
    serverSocketChannel = ServerSocketChannel.open();

    JnlpProtocolHandler handler = null;
    for (JnlpProtocolHandler h : new JnlpProtocolHandlerFactory(executorService).withNioChannelHub(legacyHub)
            .withIOHub(mainHub).withSSLContext(context).withPreferNonBlockingIO(!config.bio)
            .withClientDatabase(new JnlpClientDatabase() {
                @Override
                public boolean exists(String clientName) {
                    return true;
                }

                @Override
                public String getSecretOf(@Nonnull String clientName) {
                    return secretFor(clientName);
                }
            }).withSSLClientAuthRequired(false).handlers()) {
        if (config.name.equals(h.getName())) {
            handler = h;
            break;
        }
    }
    if (handler == null) {
        throw new RuntimeException("Unknown handler: " + config.name);
    }
    this.handler = handler;

    acceptor = new Acceptor(serverSocketChannel);
    runtimeMXBean = ManagementFactory.getRuntimeMXBean();
    operatingSystemMXBean = ManagementFactory.getOperatingSystemMXBean();
    _getProcessCpuTime = _getProcessCpuTime(operatingSystemMXBean);
    garbageCollectorMXBeans = new ArrayList<GarbageCollectorMXBean>(
            ManagementFactory.getGarbageCollectorMXBeans());
    Collections.sort(garbageCollectorMXBeans, new Comparator<GarbageCollectorMXBean>() {
        @Override
        public int compare(GarbageCollectorMXBean o1, GarbageCollectorMXBean o2) {
            return o1.getName().compareTo(o2.getName());
        }
    });
    stats = new Stats();
}

From source file:org.wso2.carbon.certificate.mgt.core.impl.CertificateGenerator.java

public X509Certificate generateX509Certificate() throws KeystoreException {

    CommonUtil commonUtil = new CommonUtil();
    Date validityBeginDate = commonUtil.getValidityStartDate();
    Date validityEndDate = commonUtil.getValidityEndDate();

    Security.addProvider(new BouncyCastleProvider());

    try {//from ww w  .j  a  va 2  s  . c o m
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(CertificateManagementConstants.RSA,
                CertificateManagementConstants.PROVIDER);
        keyPairGenerator.initialize(CertificateManagementConstants.RSA_KEY_LENGTH, new SecureRandom());
        KeyPair pair = keyPairGenerator.generateKeyPair();
        X500Principal principal = new X500Principal(CertificateManagementConstants.DEFAULT_PRINCIPAL);

        X509v3CertificateBuilder certificateBuilder = new JcaX509v3CertificateBuilder(principal,
                CommonUtil.generateSerialNumber(), validityBeginDate, validityEndDate, principal,
                pair.getPublic());
        ContentSigner contentSigner = new JcaContentSignerBuilder(CertificateManagementConstants.SHA256_RSA)
                .setProvider(CertificateManagementConstants.PROVIDER).build(pair.getPrivate());
        X509Certificate certificate = new JcaX509CertificateConverter()
                .setProvider(CertificateManagementConstants.PROVIDER)
                .getCertificate(certificateBuilder.build(contentSigner));

        // cert.checkValidity();

        certificate.verify(certificate.getPublicKey());

        List<org.wso2.carbon.certificate.mgt.core.bean.Certificate> certificates = new ArrayList<>();
        org.wso2.carbon.certificate.mgt.core.bean.Certificate certificateToStore = new org.wso2.carbon.certificate.mgt.core.bean.Certificate();
        certificateToStore.setTenantId(PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId());
        certificateToStore.setCertificate(certificate);
        certificates.add(certificateToStore);
        saveCertInKeyStore(certificates);

        return certificate;
    } catch (NoSuchAlgorithmException e) {
        String errorMsg = "No such algorithm found when generating certificate";
        throw new KeystoreException(errorMsg, e);
    } catch (NoSuchProviderException e) {
        String errorMsg = "No such provider found when generating certificate";
        throw new KeystoreException(errorMsg, e);
    } catch (OperatorCreationException e) {
        String errorMsg = "Issue in operator creation when generating certificate";
        throw new KeystoreException(errorMsg, e);
    } catch (CertificateExpiredException e) {
        String errorMsg = "Certificate expired after generating certificate";
        throw new KeystoreException(errorMsg, e);
    } catch (CertificateNotYetValidException e) {
        String errorMsg = "Certificate not yet valid when generating certificate";
        throw new KeystoreException(errorMsg, e);
    } catch (CertificateException e) {
        String errorMsg = "Certificate issue occurred when generating certificate";
        throw new KeystoreException(errorMsg, e);
    } catch (InvalidKeyException e) {
        String errorMsg = "Invalid key used when generating certificate";
        throw new KeystoreException(errorMsg, e);
    } catch (SignatureException e) {
        String errorMsg = "Signature related issue occurred when generating certificate";
        throw new KeystoreException(errorMsg, e);
    }
}

From source file:com.cws.esolutions.security.dao.certmgmt.impl.CertificateManagerImpl.java

/**
 * @see com.cws.esolutions.security.dao.certmgmt.interfaces.ICertificateManager#createCertificateRequest(List, String, int, int)
 *//*  w w  w  .  j  a v a2  s.  com*/
public synchronized File createCertificateRequest(final List<String> subjectData, final String storePassword,
        final int validityPeriod, final int keySize) throws CertificateManagementException {
    final String methodName = ICertificateManager.CNAME
            + "#createCertificateRequest(final List<String> subjectData, final String storePassword, final int validityPeriod, final int keySize) throws CertificateManagementException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("Value: {}", subjectData);
        DEBUGGER.debug("Value: {}", validityPeriod);
        DEBUGGER.debug("Value: {}", keySize);
    }

    final File rootDirectory = certConfig.getRootDirectory();
    final String signatureAlgorithm = certConfig.getSignatureAlgorithm();
    final String certificateAlgorithm = certConfig.getCertificateAlgorithm();
    final File privateKeyDirectory = FileUtils
            .getFile(certConfig.getPrivateKeyDirectory() + "/" + subjectData.get(0));
    final File publicKeyDirectory = FileUtils
            .getFile(certConfig.getPublicKeyDirectory() + "/" + subjectData.get(0));
    final File csrDirectory = FileUtils.getFile(certConfig.getCsrDirectory() + "/" + subjectData.get(0));
    final File storeDirectory = FileUtils.getFile(certConfig.getStoreDirectory() + "/" + subjectData.get(0));
    final X500Name x500Name = new X500Name("CN=" + subjectData.get(0) + ",OU=" + subjectData.get(1) + ",O="
            + subjectData.get(2) + ",L=" + subjectData.get(3) + ",ST=" + subjectData.get(4) + ",C="
            + subjectData.get(5) + ",E=" + subjectData.get(6));

    if (DEBUG) {
        DEBUGGER.debug("rootDirectory: {}", rootDirectory);
        DEBUGGER.debug("signatureAlgorithm: {}", signatureAlgorithm);
        DEBUGGER.debug("certificateAlgorithm: {}", certificateAlgorithm);
        DEBUGGER.debug("privateKeyDirectory: {}", privateKeyDirectory);
        DEBUGGER.debug("publicKeyDirectory: {}", publicKeyDirectory);
        DEBUGGER.debug("csrDirectory: {}", csrDirectory);
        DEBUGGER.debug("storeDirectory: {}", storeDirectory);
        DEBUGGER.debug("x500Name: {}", x500Name);
    }

    File csrFile = null;
    JcaPEMWriter csrPemWriter = null;
    JcaPEMWriter publicKeyWriter = null;
    JcaPEMWriter privateKeyWriter = null;
    FileOutputStream csrFileStream = null;
    FileOutputStream keyStoreStream = null;
    FileOutputStream publicKeyFileStream = null;
    FileOutputStream privateKeyFileStream = null;
    OutputStreamWriter csrFileStreamWriter = null;
    OutputStreamWriter privateKeyStreamWriter = null;
    OutputStreamWriter publicKeyStreamWriter = null;

    try {
        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore.load(null, storePassword.toCharArray());

        if (DEBUG) {
            DEBUGGER.debug("KeyStore: {}", keyStore);
        }

        SecureRandom random = new SecureRandom();
        KeyPairGenerator keyGenerator = KeyPairGenerator.getInstance(certificateAlgorithm);
        keyGenerator.initialize(keySize, random);

        if (DEBUG) {
            DEBUGGER.debug("KeyGenerator: {}", keyGenerator);
        }

        KeyPair keyPair = keyGenerator.generateKeyPair();

        if (DEBUG) {
            DEBUGGER.debug("KeyPair: {}", keyPair);
        }

        if (keyPair != null) {
            final Signature sig = Signature.getInstance(signatureAlgorithm);
            final PrivateKey privateKey = keyPair.getPrivate();
            final PublicKey publicKey = keyPair.getPublic();

            if (DEBUG) {
                DEBUGGER.debug("Signature: {}", sig);
                DEBUGGER.debug("PrivateKey: {}", privateKey);
                DEBUGGER.debug("PublicKey: {}", publicKey);
            }

            sig.initSign(privateKey, random);
            ContentSigner signGen = new JcaContentSignerBuilder(signatureAlgorithm).build(privateKey);

            if (DEBUG) {
                DEBUGGER.debug("ContentSigner: {}", signGen);
            }

            Calendar expiry = Calendar.getInstance();
            expiry.add(Calendar.DAY_OF_YEAR, validityPeriod);

            if (DEBUG) {
                DEBUGGER.debug("Calendar: {}", expiry);
            }

            CertificateFactory certFactory = CertificateFactory.getInstance(certConfig.getCertificateType());

            if (DEBUG) {
                DEBUGGER.debug("CertificateFactory: {}", certFactory);
            }

            X509Certificate[] issuerCert = new X509Certificate[] { (X509Certificate) certFactory
                    .generateCertificate(new FileInputStream(certConfig.getIntermediateCertificateFile())) };

            if (DEBUG) {
                DEBUGGER.debug("X509Certificate[]: {}", (Object) issuerCert);
            }

            keyStore.setCertificateEntry(certConfig.getRootCertificateName(), certFactory.generateCertificate(
                    new FileInputStream(FileUtils.getFile(certConfig.getRootCertificateFile()))));
            keyStore.setCertificateEntry(certConfig.getIntermediateCertificateName(),
                    certFactory.generateCertificate(new FileInputStream(
                            FileUtils.getFile(certConfig.getIntermediateCertificateFile()))));

            PKCS10CertificationRequestBuilder builder = new JcaPKCS10CertificationRequestBuilder(x500Name,
                    publicKey);

            if (DEBUG) {
                DEBUGGER.debug("PKCS10CertificationRequestBuilder: {}", builder);
            }

            PKCS10CertificationRequest csr = builder.build(signGen);

            if (DEBUG) {
                DEBUGGER.debug("PKCS10CertificationRequest: {}", csr);
            }

            // write private key
            File privateKeyFile = FileUtils.getFile(privateKeyDirectory + "/" + subjectData.get(0)
                    + SecurityServiceConstants.PRIVATEKEY_FILE_EXT);

            if (DEBUG) {
                DEBUGGER.debug("privateKeyFile: {}", privateKeyFile);
            }

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

            privateKeyFileStream = new FileOutputStream(privateKeyFile);
            privateKeyStreamWriter = new OutputStreamWriter(privateKeyFileStream);

            if (DEBUG) {
                DEBUGGER.debug("privateKeyFileStream: {}", privateKeyFileStream);
                DEBUGGER.debug("privateKeyStreamWriter: {}", privateKeyStreamWriter);
            }

            privateKeyWriter = new JcaPEMWriter(privateKeyStreamWriter);
            privateKeyWriter.writeObject(privateKey);
            privateKeyWriter.flush();
            privateKeyStreamWriter.flush();
            privateKeyFileStream.flush();

            // write public key
            File publicKeyFile = FileUtils.getFile(publicKeyDirectory + "/" + subjectData.get(0)
                    + SecurityServiceConstants.PUBLICKEY_FILE_EXT);

            if (DEBUG) {
                DEBUGGER.debug("publicKeyFile: {}", publicKeyFile);
            }

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

            publicKeyFileStream = new FileOutputStream(publicKeyFile);
            publicKeyStreamWriter = new OutputStreamWriter(publicKeyFileStream);

            if (DEBUG) {
                DEBUGGER.debug("publicKeyFileStream: {}", publicKeyFileStream);
                DEBUGGER.debug("publicKeyStreamWriter: {}", publicKeyStreamWriter);
            }

            publicKeyWriter = new JcaPEMWriter(publicKeyStreamWriter);
            publicKeyWriter.writeObject(publicKey);
            publicKeyWriter.flush();
            publicKeyStreamWriter.flush();
            publicKeyFileStream.flush();

            // write csr
            csrFile = FileUtils
                    .getFile(csrDirectory + "/" + subjectData.get(0) + SecurityServiceConstants.CSR_FILE_EXT);

            if (DEBUG) {
                DEBUGGER.debug("csrFile: {}", csrFile);
            }

            if (!(csrFile.createNewFile())) {
                throw new IOException("Failed to store CSR file");
            }

            csrFileStream = new FileOutputStream(csrFile);
            csrFileStreamWriter = new OutputStreamWriter(csrFileStream);

            if (DEBUG) {
                DEBUGGER.debug("publicKeyFileStream: {}", publicKeyFileStream);
                DEBUGGER.debug("publicKeyStreamWriter: {}", publicKeyStreamWriter);
            }

            csrPemWriter = new JcaPEMWriter(csrFileStreamWriter);
            csrPemWriter.writeObject(csr);
            csrPemWriter.flush();
            csrFileStreamWriter.flush();
            csrFileStream.flush();

            File keyStoreFile = FileUtils
                    .getFile(storeDirectory + "/" + subjectData.get(0) + "." + KeyStore.getDefaultType());

            if (DEBUG) {
                DEBUGGER.debug("keyStoreFile: {}", keyStoreFile);
            }

            keyStoreStream = FileUtils.openOutputStream(keyStoreFile);

            if (DEBUG) {
                DEBUGGER.debug("keyStoreStream: {}", keyStoreStream);
            }

            keyStore.setKeyEntry(subjectData.get(0), (Key) keyPair.getPrivate(), storePassword.toCharArray(),
                    issuerCert);
            keyStore.store(keyStoreStream, storePassword.toCharArray());
            keyStoreStream.flush();

            if (DEBUG) {
                DEBUGGER.debug("KeyStore: {}", keyStore);
            }
        } else {
            throw new CertificateManagementException("Failed to generate keypair. Cannot continue.");
        }
    } catch (FileNotFoundException fnfx) {
        throw new CertificateManagementException(fnfx.getMessage(), fnfx);
    } catch (IOException iox) {
        throw new CertificateManagementException(iox.getMessage(), iox);
    } catch (NoSuchAlgorithmException nsax) {
        throw new CertificateManagementException(nsax.getMessage(), nsax);
    } catch (IllegalStateException isx) {
        throw new CertificateManagementException(isx.getMessage(), isx);
    } catch (InvalidKeyException ikx) {
        throw new CertificateManagementException(ikx.getMessage(), ikx);
    } catch (OperatorCreationException ocx) {
        throw new CertificateManagementException(ocx.getMessage(), ocx);
    } catch (KeyStoreException ksx) {
        throw new CertificateManagementException(ksx.getMessage(), ksx);
    } catch (CertificateException cx) {
        throw new CertificateManagementException(cx.getMessage(), cx);
    } finally {
        if (csrFileStreamWriter != null) {
            IOUtils.closeQuietly(csrFileStreamWriter);
        }

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

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

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

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

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

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

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

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

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

    return csrFile;
}

From source file:com.otterca.common.crypto.acceptance.X509CertificateBuilderAcceptanceTest.java

/**
 * Default constructor.//from   www.  j  a  v  a2  s. c  o  m
 * 
 * @throws Exception
 */
protected X509CertificateBuilderAcceptanceTest() throws GeneralSecurityException, InvalidNameException,
        URISyntaxException, UnknownHostException, IOException {
    certUtil = new X509CertificateUtilImpl();

    TimeZone.setDefault(TimeZone.getTimeZone("UTC"));

    // create key pairs. this is for testing so we use 512-bit keys for
    // speed.
    KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
    keyPairGen.initialize(512);
    keyPair = keyPairGen.generateKeyPair();
    issuerKeyPair = keyPairGen.generateKeyPair();
    grandfatherKeyPair = keyPairGen.generateKeyPair();

    notBefore = Calendar.getInstance();
    notBefore.set(Calendar.MINUTE, 0);
    notBefore.set(Calendar.SECOND, 0);
    notBefore.set(Calendar.MILLISECOND, 0);
    notAfter = Calendar.getInstance();
    notAfter.setTime(notBefore.getTime());
    notAfter.add(Calendar.YEAR, 1);

    expectedGeneralNameUri1 = new com.otterca.common.crypto.GeneralName.URI("http://example.com");
    expectedGeneralNameUri2 = new com.otterca.common.crypto.GeneralName.URI("ldap://example.net");
    expectedGeneralNameDir = new com.otterca.common.crypto.GeneralName.Directory("C=US,ST=AK,C=Anchorage");
    expectedGeneralNameEmail = new com.otterca.common.crypto.GeneralName.Email("bob@example.com");
    expectedGeneralNameDns = new com.otterca.common.crypto.GeneralName.DNS("example.com");
    expectedGeneralNameIpAddress = new com.otterca.common.crypto.GeneralName.IpAddress("127.0.0.1");
}

From source file:org.texai.x509.X509Utils.java

/** Creates a random 3072 bit RSA key pair.
 * @return a random 3072 bit RSA key pair
 * @throws NoSuchAlgorithmException when an invalid algorithm is given
 * @throws NoSuchProviderException  when an invalid provider is given
 * @throws InvalidAlgorithmParameterException when an invalid algorithm parameter is given
 *//*from w w w .j  a v  a  2  s .co m*/
public static KeyPair generateRSAKeyPair3072()
        throws NoSuchAlgorithmException, NoSuchProviderException, InvalidAlgorithmParameterException {
    final KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA", BOUNCY_CASTLE_PROVIDER);
    final AlgorithmParameterSpec algorithmParameterSpec = new RSAKeyGenParameterSpec(3072,
            RSAKeyGenParameterSpec.F4);
    keyPairGenerator.initialize(algorithmParameterSpec, getSecureRandom());
    return keyPairGenerator.generateKeyPair();
}

From source file:org.texai.x509.X509Utils.java

/** Creates a random 2048 bit RSA key pair.
 * @return a random 2048 bit RSA key pair
 * @throws NoSuchAlgorithmException when an invalid algorithm is given
 * @throws NoSuchProviderException  when an invalid provider is given
 * @throws InvalidAlgorithmParameterException when an invalid algorithm parameter is given
 *//*from  w w  w.  j  a  v  a 2  s.  c o m*/
public static KeyPair generateRSAKeyPair2048()
        throws NoSuchAlgorithmException, NoSuchProviderException, InvalidAlgorithmParameterException {
    final KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA", BOUNCY_CASTLE_PROVIDER);
    final AlgorithmParameterSpec algorithmParameterSpec = new RSAKeyGenParameterSpec(2048,
            RSAKeyGenParameterSpec.F4);
    keyPairGenerator.initialize(algorithmParameterSpec, getSecureRandom());
    return keyPairGenerator.generateKeyPair();
}

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);//  www  .  ja va  2s. co  m
    return keyGenerator.generateKeyPair();
}

From source file:net.sourceforge.msscodefactory.cflib.v2_1.CFLib.Tip.CFTipEnvelopeHandler.java

public void initServerKeys() throws NoSuchAlgorithmException, InvalidKeyException, NoSuchPaddingException,
        IllegalBlockSizeException {
    if (serverKeyPair == null) {
        KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
        kpg.initialize(2048, new SecureRandom());
        serverKeyPair = kpg.generateKeyPair();
    }/*from   ww w . j ava2 s.  c  o  m*/

    byte encodedPKey[] = getEncodedServerPublicKey();
    String encoded = new String(Base64.encodeBase64(encodedPKey));
    serverInfo.setServerLoginKey(encoded);
}

From source file:org.hyperledger.fabric.sdk.security.CryptoPrimitives.java

private KeyPair generateKey(String encryptionName, String curveName) throws CryptoException {
    try {/*from  w  w  w.j a v a  2s . com*/
        ECGenParameterSpec ecGenSpec = new ECGenParameterSpec(curveName);
        KeyPairGenerator g = SECURITY_PROVIDER == null ? KeyPairGenerator.getInstance(encryptionName)
                : KeyPairGenerator.getInstance(encryptionName, SECURITY_PROVIDER);
        g.initialize(ecGenSpec, new SecureRandom());
        return g.generateKeyPair();
    } catch (Exception exp) {
        throw new CryptoException("Unable to generate key pair", exp);
    }
}

From source file:com.l2jfree.loginserver.manager.LoginManager.java

/**
 * Private constructor to avoid direct instantiation.
 * Initialize a key generator.//from   w w w.j  a  v  a  2s .  c  o  m
 */
private LoginManager() {
    try {
        _log.info("LoginManager: initializing.");

        _hackProtection = new FastMap<InetAddress, FailedLoginAttempt>();

        _keyPairs = new ScrambledKeyPair[10];

        _service = (AccountsServices) L2Registry.getBean("AccountsServices");

        _connections = new FastList<L2Client>();

        KeyPairGenerator keygen = null;

        try {
            keygen = KeyPairGenerator.getInstance("RSA");
            RSAKeyGenParameterSpec spec = new RSAKeyGenParameterSpec(1024, RSAKeyGenParameterSpec.F4);
            keygen.initialize(spec);
        } catch (GeneralSecurityException e) {
            _log.fatal("Error in RSA setup:", e);
            _log.info("Server shutting down now");
            System.exit(1);
            return;
        }

        //generate the initial set of keys
        for (int i = 0; i < 10; i++) {
            _keyPairs[i] = new ScrambledKeyPair(keygen.generateKeyPair());
        }
        _log.info("LoginManager: Cached 10 KeyPairs for RSA communication");

        testCipher((RSAPrivateKey) _keyPairs[0].getPair().getPrivate());

        // Store keys for blowfish communication
        generateBlowFishKeys();
    } catch (GeneralSecurityException e) {
        _log.fatal("FATAL: Failed initializing LoginManager. Reason: " + e.getMessage(), e);
        System.exit(1);
    }

}