List of usage examples for java.security KeyPairGenerator getInstance
public static KeyPairGenerator getInstance(String algorithm) throws NoSuchAlgorithmException
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 ava 2s . c o 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:com.mastercard.mcbp.utils.crypto.CryptoServiceImpl.java
/** * {@inheritDoc}//from w ww. j av a 2 s . co m */ @Override public final void warmUp() { final byte[] inputMac = getRandom(DEFAULT_BLOCK_SIZE * 5); final byte[] desKey = getRandom(16); byte[] mac; try { mac = mac(inputMac, desKey); mac = des3(mac, desKey, Mode.ENCRYPT); } catch (McbpCryptoException e) { // We can ignore here if something goes wrong e.printStackTrace(); return; } final KeyPairGenerator kpg; try { kpg = KeyPairGenerator.getInstance("RSA"); } catch (NoSuchAlgorithmException e) { // We can ignore here if something goes wrong e.printStackTrace(); return; } // TODO: Refine the warm up function as with Random Key (or random data) the library // may return exceptions (on Android only). final String p = "CDCF9FDA4FC8BDBE4F641A39CD858BF0C64C80CC2055C041FF32B53E6BD8DC51B3" + "AFB13BF0D5E5DAB7537C63A84D3C19"; final String q = "C89EB6CFA22566083268CE3F975850E0F3695FF199791A27394EB8E9137619C6DA" + "65056F4D9BA4D733ACED9108F48443"; final String dp = "8935153C35307E7EDF98117BDE5907F5D98855DD6AE3D58154CC78D447E5E8367" + "7CA7627F5E3EE91CF8CFD97C588D2BB"; final String dq = "85BF248A6C18EEB0219B342A64E58B40A2463FF66650BC1A26347B460CF966849" + "198AE4A33BD188F77C89E60B0A302D7"; final String a = "BDFF1436301672F1B29C3EC7A4C6C4A5F54058A5925393BEAFB1EAA83050BBF27E" + "C745ACBF2BA0B10FBE89E99B057725"; final int privateModulusSize; try { privateModulusSize = initRsaPrivateKey(ByteArray.of(p), ByteArray.of(q), ByteArray.of(dp), ByteArray.of(dq), ByteArray.of(a)); } catch (final McbpCryptoException e) { // We can ignore here if something goes wrong e.printStackTrace(); return; } final byte[] rsaEncryptedData; try { rsaEncryptedData = rsa(new byte[privateModulusSize]); } catch (McbpCryptoException e) { // We can ignore here if something goes wrong e.printStackTrace(); return; } final byte[] inputHash = new byte[rsaEncryptedData.length + mac.length]; System.arraycopy(mac, 0, inputHash, 0, mac.length); System.arraycopy(rsaEncryptedData, 0, inputHash, mac.length, rsaEncryptedData.length); try { System.out.println("Crypto library warmed up: " + ByteArray.of(sha1(inputHash)).getByte(0)); } catch (McbpCryptoException e) { e.printStackTrace(); } }
From source file:org.alfresco.extension.countersign.signature.RepositoryManagedSignatureProvider.java
/** * Create a keystore for this user to be used for document signing, store it associated with the user's * person node//from w w w .j av a 2 s .co m * * @param person * @param password * * @return a Java KeyStore object suitable for document signing * @throws NoSuchAlgorithmException * @throws NoSuchProviderException * @throws KeyStoreException * @throws IOException * @throws CertificateException */ private KeyStore createUserKeyStore(NodeRef person, String password) throws NoSuchAlgorithmException, NoSuchProviderException, KeyStoreException, CertificateException, IOException { // get the alias from the configuration String alias = config.getProperty(RepositoryManagedSignatureProviderFactory.ALIAS); // initialize key generator KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); SecureRandom random = SecureRandom.getInstance("SHA1PRNG", "SUN"); keyGen.initialize(2048, random); // generate a keypair KeyPair pair = keyGen.generateKeyPair(); PrivateKey priv = pair.getPrivate(); PublicKey pub = pair.getPublic(); // generate the user certificate Certificate cert = generateCertificate(pair, person); // get the ca cert used to sign and create cert chain KeyStore trustedKs = getTrustedKeyStore(); Certificate[] caChain = getCaCertChain(trustedKs); Certificate[] certChain = new Certificate[caChain.length + 1]; certChain[0] = cert; for (int i = 0; i < caChain.length; i++) { certChain[i + 1] = caChain[i]; } // create keystore, adding private key and cert chain KeyStore ks = KeyStore.getInstance("pkcs12"); ks.load(null, password.toCharArray()); ks.setKeyEntry(alias, priv, password.toCharArray(), certChain); // save the keystore saveUserKeyStore(person, ks, password); // also save the public key separately, will need it // for later validaiton activities saveUserPublicKey(person, pub); // return the generated keystore return ks; }
From source file:edu.uiuc.ncsa.myproxy.MyProxyLogon.java
/** * Retrieves credentials from the MyProxy server. *//*w ww .j a v a 2 s. c om*/ public void getCredentials() throws IOException, GeneralSecurityException { KeyPairGenerator keyGenerator = KeyPairGenerator.getInstance(keyAlg); keyGenerator.initialize(getKeySize()); this.keypair = keyGenerator.genKeyPair(); MyPKCS10CertRequest pkcs10 = CertUtil.createCertRequest(this.keypair, pkcs10SigAlgName, DN, pkcs10Provider); getCredentials(pkcs10.getEncoded()); }
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; }
From source file:com.owncloud.android.utils.EncryptionUtils.java
public static KeyPair generateKeyPair() throws NoSuchAlgorithmException { KeyPairGenerator keyGen = KeyPairGenerator.getInstance(RSA); keyGen.initialize(2048, new SecureRandom()); return keyGen.generateKeyPair(); }
From source file:cl.nic.dte.util.XMLUtil.java
public static AUTORIZACIONDocument generateAuthorization(AUTORIZACIONDocument template, PrivateKey pKey) throws NoSuchAlgorithmException, SignatureException, TransformerException, InvalidKeyException, IOException {//from ww w .ja va 2 s . c o m // Generation of keys KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA"); kpg.initialize(1024); KeyPair kp = kpg.generateKeyPair(); CAFType caf = template.getAUTORIZACION().getCAF(); CAFType.DA.RSAPK rsapk = caf.getDA().addNewRSAPK(); rsapk.setM(((RSAPublicKey) kp.getPublic()).getModulus().toByteArray()); rsapk.setE(((RSAPublicKey) kp.getPublic()).getPublicExponent().toByteArray()); ResourceBundle labels = ResourceBundle.getBundle("cl.nic.dte.resources.VerifyResults"); Signature sig = null; if (pKey.getAlgorithm().equals("RSA")) { sig = Signature.getInstance("SHA1withRSA"); caf.addNewFRMA().setAlgoritmo("SHA1withRSA"); } else if (pKey.getAlgorithm().equals("DSA")) { sig = Signature.getInstance("SHA1withDSA"); caf.addNewFRMA().setAlgoritmo("SHA1withDSA"); } else { throw new NoSuchAlgorithmException( labels.getString("ALGORITHM_NOT_SUPPORTED").replaceAll("%1", pKey.getAlgorithm())); } template.getAUTORIZACION() .setRSASK("-----BEGIN RSA PRIVATE KEY-----\n" + new String(Base64.encodeBase64(kp.getPrivate().getEncoded(), true)) + "-----END RSA PRIVATE KEY-----\n"); template.getAUTORIZACION() .setRSAPUBK("-----BEGIN RSA PUBLIC KEY-----\n" + new String(Base64.encodeBase64(kp.getPublic().getEncoded(), true)) + "-----END RSA PUBLIC KEY-----\n"); sig.initSign(pKey); sig.update(XMLUtil.getCleaned(caf.getDA())); caf.getFRMA().setByteArrayValue(Base64.encodeBase64(sig.sign())); return template; }
From source file:org.dasein.cloud.google.compute.server.ServerSupport.java
@Override public @Nonnull VirtualMachine launch(@Nonnull VMLaunchOptions withLaunchOptions) throws CloudException, InternalException { APITrace.begin(getProvider(), "launchVM"); // windows-cloud_windows-server-2012-r2-dc-v20150629 validateLaunchOptions(withLaunchOptions); // this will exception out on problem. try {//w w w . j ava2 s . com Compute gce = provider.getGoogleCompute(); GoogleMethod method = new GoogleMethod(provider); String hostName = getCapabilities().getVirtualMachineNamingConstraints() .convertToValidName(withLaunchOptions.getHostName(), Locale.US); Instance instance = new Instance(); instance.setName(hostName); instance.setDescription(withLaunchOptions.getDescription()); if (withLaunchOptions.getStandardProductId().contains("+")) { instance.setMachineType(getProduct(withLaunchOptions.getStandardProductId()).getDescription()); } else { instance.setMachineType(getProduct( withLaunchOptions.getStandardProductId() + "+" + withLaunchOptions.getDataCenterId()) .getDescription()); } MachineImage image = provider.getComputeServices().getImageSupport() .getImage(withLaunchOptions.getMachineImageId()); AttachedDisk rootVolume = new AttachedDisk(); rootVolume.setBoot(Boolean.TRUE); rootVolume.setType("PERSISTENT"); rootVolume.setMode("READ_WRITE"); AttachedDiskInitializeParams params = new AttachedDiskInitializeParams(); // do not use withLaunchOptions.getFriendlyName() it is non compliant!!! params.setDiskName(hostName); // Not Optimum solution, update in core should come next release to have this be part of MachineImage try { String[] parts = withLaunchOptions.getMachineImageId().split("_"); Image img = gce.images().get(parts[0], parts[1]).execute(); Long size = img.getDiskSizeGb(); String diskSizeGb = size.toString(); if (null == diskSizeGb) { diskSizeGb = img.getUnknownKeys().get("diskSizeGb").toString(); } Long MinimumDiskSizeGb = Long.valueOf(diskSizeGb).longValue(); params.setDiskSizeGb(MinimumDiskSizeGb); } catch (Exception e) { params.setDiskSizeGb(10L); } if ((image != null) && (image.getTag("contentLink") != null)) params.setSourceImage((String) image.getTag("contentLink")); else throw new CloudException("Problem getting the contentLink tag value from the image for " + withLaunchOptions.getMachineImageId()); rootVolume.setInitializeParams(params); List<AttachedDisk> attachedDisks = new ArrayList<AttachedDisk>(); attachedDisks.add(rootVolume); if (withLaunchOptions.getVolumes().length > 0) { for (VolumeAttachment volume : withLaunchOptions.getVolumes()) { AttachedDisk vol = new AttachedDisk(); vol.setBoot(Boolean.FALSE); vol.setType("PERSISTENT"); vol.setMode("READ_WRITE"); vol.setAutoDelete(Boolean.FALSE); vol.setKind("compute#attachedDisk"); if (null != volume.getExistingVolumeId()) { vol.setDeviceName(volume.getExistingVolumeId()); vol.setSource(provider.getComputeServices().getVolumeSupport() .getVolume(volume.getExistingVolumeId()).getMediaLink()); } else { VolumeCreateOptions volumeOptions = volume.getVolumeToCreate(); volumeOptions.setDataCenterId(withLaunchOptions.getDataCenterId()); String newDisk = provider.getComputeServices().getVolumeSupport() .createVolume(volume.getVolumeToCreate()); vol.setDeviceName(newDisk); vol.setSource( provider.getComputeServices().getVolumeSupport().getVolume(newDisk).getMediaLink()); } attachedDisks.add(vol); } } instance.setDisks(attachedDisks); AccessConfig nicConfig = new AccessConfig(); nicConfig.setName("External NAT"); nicConfig.setType("ONE_TO_ONE_NAT");//Currently the only type supported if (withLaunchOptions.getStaticIpIds().length > 0) { nicConfig.setNatIP(withLaunchOptions.getStaticIpIds()[0]); } List<AccessConfig> accessConfigs = new ArrayList<AccessConfig>(); accessConfigs.add(nicConfig); NetworkInterface nic = new NetworkInterface(); nic.setName("nic0"); if (null != withLaunchOptions.getVlanId()) { VLAN vlan = provider.getNetworkServices().getVlanSupport().getVlan(withLaunchOptions.getVlanId()); nic.setNetwork(vlan.getTag("contentLink")); } else { nic.setNetwork( provider.getNetworkServices().getVlanSupport().getVlan("default").getTag("contentLink")); } nic.setAccessConfigs(accessConfigs); List<NetworkInterface> nics = new ArrayList<NetworkInterface>(); nics.add(nic); instance.setNetworkInterfaces(nics); instance.setCanIpForward(Boolean.FALSE); Scheduling scheduling = new Scheduling(); scheduling.setAutomaticRestart(Boolean.TRUE); scheduling.setOnHostMaintenance("TERMINATE"); instance.setScheduling(scheduling); Map<String, String> keyValues = new HashMap<String, String>(); if (withLaunchOptions.getBootstrapUser() != null && withLaunchOptions.getBootstrapKey() != null && !withLaunchOptions.getBootstrapUser().equals("") && !withLaunchOptions.getBootstrapKey().equals("")) { keyValues.put("sshKeys", withLaunchOptions.getBootstrapUser() + ":" + withLaunchOptions.getBootstrapKey()); } if (!withLaunchOptions.getMetaData().isEmpty()) { for (Map.Entry<String, Object> entry : withLaunchOptions.getMetaData().entrySet()) { keyValues.put(entry.getKey(), (String) entry.getValue()); } } if (!keyValues.isEmpty()) { Metadata metadata = new Metadata(); ArrayList<Metadata.Items> items = new ArrayList<Metadata.Items>(); for (Map.Entry<String, String> entry : keyValues.entrySet()) { Metadata.Items item = new Metadata.Items(); item.set("key", entry.getKey()); if ((entry.getValue() == null) || (entry.getValue().isEmpty() == true) || (entry.getValue().equals(""))) item.set("value", ""); // GCE HATES nulls... else item.set("value", entry.getValue()); items.add(item); } // https://github.com/GoogleCloudPlatform/compute-image-packages/tree/master/google-startup-scripts if (null != withLaunchOptions.getUserData()) { Metadata.Items item = new Metadata.Items(); item.set("key", "startup-script"); item.set("value", withLaunchOptions.getUserData()); items.add(item); } metadata.setItems(items); instance.setMetadata(metadata); } Tags tags = new Tags(); ArrayList<String> tagItems = new ArrayList<String>(); tagItems.add(hostName); // Each tag must be 1-63 characters long, and comply with RFC1035 tags.setItems(tagItems); instance.setTags(tags); String vmId = ""; try { Operation job = gce.instances().insert(provider.getContext().getAccountNumber(), withLaunchOptions.getDataCenterId(), instance).execute(); vmId = method.getOperationTarget(provider.getContext(), job, GoogleOperationType.ZONE_OPERATION, "", withLaunchOptions.getDataCenterId(), false); } catch (IOException ex) { if (ex.getClass() == GoogleJsonResponseException.class) { GoogleJsonResponseException gjre = (GoogleJsonResponseException) ex; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else throw new CloudException("An error occurred launching the instance: " + ex.getMessage()); } catch (Exception e) { if ((e.getMessage().contains("The resource")) && (e.getMessage().contains("disks")) && (e.getMessage().contains("already exists"))) { throw new CloudException( "A disk named '" + withLaunchOptions.getFriendlyName() + "' already exists."); } else { throw new CloudException(e); } } if (!vmId.equals("")) { VirtualMachine vm = getVirtualMachine(vmId); if (withLaunchOptions.getMachineImageId().toLowerCase().contains("windows")) { // Generate the public/private key pair for encryption and decryption. KeyPair keys = null; try { KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); keyGen.initialize(2048); keys = keyGen.genKeyPair(); } catch (NoSuchAlgorithmException e) { throw new InternalException(e); } resetPassword(vmId, withLaunchOptions.getDataCenterId(), keys); int retryCount = 20; while (retryCount-- > 0) { SerialPortOutput output = null; try { output = gce.instances().getSerialPortOutput(provider.getContext().getAccountNumber(), withLaunchOptions.getDataCenterId(), vmId).setPort(4).execute(); } catch (IOException e) { throw new CloudException(e); } System.out.println(output); // Get the last line - this will be a JSON string corresponding to the most recent password reset attempt. String[] entries = output.getContents().split("\n"); String outputEntry = entries[entries.length - 1]; // Parse output using the json-simple library. JSONParser parser = new JSONParser(); try { org.json.simple.JSONObject passwordDict = (org.json.simple.JSONObject) parser .parse(outputEntry); vm.setRootUser(passwordDict.get("userName").toString()); vm.setRootPassword( decryptPassword(passwordDict.get("encryptedPassword").toString(), keys)); break; } catch (Exception e) { } // ignore exception, just means metadata not yet avail. try { Thread.sleep(10000); } catch (InterruptedException e) { } } } return vm; } else { throw new CloudException( "Could not find the instance: " + withLaunchOptions.getFriendlyName() + " after launch."); } } finally { APITrace.end(); } }
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. c o m 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.streamsets.datacollector.credential.cyberark.TestWebServicesFetcher.java
private static KeyPair generateKeyPair(String algorithm) throws NoSuchAlgorithmException { KeyPairGenerator keyGen = KeyPairGenerator.getInstance(algorithm); keyGen.initialize(1024);/* w w w . jav a 2 s .com*/ return keyGen.genKeyPair(); }