List of usage examples for java.security KeyPairGenerator generateKeyPair
public KeyPair generateKeyPair()
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 a2s . c o 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.guanxi.sp.engine.form.RegisterGuardFormController.java
/** * Creates an authenticated certificate chain for the specified X509 name * * @param x509DN X509 name to for which to create a certificate chain * @param keyType The type of the key, e.g. "RSA", "DSA" * @return Returns a CABean instance encapsulating certificate chain and key information * or null if an error occurred// ww w . j a v a2s.com */ private CABean createSignedCertificateChain(String x509DN, String keyType) { try { // Create a public/private keypair... KeyPairGenerator keyGen = KeyPairGenerator.getInstance(keyType); keyGen.initialize(1024, new SecureRandom()); KeyPair keypair = keyGen.generateKeyPair(); PrivateKey clientPrivateKey = keypair.getPrivate(); PublicKey clientPublicKey = keypair.getPublic(); // ...and a CSR from them... PKCS10CertificationRequest csr = generateRequest(x509DN, clientPublicKey, clientPrivateKey, keyType); // ...sign it KeyStore rootKS = loadRootKeyStore(); X509Certificate rootCert = (X509Certificate) rootKS.getCertificate(rootCAKeystoreAlias); if (rootCert == null) { logger.error("Can't get root certificate from CA keystore"); return null; } PrivateKey rootPrivKey = (PrivateKey) rootKS.getKey(rootCAKeystoreAlias, rootCAKeystorePassword.toCharArray()); X509Certificate[] signedChain = createSignedCert(rootCert, rootPrivKey, csr, keyType); //...package up the result... CABean caBean = new CABean(); caBean.setChain(signedChain); caBean.setCSRPrivateKey(clientPrivateKey); caBean.setSubjectDN(x509DN); // ...and send it back return caBean; } catch (Exception e) { logger.error(e); return null; } }
From source file:org.forgerock.openidm.security.impl.SecurityResourceProvider.java
/** * Generates a CSR request.//from w w w . jav a 2 s. c o m * * @param alias * @param algorithm * @param signatureAlgorithm * @param keySize * @param params * @return * @throws Exception */ protected Pair<PKCS10CertificationRequest, PrivateKey> generateCSR(String alias, String algorithm, String signatureAlgorithm, int keySize, JsonValue params) throws Exception { // Construct the distinguished name StringBuilder sb = new StringBuilder(); sb.append("CN=").append(params.get("CN").required().asString().replaceAll(",", "\\\\,")); sb.append(", OU=").append(params.get("OU").defaultTo("None").asString().replaceAll(",", "\\\\,")); sb.append(", O=").append(params.get("O").defaultTo("None").asString().replaceAll(",", "\\\\,")); sb.append(", L=").append(params.get("L").defaultTo("None").asString().replaceAll(",", "\\\\,")); sb.append(", ST=").append(params.get("ST").defaultTo("None").asString().replaceAll(",", "\\\\,")); sb.append(", C=").append(params.get("C").defaultTo("None").asString().replaceAll(",", "\\\\,")); // Create the principle subject name X509Principal subjectName = new X509Principal(sb.toString()); //store.getStore(). // Generate the key pair KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(algorithm); keyPairGenerator.initialize(keySize); KeyPair keyPair = keyPairGenerator.generateKeyPair(); PublicKey publicKey = keyPair.getPublic(); PrivateKey privateKey = keyPair.getPrivate(); // Generate the certificate request PKCS10CertificationRequest cr = new PKCS10CertificationRequest(signatureAlgorithm, subjectName, publicKey, null, privateKey); // Store the private key to use when the signed cert is return and updated logger.debug("Storing private key with alias {}", alias); storeKeyPair(alias, keyPair); return Pair.of(cr, privateKey); }
From source file:org.tolven.gatekeeper.CertificateHelper.java
private X509CertificatePrivateKeyPair createX509CertificatePrivateKeyPair(String email, String commonName, String organizationUnitName, String organizationName, String stateOrProvince) { String privateKeyAlgorithm = USER_PRIVATE_KEY_ALGORITHM_PROP; KeyPairGenerator keyPairGenerator; try {// w w w .j a v a2 s .c o m keyPairGenerator = KeyPairGenerator.getInstance(privateKeyAlgorithm); } catch (NoSuchAlgorithmException ex) { throw new RuntimeException("Could not get KeyPairGenerator for algorithm: " + privateKeyAlgorithm, ex); } int keySize = Integer.parseInt(USER_PRIVATE_KEY_LENGTH_PROP); keyPairGenerator.initialize(keySize); KeyPair keyPair = keyPairGenerator.generateKeyPair(); X500Principal x500Principal = getX500Principal(email, commonName, organizationUnitName, organizationName, stateOrProvince); return createSelfSignedCertificate(x500Principal, keyPair.getPublic(), keyPair.getPrivate()); }
From source file:org.signserver.server.cryptotokens.KeystoreCryptoTokenTest.java
/** * Tests that a worker just set up with a key store containing a new * key-pair and is activated manually gets status ACTIVE. * @throws Exception/* w ww.j av a 2 s . c o m*/ */ public void testActivateWithNewKeystore() throws Exception { LOG.info("testActivateWithNewKeystore"); final boolean autoActivate = false; final int workerId = WORKER_CMS; try { setCMSSignerPropertiesCombined(workerId, autoActivate); // Create a key-pair and certificate in the keystore FileOutputStream out = null; try { KeyStore ks = KeyStore.getInstance("PKCS12", "BC"); ks.load(null, null); // Generate key and issue certificate final KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA", "BC"); kpg.initialize(1024); final KeyPair keyPair = kpg.generateKeyPair(); X509Certificate[] chain = new X509Certificate[1]; chain[0] = getSelfCertificate("CN=TestActivateWithNewKeystore" + ", C=SE", (long) 30 * 24 * 60 * 60 * 365, keyPair); ks.setKeyEntry("newkey11", keyPair.getPrivate(), pin.toCharArray(), chain); out = new FileOutputStream(keystoreFile); ks.store(out, pin.toCharArray()); } finally { IOUtils.closeQuietly(out); } workerSession.setWorkerProperty(workerId, "DEFAULTKEY", "newkey11"); workerSession.reloadConfiguration(workerId); // Activate first so we can generate a key workerSession.activateSigner(workerId, pin); List<String> errors = workerSession.getStatus(workerId).getFatalErrors(); assertTrue("Fatal errors: " + errors, workerSession.getStatus(workerId).getFatalErrors().isEmpty()); } finally { FileUtils.deleteQuietly(keystoreFile); removeWorker(workerId); } }
From source file:org.signserver.server.cryptotokens.KeystoreCryptoTokenTest.java
/** * Test importing a new certificate chain to an existing keystore. * @throws Exception /*from ww w .ja v a2 s . c om*/ */ public void testImportCertificateChain() throws Exception { LOG.info("testImportCertificateChain"); final boolean autoActivate = false; final int workerId = WORKER_CMS; try { setCMSSignerPropertiesCombined(workerId, autoActivate); // Generate key and issue certificate final KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA", "BC"); kpg.initialize(1024); final KeyPair keyPair = kpg.generateKeyPair(); // Create a key-pair and certificate in the keystore FileOutputStream out = null; try { KeyStore ks = KeyStore.getInstance("PKCS12", "BC"); ks.load(null, null); final X509Certificate[] chain = new X509Certificate[1]; chain[0] = getSelfCertificate("CN=Test", (long) 30 * 24 * 60 * 60 * 365, keyPair); ks.setKeyEntry("newkey11", keyPair.getPrivate(), pin.toCharArray(), chain); out = new FileOutputStream(keystoreFile); ks.store(out, pin.toCharArray()); } finally { IOUtils.closeQuietly(out); } workerSession.setWorkerProperty(workerId, "DEFAULTKEY", "newkey11"); workerSession.reloadConfiguration(workerId); // Activate first so we can generate a key workerSession.activateSigner(workerId, pin); List<String> errors = workerSession.getStatus(workerId).getFatalErrors(); assertTrue("Fatal errors: " + errors, workerSession.getStatus(workerId).getFatalErrors().isEmpty()); // generate a new certificate final X509Certificate newCert = getSelfCertificate("CN=TestNew", (long) 30 * 24 * 60 * 60 * 365, keyPair); workerSession.importCertificateChain(workerId, Arrays.asList(newCert.getEncoded()), "newkey11", null); final Certificate readCert = workerSession.getSignerCertificate(workerId); assertTrue("Matching certificates", Arrays.equals(newCert.getEncoded(), readCert.getEncoded())); } finally { FileUtils.deleteQuietly(keystoreFile); removeWorker(workerId); } }
From source file:org.candlepin.sync.ExporterTest.java
private KeyPair createKeyPair() { KeyPair cpKeyPair = null;/*w w w. j a v a2 s . co m*/ try { KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); generator.initialize(2048); java.security.KeyPair newPair = generator.generateKeyPair(); cpKeyPair = new KeyPair(newPair.getPrivate(), newPair.getPublic()); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } return cpKeyPair; }
From source file:org.forgerock.openidm.security.impl.SecurityResourceProvider.java
/** * Generates a self signed certificate using the given properties. * * @param commonName the subject's common name * @param organization the subject's organization name * @param organizationUnit the subject's organization unit name * @param stateOrProvince the subject's state or province * @param country the subject's country code * @param locality the subject's locality * @param algorithm the algorithm to use * @param keySize the keysize to use//from www .j a v a 2s . co m * @param signatureAlgorithm the signature algorithm to use * @param validFrom when the certificate is valid from * @param validTo when the certificate is valid until * @return The generated certificate * @throws Exception */ protected Pair<X509Certificate, PrivateKey> generateCertificate(String commonName, String organization, String organizationUnit, String stateOrProvince, String country, String locality, String algorithm, int keySize, String signatureAlgorithm, String validFrom, String validTo) throws Exception { KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(algorithm); // "RSA","BC" keyPairGenerator.initialize(keySize); KeyPair keyPair = keyPairGenerator.generateKeyPair(); // Generate self-signed certificate X500NameBuilder builder = new X500NameBuilder(BCStyle.INSTANCE); builder.addRDN(BCStyle.C, country); builder.addRDN(BCStyle.ST, stateOrProvince); builder.addRDN(BCStyle.L, locality); builder.addRDN(BCStyle.OU, organizationUnit); builder.addRDN(BCStyle.O, organization); builder.addRDN(BCStyle.CN, commonName); Date notBefore = null; Date notAfter = null; if (validFrom == null) { notBefore = new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30); } else { DateTime notBeforeDateTime = DateUtil.getDateUtil().parseIfDate(validFrom); if (notBeforeDateTime == null) { throw new InternalServerErrorException("Invalid date format for 'validFrom' property"); } else { notBefore = notBeforeDateTime.toDate(); } } if (validTo == null) { Calendar date = Calendar.getInstance(); date.setTime(new Date()); date.add(Calendar.YEAR, 10); notAfter = date.getTime(); } else { DateTime notAfterDateTime = DateUtil.getDateUtil().parseIfDate(validTo); if (notAfterDateTime == null) { throw new InternalServerErrorException("Invalid date format for 'validTo' property"); } else { notAfter = notAfterDateTime.toDate(); } } BigInteger serial = BigInteger.valueOf(System.currentTimeMillis()); X509v3CertificateBuilder v3CertGen = new JcaX509v3CertificateBuilder(builder.build(), serial, notBefore, notAfter, builder.build(), keyPair.getPublic()); ContentSigner sigGen = new JcaContentSignerBuilder(signatureAlgorithm).setProvider(BC) .build(keyPair.getPrivate()); X509Certificate cert = new JcaX509CertificateConverter().setProvider(BC) .getCertificate(v3CertGen.build(sigGen)); cert.checkValidity(new Date()); cert.verify(cert.getPublicKey()); return Pair.of(cert, keyPair.getPrivate()); }
From source file:test.integ.be.e_contract.sts.CXFSTSClientTest.java
@Test public void testSelfSignedCertificateFails() throws Exception { SpringBusFactory bf = new SpringBusFactory(); Bus bus = bf.createBus("cxf-https-trust-all.xml"); BusFactory.setDefaultBus(bus);/*from w w w. j a v a 2 s .co m*/ // get the JAX-WS client URL wsdlLocation = CXFSTSClientTest.class.getResource("/example-localhost-sts.wsdl"); ExampleService exampleService = new ExampleService(wsdlLocation, new QName("urn:be:e-contract:sts:example", "ExampleService")); ExampleServicePortType port = exampleService.getExampleServicePort(); // set the web service address on the client stub BindingProvider bindingProvider = (BindingProvider) port; Map<String, Object> requestContext = bindingProvider.getRequestContext(); requestContext.put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, "https://localhost/iam/example"); KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); KeyPair keyPair = keyPairGenerator.generateKeyPair(); PrivateKey privateKey = keyPair.getPrivate(); PublicKey publicKey = keyPair.getPublic(); X509Certificate certificate = getCertificate(privateKey, publicKey); List<X509Certificate> certificates = new LinkedList<>(); certificates.add(certificate); requestContext.put(SecurityConstants.STS_CLIENT_SOAP12_BINDING, "true"); requestContext.put(SecurityConstants.SIGNATURE_CRYPTO, new ClientCrypto(privateKey, certificates)); requestContext.put(SecurityConstants.STS_TOKEN_USE_CERT_FOR_KEYINFO, "true"); requestContext.put(SecurityConstants.SIGNATURE_USERNAME, "username"); requestContext.put(SecurityConstants.CALLBACK_HANDLER, new ExampleSecurityPolicyCallbackHandler()); requestContext.put(SecurityConstants.PREFER_WSMEX_OVER_STS_CLIENT_CONFIG, "true"); // invoke the web service try { port.echo("hello world"); fail(); } catch (SOAPFaultException e) { // expected assertTrue(e.getMessage().contains("security token")); } bus.shutdown(true); }
From source file:test.integ.be.agiv.security.IPSTSTest.java
private KeyPair generateKeyPair() throws Exception { KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); SecureRandom random = new SecureRandom(); keyPairGenerator.initialize(new RSAKeyGenParameterSpec(1024, RSAKeyGenParameterSpec.F4), random); KeyPair keyPair = keyPairGenerator.generateKeyPair(); return keyPair; }