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, Provider provider)
        throws NoSuchAlgorithmException 

Source Link

Document

Returns a KeyPairGenerator object that generates public/private key pairs for the specified algorithm.

Usage

From source file:org.apache.hadoop.yarn.server.resourcemanager.security.X509SecurityHandler.java

@Override
public void init(Configuration config) throws Exception {
    LOG.info("Initializing X.509 Security Handler");
    this.config = config;
    hopsTLSEnabled = config.getBoolean(CommonConfigurationKeys.IPC_SERVER_SSL_ENABLED,
            CommonConfigurationKeys.IPC_SERVER_SSL_ENABLED_DEFAULT);
    renewalExecutorService = rmAppSecurityManager.getRenewalExecutorService();

    String delayConfiguration = config.get(YarnConfiguration.RM_APP_CERTIFICATE_EXPIRATION_SAFETY_PERIOD,
            YarnConfiguration.DEFAULT_RM_APP_CERTIFICATE_RENEWER_DELAY);
    Pair<Long, TemporalUnit> delayIntervalUnit = rmAppSecurityManager.parseInterval(delayConfiguration,
            YarnConfiguration.RM_APP_CERTIFICATE_EXPIRATION_SAFETY_PERIOD);
    amountOfTimeToSubstractFromExpiration = delayIntervalUnit.getFirst();
    renewalUnitOfTime = delayIntervalUnit.getSecond();

    String confMonitorInterval = config.get(YarnConfiguration.RM_APP_CERTIFICATE_REVOCATION_MONITOR_INTERVAL,
            YarnConfiguration.DEFAULT_RM_APP_CERTIFICATE_REVOCATION_MONITOR_INTERVAL);
    Pair<Long, TemporalUnit> monitorIntervalUnit = rmAppSecurityManager.parseInterval(confMonitorInterval,
            YarnConfiguration.RM_APP_CERTIFICATE_REVOCATION_MONITOR_INTERVAL);
    revocationMonitorInterval = monitorIntervalUnit.getFirst();
    revocationUnitOfInterval = monitorIntervalUnit.getSecond();

    if (isHopsTLSEnabled()) {
        this.certificateLocalizationService = rmContext.getCertificateLocalizationService();
        rmAppSecurityActions = rmAppSecurityManager.getRmAppCertificateActions();
        keyPairGenerator = KeyPairGenerator.getInstance(KEY_ALGORITHM, SECURITY_PROVIDER);
        keyPairGenerator.initialize(KEY_SIZE);
    }/*  w  ww  .j av  a2  s  .c o  m*/
}

From source file:org.apache.hadoop.yarn.server.resourcemanager.security.TestHopsworksRMAppSecurityActions.java

private PKCS10CertificationRequest generateCSR(String cn) throws Exception {
    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA", "BC");
    keyPairGenerator.initialize(1024);/* w w w.j  av  a  2 s . c  o  m*/
    KeyPair keyPair = keyPairGenerator.genKeyPair();

    X500NameBuilder x500NameBuilder = new X500NameBuilder(BCStyle.INSTANCE);
    x500NameBuilder.addRDN(BCStyle.CN, cn);
    x500NameBuilder.addRDN(BCStyle.O, O);
    x500NameBuilder.addRDN(BCStyle.OU, OU);
    X500Name x500Name = x500NameBuilder.build();

    PKCS10CertificationRequestBuilder csrBuilder = new JcaPKCS10CertificationRequestBuilder(x500Name,
            keyPair.getPublic());
    return csrBuilder
            .build(new JcaContentSignerBuilder("SHA256withRSA").setProvider("BC").build(keyPair.getPrivate()));
}

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 www .ja v  a 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:org.panbox.core.crypto.CryptCore.java

