List of usage examples for java.security KeyPairGenerator initialize
public void initialize(AlgorithmParameterSpec params) throws InvalidAlgorithmParameterException
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); return keyGenerator.generateKeyPair(); }
From source file:it.scoppelletti.programmerpower.security.CryptoUtils.java
/** * Restituisce un generatore di coppie di chiavi (pubblica, privata). * /*from www. j a v a2 s. c om*/ * <H4>1. Proprietà</H4> * * <P><TABLE WIDTH="100%" BORDER="1" CELLPADDING="5"> * <THEAD> * <TR> * <TH>Proprietà</TH> * <TH>Descrizione</TH> * </TR> * </THEAD> * <TBODY> * <TR> * <TD>{@code alg}</TD> * <TD>Codice dell’algoritmo di crittografia.</TD> * </TR> * <TR> * <TD>{@code param.factory}</TD> * <TD>Nome della classe di factory dei parametri specifici * dell’algoritmo; la classe deve implementare * l’interfaccia {@code AlgorithmParameterSpecFactory} e * può prevedere altre proprietà.</TD> * </TR> * <TR> * <TD>{@code param.factory.prefix}</TD> * <TD>Eventuale prefisso da applicare al nome delle proprietà * interrogate dal provider {@code param.factory}.</TD> * </TR> * <TR> * <TD>{@code key.size}</TD> * <TD>Dimensione della chiave (numero di bit).</TD> * </TR> * <TR> * <TD COLSPAN="2">Le proprietà {@code param.factory} e * {@code key.size} non possono essere entrambe impostate; se nessuna * delle due proprietà è impostata, il generatore * sarà inizializzato con i parametri di default definiti dallo * specifico provider JCA.</TD> * </TR> * </TBODY> * </TABLE></P> * * @param props Proprietà. * @param prefix Prefisso da applicare al nome delle proprietà da * interrogare. Può essere {@code null}. * @return Oggetto. * @see it.scoppelletti.programmerpower.security.spi.AlgorithmParameterSpecFactory * @see <A HREF="{@docRoot}/it/scoppelletti/programmerpower/security/CryptoUtils.html#idAlg">Algoritmi * di crittografia</A> */ public static KeyPairGenerator getKeyPairGenerator(Properties props, String prefix) { int keySize; String alg, name; KeyPairGenerator gen; AlgorithmParameterSpec params; SecurityResources res = new SecurityResources(); if (props == null) { throw new ArgumentNullException("props"); } name = Strings.concat(prefix, CryptoUtils.PROP_KEYALGORITHM); alg = props.getProperty(name); if (Strings.isNullOrEmpty(alg)) { throw new ArgumentNullException(name); } params = CryptoUtils.getAlgorithmParameterSpec(props, prefix); keySize = CryptoUtils.getKeySize(props, prefix); if (params != null && keySize >= 0) { throw new IllegalArgumentException( res.getArgumentIncompatibilityException(Strings.concat(prefix, CryptoUtils.PROP_PARAMFACTORY), Strings.concat(prefix, CryptoUtils.PROP_KEYSIZE))); } try { gen = KeyPairGenerator.getInstance(alg); if (params != null) { gen.initialize(params); } if (keySize >= 0) { gen.initialize(keySize); } } catch (GeneralSecurityException ex) { throw SecurityUtils.toSecurityException(ex); } return gen; }
From source file:duthientan.mmanm.com.Main.java
private void BntGenerationKeyActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BntGenerationKeyActionPerformed // TODO add your handling code here: if (filePath.size() != 0) { progressBarCipher.setIndeterminate(true); new Thread(new Runnable() { @Override/*from www . ja v a 2 s. c o m*/ public void run() { try { Path path = Paths.get(filePath.get(0)); String srcParent = path.getParent().toString(); final KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); keyGen.initialize(2048); final KeyPair key = keyGen.generateKeyPair(); File privateKeyFile = new File(srcParent + "/private.key"); File publicKeyFile = new File(srcParent + "/public.key"); publicKeyFile.createNewFile(); publicKeyFile.createNewFile(); ObjectOutputStream publicKeyOS = new ObjectOutputStream( new FileOutputStream(publicKeyFile)); publicKeyOS.writeObject(key.getPublic()); publicKeyOS.close(); ObjectOutputStream privateKeyOS = new ObjectOutputStream( new FileOutputStream(privateKeyFile)); privateKeyOS.writeObject(key.getPrivate()); privateKeyOS.close(); progressBarCipher.setIndeterminate(false); JFrame frame = new JFrame("COMPLETED"); JOptionPane.showMessageDialog(frame, "Greneration Key File Completed"); } catch (IOException ex) { Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); } catch (NoSuchAlgorithmException ex) { Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); } } }).start(); } else { JFrame frame = new JFrame("ERROR"); JOptionPane.showMessageDialog(frame, "Please Choice File To Cipher Before Greneration Key"); } }
From source file:com.mirth.connect.server.controllers.DefaultConfigurationController.java
/** * Checks for an existing certificate to use for secure communication between the server and * client. If no certficate exists, this will generate a new one. * //from w w w. j a v a 2s . c o m */ private void generateDefaultCertificate(Provider provider, KeyStore keyStore, char[] keyPassword) throws Exception { final String certificateAlias = "mirthconnect"; if (!keyStore.containsAlias(certificateAlias)) { // Common CA and SSL cert attributes Date startDate = new Date(); // time from which certificate is valid Date expiryDate = DateUtils.addYears(startDate, 50); // time after which certificate is not valid KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA", provider); keyPairGenerator.initialize(2048); KeyPair caKeyPair = keyPairGenerator.generateKeyPair(); logger.debug("generated new key pair for CA cert using provider: " + provider.getName()); // Generate CA cert X500Name caSubjectName = new X500Name("CN=Mirth Connect Certificate Authority"); SubjectPublicKeyInfo caSubjectKey = new SubjectPublicKeyInfo( ASN1Sequence.getInstance(caKeyPair.getPublic().getEncoded())); X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(caSubjectName, BigInteger.ONE, startDate, expiryDate, caSubjectName, caSubjectKey); certBuilder.addExtension(org.bouncycastle.asn1.x509.Extension.basicConstraints, true, new BasicConstraints(0)); ContentSigner sigGen = new JcaContentSignerBuilder("SHA256withRSA").setProvider(provider) .build(caKeyPair.getPrivate()); Certificate caCert = new JcaX509CertificateConverter().setProvider(provider) .getCertificate(certBuilder.build(sigGen)); // Generate SSL cert KeyPair sslKeyPair = keyPairGenerator.generateKeyPair(); logger.debug("generated new key pair for SSL cert using provider: " + provider.getName()); X500Name sslSubjectName = new X500Name("CN=mirth-connect"); SubjectPublicKeyInfo sslSubjectKey = new SubjectPublicKeyInfo( ASN1Sequence.getInstance(sslKeyPair.getPublic().getEncoded())); X509v3CertificateBuilder sslCertBuilder = new X509v3CertificateBuilder(caSubjectName, new BigInteger(50, new SecureRandom()), startDate, expiryDate, sslSubjectName, sslSubjectKey); sslCertBuilder.addExtension(org.bouncycastle.asn1.x509.Extension.authorityKeyIdentifier, false, new AuthorityKeyIdentifier(caCert.getEncoded())); sslCertBuilder.addExtension(org.bouncycastle.asn1.x509.Extension.subjectKeyIdentifier, false, new SubjectKeyIdentifier(sslKeyPair.getPublic().getEncoded())); sigGen = new JcaContentSignerBuilder("SHA256withRSA").setProvider(provider) .build(caKeyPair.getPrivate()); Certificate sslCert = new JcaX509CertificateConverter().setProvider(provider) .getCertificate(sslCertBuilder.build(sigGen)); logger.debug("generated new certificate with serial number: " + ((X509Certificate) sslCert).getSerialNumber()); // add the generated SSL cert to the keystore using the key password keyStore.setKeyEntry(certificateAlias, sslKeyPair.getPrivate(), keyPassword, new Certificate[] { sslCert }); } else { logger.debug("found certificate in keystore"); } }
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 ww. j a v a2 s . c om 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.sakaiproject.lti13.LTI13Servlet.java
@Override public void init(ServletConfig config) throws ServletException { super.init(config); if (ltiService == null) { ltiService = (LTIService) ComponentManager.get("org.sakaiproject.lti.api.LTIService"); }/* w w w . ja v a2 s . co m*/ if (tokenKeyPair == null) { try { KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); keyGen.initialize(2048); tokenKeyPair = keyGen.genKeyPair(); } catch (NoSuchAlgorithmException ex) { Logger.getLogger(LTI13Servlet.class.getName()).log(Level.SEVERE, "Unable to generate tokenKeyPair", ex); } } }
From source file:org.ejbca.util.keystore.KeyStoreContainerBase.java
/** * @see org.ejbca.util.keystore.KeyStoreContainer#generate(java.lang.String, java.lang.String) *///from w w w . j a v a2 s. c o m private byte[] generateEC(final String name, final String keyEntryName) throws Exception { if (log.isTraceEnabled()) { log.trace(">generate EC: curve name " + name + ", keyEntryName " + keyEntryName); } // Generate the EC Keypair final KeyPairGenerator kpg = KeyPairGenerator.getInstance("EC", this.providerName); try { Provider prov = Security.getProvider(this.providerName); if (StringUtils.contains(prov.getClass().getName(), "iaik")) { throw new InvalidAlgorithmParameterException("IAIK ECC key generation not implemented."); /* ECDSAPrivateKey privateKeyTemplate = new ECDSAPrivateKey(); privateKeyTemplate.getSign().setBooleanValue(Boolean.TRUE); privateKeyTemplate.getToken().setBooleanValue(Boolean.FALSE); ECDSAPublicKey publicKeyTemplate = new ECDSAPublicKey(); publicKeyTemplate.getVerify().setBooleanValue(Boolean.TRUE); publicKeyTemplate.getToken().setBooleanValue(Boolean.FALSE); ObjectID eccCurveObjectID = new ObjectID(objectID); publicKeyTemplate.getEcdsaParams().setByteArrayValue(DerCoder.encode(eccCurveObjectID)); PKCS11KeyPairGenerationSpec keyPairGenerationSpec = new PKCS11KeyPairGenerationSpec(tokenManager, publicKeyTemplate, privateKeyTemplate, PKCS11Spec.USE_READ_WRITE_SESSION, PKCS11Spec.USE_USER_SESSION); keyPairGenerator.initialize(keyPairGenerationSpec); */ } else { kpg.initialize(new ECGenParameterSpec(name)); } } catch (InvalidAlgorithmParameterException e) { log.debug("EC name " + name + " not supported."); throw e; } final byte result[] = generate(kpg, keyEntryName, "SHA1withECDSA"); if (log.isTraceEnabled()) { log.trace("<generate: curve name " + name + ", keyEntryName " + keyEntryName); } return result; }
From source file:org.cesecore.keys.util.KeyStoreTools.java
private void generateEC(final String name, final String keyEntryName) throws InvalidAlgorithmParameterException { if (log.isTraceEnabled()) { log.trace(">generate EC: curve name " + name + ", keyEntryName " + keyEntryName); }/* ww w.ja v a 2s . co m*/ // Generate the EC Keypair KeyPairGenerator kpg; try { kpg = KeyPairGenerator.getInstance("EC", this.providerName); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException("Algorithm " + "EC" + "was not recognized.", e); } catch (NoSuchProviderException e) { throw new IllegalStateException("BouncyCastle was not found as a provider.", e); } try { Provider prov = Security.getProvider(this.providerName); if (StringUtils.contains(prov.getClass().getName(), "iaik")) { throw new InvalidAlgorithmParameterException("IAIK ECC key generation not implemented."); /* ECDSAPrivateKey privateKeyTemplate = new ECDSAPrivateKey(); privateKeyTemplate.getSign().setBooleanValue(Boolean.TRUE); privateKeyTemplate.getToken().setBooleanValue(Boolean.FALSE); ECDSAPublicKey publicKeyTemplate = new ECDSAPublicKey(); publicKeyTemplate.getVerify().setBooleanValue(Boolean.TRUE); publicKeyTemplate.getToken().setBooleanValue(Boolean.FALSE); ObjectID eccCurveObjectID = new ObjectID(objectID); publicKeyTemplate.getEcdsaParams().setByteArrayValue(DerCoder.encode(eccCurveObjectID)); PKCS11KeyPairGenerationSpec keyPairGenerationSpec = new PKCS11KeyPairGenerationSpec(tokenManager, publicKeyTemplate, privateKeyTemplate, PKCS11Spec.USE_READ_WRITE_SESSION, PKCS11Spec.USE_USER_SESSION); keyPairGenerator.initialize(keyPairGenerationSpec); */ } else { ECGenParameterSpec ecSpec = new ECGenParameterSpec(name); if (StringUtils.equals(name, "implicitlyCA")) { log.debug("Generating implicitlyCA encoded ECDSA key pair"); // If the keySpec is null, we have "implicitlyCA" defined EC parameters // The parameters were already installed when we installed the provider // We just make sure that ecSpec == null here ecSpec = null; } kpg.initialize(ecSpec); } } catch (InvalidAlgorithmParameterException e) { log.debug("EC name " + name + " not supported."); throw e; } generateKeyPair(kpg, keyEntryName, "SHA1withECDSA"); if (log.isTraceEnabled()) { log.trace("<generate: curve name " + name + ", keyEntryName " + keyEntryName); } }