List of usage examples for javax.crypto KeyGenerator getInstance
public static final KeyGenerator getInstance(String algorithm) throws NoSuchAlgorithmException
From source file:org.oscarehr.common.hl7.v2.oscar_to_oscar.SendingUtils.java
private static SecretKey createSecretKey() throws NoSuchAlgorithmException { KeyGenerator keyGenerator = KeyGenerator.getInstance("AES"); keyGenerator.init(128);//from w w w . ja v a 2 s . c o m return (keyGenerator.generateKey()); }
From source file:org.apache.hadoop.mapreduce.JobSubmitter.java
/** * Internal method for submitting jobs to the system. * /* w ww. j a v a 2s .c o m*/ * <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:org.apache.abdera.ext.oauth.OAuthScheme.java
private String sign(String method, String baseString, Certificate cert) throws AuthenticationException { if (method.equalsIgnoreCase("HMAC-MD5") || method.equalsIgnoreCase("HMAC-SHA1")) { try {// w w w .j a va2s.co m String[] tokens = method.split("-"); String methodName = tokens[0].substring(0, 1).toUpperCase() + tokens[0].substring(1).toLowerCase() + tokens[1]; KeyGenerator kg = KeyGenerator.getInstance(methodName); Mac mac = Mac.getInstance(kg.getAlgorithm()); mac.init(kg.generateKey()); byte[] result = mac.doFinal(baseString.getBytes()); return new String(Base64.encodeBase64(result)); } catch (Exception e) { throw new AuthenticationException(e.getMessage(), e); } } else if (method.equalsIgnoreCase("md5")) { return new String(Base64.encodeBase64(DigestUtils.md5(baseString))); } else if (method.equalsIgnoreCase("sha1")) { return new String(Base64.encodeBase64(DigestUtils.sha(baseString))); } else if (method.equalsIgnoreCase("RSA-SHA1")) { if (cert == null) { throw new AuthenticationException("a cert is mandatory to use SHA1 with RSA"); } try { Cipher cipher = Cipher.getInstance("SHA1withRSA"); cipher.init(Cipher.ENCRYPT_MODE, cert); byte[] result = cipher.doFinal(baseString.getBytes()); return new String(Base64.encodeBase64(result)); } catch (Exception e) { throw new AuthenticationException(e.getMessage(), e); } } else { throw new AuthenticationException("unsupported algorithm method: " + method); } }
From source file:org.opensaml.xml.security.XMLSecurityHelper.java
/** * Generates a random Java JCE symmetric Key object from the specified XML Encryption algorithm URI. * /*from w w w . ja v a2 s . c o m*/ * @param algoURI The XML Encryption algorithm URI * @return a randomly-generated symmetric Key * @throws NoSuchAlgorithmException thrown if the specified algorithm is invalid * @throws KeyException thrown if the length of the key to generate could not be determined */ public static SecretKey generateSymmetricKey(String algoURI) throws NoSuchAlgorithmException, KeyException { Logger log = getLogger(); String jceAlgorithmName = getKeyAlgorithmFromURI(algoURI); if (StringSupport.isNullOrEmpty(jceAlgorithmName)) { log.error("Mapping from algorithm URI '" + algoURI + "' to key algorithm not available, key generation failed"); throw new NoSuchAlgorithmException("Algorithm URI'" + algoURI + "' is invalid for key generation"); } Integer keyLength = getKeyLengthFromURI(algoURI); if (keyLength == null) { log.error("Key length could not be determined from algorithm URI, can't generate key"); throw new KeyException("Key length not determinable from algorithm URI, could not generate new key"); } KeyGenerator keyGenerator = KeyGenerator.getInstance(jceAlgorithmName); keyGenerator.init(keyLength); return keyGenerator.generateKey(); }
From source file:org.kuali.rice.kew.documentoperation.web.DocumentContentOperationAction.java
private SecretKey getSecretKey(String encryptionKey) throws Exception { KeyGenerator keygen = KeyGenerator.getInstance("DES"); SecretKey desKey = keygen.generateKey(); // Create the cipher Cipher cipher = Cipher.getInstance(ALGORITHM); cipher.init((Cipher.UNWRAP_MODE), desKey); byte[] bytes = Base64.decodeBase64(encryptionKey.getBytes()); SecretKeyFactory desFactory = SecretKeyFactory.getInstance("DES"); DESKeySpec keyspec = new DESKeySpec(bytes); desKey = desFactory.generateSecret(keyspec); // Create the cipher cipher.init((Cipher.WRAP_MODE), desKey); return desKey; }
From source file:org.wso2.carbon.apimgt.core.impl.FileEncryptionUtility.java
/** * Creates and stores an AES key/*from w w w. ja v a2 s .com*/ * * @throws APIManagementException if an error occurs while creating or storing AES key */ void createAndStoreAESKey() throws APIManagementException { try { //create a new AES key KeyGenerator keyGenerator = KeyGenerator.getInstance(EncryptionConstants.AES); keyGenerator.init(AES_Key_Size); byte[] aesKey = keyGenerator.generateKey().getEncoded(); //store key => encrypt -> encode -> chars -> string byte[] encryptedKeyBytes = SecureVaultUtils.base64Encode(getSecureVault().encrypt(aesKey)); String encryptedKeyString = new String(SecureVaultUtils.toChars(encryptedKeyBytes)); Files.deleteIfExists(Paths.get(getAesKeyFileLocation())); APIFileUtils.createFile(getAesKeyFileLocation()); APIFileUtils.writeToFile(getAesKeyFileLocation(), encryptedKeyString); log.debug("AES key successfully created and stored"); } catch (NoSuchAlgorithmException | SecureVaultException | APIMgtDAOException | IOException e) { String msg = "Error while creating or storing created AES key"; throw new APIManagementException(msg, e); } }
From source file:jef.tools.security.EncrypterUtil.java
/** * ?KEY//from w w w . j a va 2s . com * * @param value * @param algom * * @return */ public static final SecretKey generateKey(String algom, int keylength) { try { KeyGenerator keygen = KeyGenerator.getInstance(algom); keygen.init(keylength); SecretKey deskey = keygen.generateKey(); return deskey; } catch (GeneralSecurityException e) { throw new RuntimeException(e); } }
From source file:net.sourceforge.jencrypt.lib.CryptoWrapper.java
private Key getInitializationVector(CryptoWrapperBuilder builder) throws NoSuchAlgorithmException { KeyGenerator generator = KeyGenerator.getInstance(builder.cipherName); generator.init(CryptoWrapper.AES_BLOCK_SIZE_IN_BITS, new SecureRandom()); return generator.generateKey(); }
From source file:org.jpos.qi.eeuser.ConsumersView.java
private SecretKey generateKey() throws NoSuchAlgorithmException { KeyGenerator gen = KeyGenerator.getInstance(HASH_ALGORITHM); return gen.generateKey(); }
From source file:net.jmhertlein.core.crypto.Keys.java
/** * Generates a new AES key using the system's default SecureRandom * * @param bits/*from www.j a v a2s .c o m*/ * * @return the AES key, or null if the AES algorithm is not available on the system */ public static SecretKey newAESKey(int bits) { KeyGenerator keyGen; try { keyGen = KeyGenerator.getInstance("AES"); } catch (NoSuchAlgorithmException ex) { Logger.getLogger(Keys.class.getName()).log(Level.SEVERE, null, ex); return null; } keyGen.init(bits); return keyGen.generateKey(); }