public static KeyPair generateKeypair() {
    try {/*  w w w . jav  a2  s .  c  o  m*/
        KeyPairGenerator kpg = KeyPairGenerator.getInstance(KeyConstants.KEY_FACTORY, KeyConstants.PROV_BC);
        kpg.initialize(KeyConstants.ASYMMETRIC_KEYSIZE);
        KeyPair kp = kpg.generateKeyPair();
        return kp;
    } catch (NoSuchAlgorithmException e) {
        logger.error("Error during asymmetric key pair generation: " + e);
    } catch (NoSuchProviderException e) {
        logger.error("Error during asymmetric key pair generation: " + e);
    }
    return null;
}

From source file:com.thoughtworks.go.server.util.HttpTestUtil.java

private KeyPair generateKeyPair() {
    try {//from w w  w . ja  v a 2 s. c om
        KeyPair seed = KeyPairGenerator.getInstance("RSA", "BC").generateKeyPair();
        RSAPrivateKey privateSeed = (RSAPrivateKey) seed.getPrivate();
        RSAPublicKey publicSeed = (RSAPublicKey) seed.getPublic();
        KeyFactory fact = KeyFactory.getInstance("RSA", "BC");
        RSAPrivateKeySpec privateKeySpec = new RSAPrivateKeySpec(privateSeed.getModulus(),
                privateSeed.getPrivateExponent());
        RSAPublicKeySpec publicKeySpec = new RSAPublicKeySpec(publicSeed.getModulus(),
                publicSeed.getPublicExponent());
        return new KeyPair(fact.generatePublic(publicKeySpec), fact.generatePrivate(privateKeySpec));
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:org.ejbca.util.keystore.KeyStoreContainerBase.java

/** 
 * @see org.ejbca.util.keystore.KeyStoreContainer#generate(int, java.lang.String)
 *///from w w  w .j  a v a 2 s .  com
private byte[] generateRSA(final int keySize, final String keyEntryName) throws Exception {
    if (log.isTraceEnabled()) {
        log.trace(">generate: keySize " + keySize + ", keyEntryName " + keyEntryName);
    }
    // Generate the RSA Keypair
    final KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA", this.providerName);
    kpg.initialize(keySize);
    final byte result[] = generate(kpg, keyEntryName, "SHA1withRSA");
    if (log.isTraceEnabled()) {
        log.trace("<generate: keySize " + keySize + ", keyEntryName " + keyEntryName);
    }
    return result;
}

From source file:qauth.djd.qauthclient.main.ContentFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    Bundle args = getArguments();//from  w  w  w  .j  a  v  a  2 s. co  m
    if (args.getCharSequence(KEY_TITLE).toString().equals("Providers")) {

        View rootView = inflater.inflate(R.layout.providers_view_frag, container, false);

        mRecyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerView);
        mLayoutManager = new LinearLayoutManager(getActivity());
        mCurrentLayoutManagerType = LayoutManagerType.LINEAR_LAYOUT_MANAGER;

        if (savedInstanceState != null) {
            // Restore saved layout manager type.
            mCurrentLayoutManagerType = (LayoutManagerType) savedInstanceState
                    .getSerializable(KEY_LAYOUT_MANAGER);
        }
        setRecyclerViewLayoutManager(mCurrentLayoutManagerType);

        pAdapter = new ProviderAdapter(pDataset);
        mRecyclerView.setAdapter(pAdapter);

        final PackageManager pm = getActivity().getPackageManager();
        List<ApplicationInfo> packages = pm.getInstalledApplications(PackageManager.GET_META_DATA);

        for (ApplicationInfo packageInfo : packages) {
            //Log.i(TAG, "Installed package :" + packageInfo.packageName);
            //Log.i(TAG, "Source dir : " + packageInfo.sourceDir);
            //Log.i(TAG, "Launch Activity :" + pm.getLaunchIntentForPackage(packageInfo.packageName));

            if (packageInfo.packageName.equals("qauth.djd.dummyclient")) {
                Provider provider = new Provider("DummyClient", packageInfo.packageName);
                pDataset.add(provider);
                pAdapter.notifyDataSetChanged();
            }

        }

        //get local package names and cross reference with providers on server ("/provider/available")
        //display package names in listview
        //allow user to click on item to activate or deactivate
        // '-> have check box with progress bar indicating status

        return rootView;

    } else {

        View rootView = inflater.inflate(R.layout.recycler_view_frag, container, false);
        mRecyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerView);
        mLayoutManager = new LinearLayoutManager(getActivity());
        mCurrentLayoutManagerType = LayoutManagerType.LINEAR_LAYOUT_MANAGER;

        if (savedInstanceState != null) {
            // Restore saved layout manager type.
            mCurrentLayoutManagerType = (LayoutManagerType) savedInstanceState
                    .getSerializable(KEY_LAYOUT_MANAGER);
        }
        setRecyclerViewLayoutManager(mCurrentLayoutManagerType);

        wAdapter = new WatchAdapter(wDataset);
        mRecyclerView.setAdapter(wAdapter);

        FloatingActionButton fab = (FloatingActionButton) rootView.findViewById(R.id.fab);
        fab.attachToRecyclerView(mRecyclerView);

        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.i("test", "clicked!");

                AlertDialog.Builder builderSingle = new AlertDialog.Builder(getActivity());
                builderSingle.setIcon(R.drawable.ic_launcher);
                builderSingle.setTitle("Select Bluetooth Device");
                final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(getActivity(),
                        android.R.layout.select_dialog_singlechoice);
                new Thread(new Runnable() {
                    public void run() {
                        for (String s : getNodes()) {
                            arrayAdapter.add(s);
                        }
                    }
                }).start();
                builderSingle.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                builderSingle.setAdapter(arrayAdapter, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        String nodeId = arrayAdapter.getItem(which);
                        String privKey = null;
                        String pubKey = null;

                        try {
                            SecureRandom random = new SecureRandom();
                            RSAKeyGenParameterSpec spec = new RSAKeyGenParameterSpec(1024,
                                    RSAKeyGenParameterSpec.F4);
                            KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA", "SC");
                            generator.initialize(spec, random);
                            KeyPair pair = generator.generateKeyPair();
                            privKey = Base64.encodeToString(pair.getPrivate().getEncoded(), Base64.DEFAULT);
                            pubKey = Base64.encodeToString(pair.getPublic().getEncoded(), Base64.DEFAULT);
                        } catch (Exception e) {
                            Log.i("generate", "error: " + e);
                        }

                        //Log.i("keys", "priv key : " + privKey);

                        //String privKey = Base64.encodeToString(MainTabsActivity.privKey.getEncoded(), Base64.DEFAULT);
                        //String pubKey = Base64.encodeToString(MainTabsActivity.pubKey.getEncoded(), Base64.DEFAULT);

                        Keys keys = new Keys(privKey, pubKey);
                        ByteArrayOutputStream bos = new ByteArrayOutputStream();
                        ObjectOutput out = null;
                        try {
                            out = new ObjectOutputStream(bos);
                        } catch (Exception e) {
                        }
                        try {
                            out.writeObject(keys);
                        } catch (Exception e) {
                        }
                        byte b[] = bos.toByteArray();
                        try {
                            out.close();
                        } catch (Exception e) {
                        }
                        try {
                            bos.close();
                        } catch (Exception e) {
                        }

                        Wearable.MessageApi.sendMessage(mGoogleApiClient, nodeId, "REGISTER", b)
                                .setResultCallback(new ResultCallback<MessageApi.SendMessageResult>() {
                                    @Override
                                    public void onResult(MessageApi.SendMessageResult sendMessageResult) {
                                        if (!sendMessageResult.getStatus().isSuccess()) {
                                            Log.i("MessageApi", "Failed to send message with status code: "
                                                    + sendMessageResult.getStatus().getStatusCode());
                                        } else if (sendMessageResult.getStatus().isSuccess()) {
                                            Log.i("MessageApi", "onResult successful!");
                                        }
                                    }
                                });

                    }
                });
                builderSingle.show();

            }
        });

        mGoogleApiClient = new GoogleApiClient.Builder(getActivity()).addConnectionCallbacks(this)
                .addOnConnectionFailedListener(
                        new com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener() {
                            @Override
                            public void onConnectionFailed(ConnectionResult result) {
                                Log.i("mGoogleApiClient", "onConnectionFailed: " + result);
                            }
                        })
                // Request access only to the Wearable API
                .addApi(Wearable.API).build();
        mGoogleApiClient.connect();

        /*BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
                
        for(BluetoothDevice bt : pairedDevices)
        Log.i("BluetoothDevice", "pairedDevice: " + bt.toString());*/

        return rootView;

    }

}

