List of usage examples for javax.crypto KeyGenerator init
public final void init(int keysize)
From source file:org.tolven.security.password.PasswordHolder.java
private void generateSecretKey(File secretKeyFile) { if (getSecretKeyFile().exists()) { throw new RuntimeException("A secretkey file already exists at: " + getSecretKeyFile().getPath()); }/*w w w . j a v a 2 s .c o m*/ try { KeyGenerator keyGenerator = KeyGenerator.getInstance("DESede"); keyGenerator.init(112); secretKey = keyGenerator.generateKey(); String alias = getKeyStore().aliases().nextElement(); Certificate adminCert = getKeyStore().getCertificate(alias); PublicKey publicKey = adminCert.getPublicKey(); Cipher cipher = Cipher.getInstance(publicKey.getAlgorithm()); cipher.init(Cipher.WRAP_MODE, publicKey); byte[] encryptedSecretKey = cipher.wrap(secretKey); FileOutputStream out = null; try { out = new FileOutputStream(secretKeyFile); out.write(Base64.encodeBase64(encryptedSecretKey)); } finally { if (out != null) { out.close(); } } } catch (Exception ex) { throw new RuntimeException("Could not generate secret key for file: " + secretKeyFile.getPath(), ex); } }
From source file:org.opensmartgridplatform.adapter.protocol.dlms.application.services.SecurityKeyService.java
/** * Generates a new key that can be used as DLMS master key, authentication * key, global unicast encryption key, M-Bus Default key or M-Bus User key. * <p>/*w ww . java 2s. c o m*/ * The master keys (DLMS master or M-Bus Default) cannot be changed on a * device, but can be generated for use in tests or with simulated devices. * * @return a new 16-byte AES key. */ public byte[] generateKey() { try { final KeyGenerator keyGenerator = KeyGenerator.getInstance("AES"); keyGenerator.init(AES_GMC_128_KEY_SIZE); return keyGenerator.generateKey().getEncoded(); } catch (final NoSuchAlgorithmException e) { throw new AssertionError("Expected AES algorithm to be available for key generation.", e); } }
From source file:org.cesecore.keys.util.KeyStoreTools.java
/** Generates symmetric keys in the Keystore token. * /*from w w w .j ava 2s .c om*/ * @param algorithm symmetric algorithm specified in http://download.oracle.com/javase/1.5.0/docs/api/index.html, suggest AES, DESede or DES * @param keysize keysize of symmetric key, suggest 128 or 256 for AES, 64 for 168 for DESede and 64 for DES * @param keyEntryName the alias the key will get in the keystore * @throws NoSuchProviderException * @throws NoSuchAlgorithmException * @throws KeyStoreException */ public void generateKey(final String algorithm, final int keysize, final String keyEntryName) throws NoSuchAlgorithmException, NoSuchProviderException, KeyStoreException { KeyGenerator generator = KeyGenerator.getInstance(algorithm, this.providerName); generator.init(keysize); Key key = generator.generateKey(); setKeyEntry(keyEntryName, key, null); }
From source file:org.openhab.binding.loxone.internal.core.LxWsSecurityToken.java
private boolean initialize() { try {/*from w ww . j a v a 2s. co m*/ encryptionReady = false; tokenRefreshRetryCount = TOKEN_REFRESH_RETRY_COUNT; if (Cipher.getMaxAllowedKeyLength("AES") < 256) { return setError(LxOfflineReason.INTERNAL_ERROR, "Enable Java cryptography unlimited strength (see binding doc)."); } // generate a random key for the session KeyGenerator aesKeyGen = KeyGenerator.getInstance("AES"); aesKeyGen.init(256); aesKey = aesKeyGen.generateKey(); // generate an initialization vector secureRandom = new SecureRandom(); secureRandom.nextBytes(initVector); IvParameterSpec ivSpec = new IvParameterSpec(initVector); // initialize aes cipher for command encryption aesEncryptCipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); aesEncryptCipher.init(Cipher.ENCRYPT_MODE, aesKey, ivSpec); // initialize aes cipher for response decryption aesDecryptCipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); aesDecryptCipher.init(Cipher.DECRYPT_MODE, aesKey, ivSpec); // get token value from configuration storage token = (String) configuration.get(SETTINGS_TOKEN); logger.debug("[{}] Retrieved token value: {}", debugId, token); } catch (InvalidParameterException e) { return setError(LxOfflineReason.INTERNAL_ERROR, "Invalid parameter: " + e.getMessage()); } catch (NoSuchAlgorithmException e) { return setError(LxOfflineReason.INTERNAL_ERROR, "AES not supported on platform."); } catch (InvalidKeyException | NoSuchPaddingException | InvalidAlgorithmParameterException e) { return setError(LxOfflineReason.INTERNAL_ERROR, "AES cipher initialization failed."); } return true; }
From source file:org.guanxi.idp.service.SSOBase.java
/** * Adds encrypted assertions to a SAML2 Response * * @param encryptionCert the X509 certificate to use for encrypting the assertions * @param assertionDoc the assertions to encrypt * @param responseDoc the SAML2 Response to add the encrypted assertions to * @throws GuanxiException if an error occurs *//*from ww w. j a va 2 s . c o m*/ protected void addEncryptedAssertionsToResponse(X509Certificate encryptionCert, AssertionDocument assertionDoc, ResponseDocument responseDoc) throws GuanxiException { try { PublicKey keyEncryptKey = encryptionCert.getPublicKey(); // Generate a secret key KeyGenerator keyGenerator = KeyGenerator.getInstance("AES"); keyGenerator.init(128); SecretKey secretKey = keyGenerator.generateKey(); XMLCipher keyCipher = XMLCipher.getInstance(XMLCipher.RSA_OAEP); keyCipher.init(XMLCipher.WRAP_MODE, keyEncryptKey); Document domAssertionDoc = (Document) assertionDoc.newDomNode(xmlOptions); EncryptedKey encryptedKey = keyCipher.encryptKey(domAssertionDoc, secretKey); Element elementToEncrypt = domAssertionDoc.getDocumentElement(); XMLCipher xmlCipher = XMLCipher.getInstance(XMLCipher.AES_128); xmlCipher.init(XMLCipher.ENCRYPT_MODE, secretKey); // Add KeyInfo to the EncryptedData element EncryptedData encryptedDataElement = xmlCipher.getEncryptedData(); KeyInfo keyInfo = new KeyInfo(domAssertionDoc); keyInfo.add(encryptedKey); encryptedDataElement.setKeyInfo(keyInfo); // Encrypt the assertion xmlCipher.doFinal(domAssertionDoc, elementToEncrypt, false); // Go back into XMLBeans land... EncryptedDataDocument encryptedDataDoc = EncryptedDataDocument.Factory.parse(domAssertionDoc); // ...and add the encrypted assertion to the response responseDoc.getResponse().addNewEncryptedAssertion() .setEncryptedData(encryptedDataDoc.getEncryptedData()); // Look for the Response/EncryptedAssertion/EncryptedData/KeyInfo/EncryptedKey node... EncryptedDataType encryptedData = responseDoc.getResponse().getEncryptedAssertionArray(0) .getEncryptedData(); NodeList nodes = encryptedData.getKeyInfo().getDomNode().getChildNodes(); Node encryptedKeyNode = null; for (int c = 0; c < nodes.getLength(); c++) { encryptedKeyNode = nodes.item(c); if (encryptedKeyNode.getLocalName() != null) { if (encryptedKeyNode.getLocalName().equals("EncryptedKey")) break; } } // ...get a new KeyInfo ready... KeyInfoDocument keyInfoDoc = KeyInfoDocument.Factory.newInstance(); X509DataType x509Data = keyInfoDoc.addNewKeyInfo().addNewX509Data(); // ...and a useable version of the SP's encryption certificate... StringWriter sw = new StringWriter(); PEMWriter pemWriter = new PEMWriter(sw); pemWriter.writeObject(encryptionCert); pemWriter.close(); String x509 = sw.toString(); x509 = x509.replaceAll("-----BEGIN CERTIFICATE-----", ""); x509 = x509.replaceAll("-----END CERTIFICATE-----", ""); // ...add the encryption cert to the new KeyInfo... x509Data.addNewX509Certificate().setStringValue(x509); // ...and insert it into Response/EncryptedAssertion/EncryptedData/KeyInfo/EncryptedKey encryptedKeyNode.appendChild( encryptedKeyNode.getOwnerDocument().importNode(keyInfoDoc.getKeyInfo().getDomNode(), true)); } catch (NoSuchAlgorithmException nsae) { logger.error("AES encryption not available"); throw new GuanxiException(nsae); } catch (XMLEncryptionException xea) { logger.error("RSA_OAEP error with WRAP_MODE"); throw new GuanxiException(xea); } catch (Exception e) { logger.error("Error encyrpting the assertion"); throw new GuanxiException(e); } }
From source file:com.owncloud.android.ui.activity.FingerprintActivity.java
@TargetApi(Build.VERSION_CODES.M) protected void generateKey() { try {/*from w w w . j av a2 s . c o m*/ keyStore = KeyStore.getInstance(ANDROID_KEY_STORE); } catch (Exception e) { Log_OC.e(TAG, "Error getting KeyStore", e); } KeyGenerator keyGenerator; try { keyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, ANDROID_KEY_STORE); } catch (NoSuchAlgorithmException | NoSuchProviderException e) { return; } try { keyStore.load(null); keyGenerator.init(new KeyGenParameterSpec.Builder(KEY_NAME, KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT) .setBlockModes(KeyProperties.BLOCK_MODE_CBC).setUserAuthenticationRequired(true) .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_PKCS7).build()); keyGenerator.generateKey(); } catch (NoSuchAlgorithmException | InvalidAlgorithmParameterException | CertificateException | IOException e) { return; } }
From source file:org.apache.hadoop.crypto.key.KeyProvider.java
/** * Generates a key material.//from w w w . ja v a2 s .c o m * * @param size length of the key. * @param algorithm algorithm to use for generating the key. * @return the generated key. * @throws NoSuchAlgorithmException */ protected byte[] generateKey(int size, String algorithm) throws NoSuchAlgorithmException { algorithm = getAlgorithm(algorithm); KeyGenerator keyGenerator = KeyGenerator.getInstance(algorithm); keyGenerator.init(size); byte[] key = keyGenerator.generateKey().getEncoded(); return key; }
From source file:org.apache.hadoop.mapreduce.JobSubmitter.java
/** * Internal method for submitting jobs to the system. * /*from w w w. ja v a2s.com*/ * <p>The job submission process involves: * <ol> * <li> * Checking the input and output specifications of the job. * </li> * <li> * Computing the {@link InputSplit}s for the job. * </li> * <li> * Setup the requisite accounting information for the * {@link DistributedCache} of the job, if necessary. * </li> * <li> * Copying the job's jar and configuration to the map-reduce system * directory on the distributed file-system. * </li> * <li> * Submitting the job to the <code>JobTracker</code> and optionally * monitoring it's status. * </li> * </ol></p> * @param job the configuration to submit * @param cluster the handle to the Cluster * @throws ClassNotFoundException * @throws InterruptedException * @throws IOException */ JobStatus submitJobInternal(Job job, Cluster cluster) throws ClassNotFoundException, InterruptedException, IOException { //validate the jobs output specs checkSpecs(job); Configuration conf = job.getConfiguration(); addMRFrameworkToDistributedCache(conf); Path jobStagingArea = JobSubmissionFiles.getStagingDir(cluster, conf); //configure the command line options correctly on the submitting dfs InetAddress ip = InetAddress.getLocalHost(); if (ip != null) { submitHostAddress = ip.getHostAddress(); submitHostName = ip.getHostName(); conf.set(MRJobConfig.JOB_SUBMITHOST, submitHostName); conf.set(MRJobConfig.JOB_SUBMITHOSTADDR, submitHostAddress); } JobID jobId = submitClient.getNewJobID(); job.setJobID(jobId); Path submitJobDir = new Path(jobStagingArea, jobId.toString()); JobStatus status = null; try { conf.set(MRJobConfig.USER_NAME, UserGroupInformation.getCurrentUser().getShortUserName()); conf.set("hadoop.http.filter.initializers", "org.apache.hadoop.yarn.server.webproxy.amfilter.AmFilterInitializer"); conf.set(MRJobConfig.MAPREDUCE_JOB_DIR, submitJobDir.toString()); LOG.debug("Configuring job " + jobId + " with " + submitJobDir + " as the submit dir"); // get delegation token for the dir TokenCache.obtainTokensForNamenodes(job.getCredentials(), new Path[] { submitJobDir }, conf); populateTokenCache(conf, job.getCredentials()); // generate a secret to authenticate shuffle transfers if (TokenCache.getShuffleSecretKey(job.getCredentials()) == null) { KeyGenerator keyGen; try { keyGen = KeyGenerator.getInstance(SHUFFLE_KEYGEN_ALGORITHM); keyGen.init(SHUFFLE_KEY_LENGTH); } catch (NoSuchAlgorithmException e) { throw new IOException("Error generating shuffle secret key", e); } SecretKey shuffleKey = keyGen.generateKey(); TokenCache.setShuffleSecretKey(shuffleKey.getEncoded(), job.getCredentials()); } if (CryptoUtils.isEncryptedSpillEnabled(conf)) { conf.setInt(MRJobConfig.MR_AM_MAX_ATTEMPTS, 1); LOG.warn("Max job attempts set to 1 since encrypted intermediate" + "data spill is enabled"); } copyAndConfigureFiles(job, submitJobDir); Path submitJobFile = JobSubmissionFiles.getJobConfPath(submitJobDir); // Create the splits for the job LOG.debug("Creating splits at " + jtFs.makeQualified(submitJobDir)); int maps = writeSplits(job, submitJobDir); conf.setInt(MRJobConfig.NUM_MAPS, maps); LOG.info("number of splits:" + maps); // write "queue admins of the queue to which job is being submitted" // to job file. String queue = conf.get(MRJobConfig.QUEUE_NAME, JobConf.DEFAULT_QUEUE_NAME); AccessControlList acl = submitClient.getQueueAdmins(queue); conf.set(toFullPropertyName(queue, QueueACL.ADMINISTER_JOBS.getAclName()), acl.getAclString()); // removing jobtoken referrals before copying the jobconf to HDFS // as the tasks don't need this setting, actually they may break // because of it if present as the referral will point to a // different job. TokenCache.cleanUpTokenReferral(conf); if (conf.getBoolean(MRJobConfig.JOB_TOKEN_TRACKING_IDS_ENABLED, MRJobConfig.DEFAULT_JOB_TOKEN_TRACKING_IDS_ENABLED)) { // Add HDFS tracking ids ArrayList<String> trackingIds = new ArrayList<String>(); for (Token<? extends TokenIdentifier> t : job.getCredentials().getAllTokens()) { trackingIds.add(t.decodeIdentifier().getTrackingId()); } conf.setStrings(MRJobConfig.JOB_TOKEN_TRACKING_IDS, trackingIds.toArray(new String[trackingIds.size()])); } // Set reservation info if it exists ReservationId reservationId = job.getReservationId(); if (reservationId != null) { conf.set(MRJobConfig.RESERVATION_ID, reservationId.toString()); } // Write job file to submit dir writeConf(conf, submitJobFile); // // Now, actually submit the job (using the submit name) // printTokens(jobId, job.getCredentials()); status = submitClient.submitJob(jobId, submitJobDir.toString(), job.getCredentials()); if (status != null) { return status; } else { throw new IOException("Could not launch job"); } } finally { if (status == null) { LOG.info("Cleaning up the staging area " + submitJobDir); if (jtFs != null && submitJobDir != null) jtFs.delete(submitJobDir, true); } } }
From source file:de.schildbach.wallet.util.FingerprintHelper.java
@RequiresApi(api = Build.VERSION_CODES.M) private boolean initKeyStore() { try {/*from w w w .j a v a 2 s . co m*/ keyStore = KeyStore.getInstance("AndroidKeyStore"); KeyGenerator keyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore"); keyStore.load(null); if (getLastIv() == null) { KeyGenParameterSpec keyGeneratorSpec = createKeyGenParameterSpec(); keyGenerator.init(keyGeneratorSpec); keyGenerator.generateKey(); } } catch (Throwable t) { log.info("Failed init of keyStore & keyGenerator: " + t.getMessage()); return false; } return true; }
From source file:org.apache.ws.security.message.EncryptionTest.java
/** * Setup method/*from w ww . jav a 2s .c om*/ * * @throws java.lang.Exception Thrown when there is a problem in setup */ @org.junit.Before public void setUp() throws Exception { KeyGenerator keyGen = KeyGenerator.getInstance("AES"); keyGen.init(128); key = keyGen.generateKey(); keyData = key.getEncoded(); WSSConfig wssConfig = WSSConfig.getNewInstance(); wssConfig.setWsiBSPCompliant(true); secEngine.setWssConfig(wssConfig); }