From source file:org.wso2.carbon.device.mgt.iot.agent.firealarm.enrollment.EnrollmentManager.java

/**
 * This method creates the Public-Private Key pair for the current client.
 *
 * @return the generated KeyPair object//w  w  w  .j  a v  a 2 s . c o  m
 * @throws AgentCoreOperationException when the given Security Provider does not exist or the Algorithmn used to
 *                                     generate the key pair is invalid.
 */
private KeyPair generateKeyPair() throws AgentCoreOperationException {

    // Generate our key pair
    KeyPairGenerator keyPairGenerator;
    try {
        keyPairGenerator = KeyPairGenerator.getInstance(KEY_PAIR_ALGORITHM, PROVIDER);
        keyPairGenerator.initialize(KEY_SIZE, new SecureRandom(SEED));
    } catch (NoSuchAlgorithmException e) {
        String errorMsg = "Algorithm [" + KEY_PAIR_ALGORITHM + "] provided for KeyPairGenerator is invalid.";
        log.error(errorMsg);
        throw new AgentCoreOperationException(errorMsg, e);
    } catch (NoSuchProviderException e) {
        String errorMsg = "Provider [" + PROVIDER + "] provided for KeyPairGenerator does not exist.";
        log.error(errorMsg);
        throw new AgentCoreOperationException(errorMsg, e);
    }

    return keyPairGenerator.genKeyPair();
}

From source file:org.ejbca.util.keystore.KeyStoreContainerBase.java

/** 
 * @see org.ejbca.util.keystore.KeyStoreContainer#generate(int, java.lang.String)
 *///from w ww .  j a va  2  s . c  om
private byte[] generateDSA(final int keySize, final String keyEntryName) throws Exception {
    if (log.isTraceEnabled()) {
        log.trace(">generate: keySize " + keySize + ", keyEntryName " + keyEntryName);
    }
    // Generate the RSA Keypair
    final KeyPairGenerator kpg = KeyPairGenerator.getInstance("DSA", this.providerName);
    kpg.initialize(keySize);
    final byte result[] = generate(kpg, keyEntryName, "SHA1withDSA");
    if (log.isTraceEnabled()) {
        log.trace("<generate: keySize " + keySize + ", keyEntryName " + keyEntryName);
    }
    return result;
}

From source file:org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.enrollment.EnrollmentManager.java

/**
 * This method creates the Public-Private Key pair for the current client.
 *
 * @return the generated KeyPair object// w  w w.ja v a  2s  .c  om
 * @throws AgentCoreOperationException when the given Security Provider does not exist or the Algorithmn used to
 *                                     generate the key pair is invalid.
 */
private KeyPair generateKeyPair() throws AgentCoreOperationException {

    // Generate key pair
    KeyPairGenerator keyPairGenerator;
    try {
        keyPairGenerator = KeyPairGenerator.getInstance(KEY_PAIR_ALGORITHM, PROVIDER);
        keyPairGenerator.initialize(KEY_SIZE, new SecureRandom(SEED));
    } catch (NoSuchAlgorithmException e) {
        String errorMsg = "Algorithm [" + KEY_PAIR_ALGORITHM + "] provided for KeyPairGenerator is invalid.";
        log.error(errorMsg);
        throw new AgentCoreOperationException(errorMsg, e);
    } catch (NoSuchProviderException e) {
        String errorMsg = "Provider [" + PROVIDER + "] provided for KeyPairGenerator does not exist.";
        log.error(errorMsg);
        throw new AgentCoreOperationException(errorMsg, e);
    }

    return keyPairGenerator.genKeyPair();
}