List of usage examples for javax.crypto KeyGenerator getInstance
public static final KeyGenerator getInstance(String algorithm) throws NoSuchAlgorithmException
From source file:test.integ.be.fedict.commons.eid.client.JCATest.java
@Test public void testSoftwareRSAKeyWrapping() throws Exception { final KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); final KeyPair keyPair = keyPairGenerator.generateKeyPair(); final KeyGenerator keyGenerator = KeyGenerator.getInstance("AES"); final SecretKey secretKey = keyGenerator.generateKey(); LOG.debug("secret key algo: " + secretKey.getAlgorithm()); final Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.WRAP_MODE, keyPair.getPublic()); LOG.debug("cipher security provider: " + cipher.getProvider().getName()); LOG.debug("cipher type: " + cipher.getClass().getName()); final byte[] wrappedKey = cipher.wrap(secretKey); cipher.init(Cipher.UNWRAP_MODE, keyPair.getPrivate()); final Key resultKey = cipher.unwrap(wrappedKey, "AES", Cipher.SECRET_KEY); assertArrayEquals(secretKey.getEncoded(), resultKey.getEncoded()); }
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>/*from w w w .ja va 2s . c om*/ * 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.apache.hadoop.mapreduce.JobSubmitter.java
/** * Internal method for submitting jobs to the system. * /* ww w . j a v a 2 s.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 { int keyLen = CryptoUtils.isShuffleEncrypted(conf) ? conf.getInt(MRJobConfig.MR_ENCRYPTED_INTERMEDIATE_DATA_KEY_SIZE_BITS, MRJobConfig.DEFAULT_MR_ENCRYPTED_INTERMEDIATE_DATA_KEY_SIZE_BITS) : SHUFFLE_KEY_LENGTH; keyGen = KeyGenerator.getInstance(SHUFFLE_KEYGEN_ALGORITHM); keyGen.init(keyLen); } catch (NoSuchAlgorithmException e) { throw new IOException("Error generating shuffle secret key", e); } SecretKey shuffleKey = keyGen.generateKey(); TokenCache.setShuffleSecretKey(shuffleKey.getEncoded(), job.getCredentials()); } 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); Limits.reset(conf); // // 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:com.piusvelte.taplock.server.TapLockServer.java
protected static String encryptString(String decStr) { String encStr = null;/*from w ww .j a v a 2 s .co m*/ KeyStore ks = getKeyStore(); if (ks != null) { SecretKey sk = getSecretKey(ks); if (sk == null) { // create key KeyGenerator kgen = null; try { kgen = KeyGenerator.getInstance("AES"); } catch (NoSuchAlgorithmException e) { writeLog("encryptString: " + e.getMessage()); } if (kgen != null) { int keyLength; try { keyLength = Cipher.getMaxAllowedKeyLength("AES"); } catch (NoSuchAlgorithmException e) { keyLength = 128; writeLog("encryptString: " + e.getMessage()); } kgen.init(keyLength); sk = kgen.generateKey(); // create a keystore try { ks.load(null, sPassphrase.toCharArray()); ks.setKeyEntry(TAP_LOCK, sk, sPassphrase.toCharArray(), null); ks.store(new FileOutputStream(sKeystore), sPassphrase.toCharArray()); } catch (NoSuchAlgorithmException e) { writeLog("encryptString: " + e.getMessage()); } catch (CertificateException e) { writeLog("encryptString: " + e.getMessage()); } catch (IOException e) { writeLog("encryptString: " + e.getMessage()); } catch (KeyStoreException e) { writeLog("encryptString: " + e.getMessage()); } } } if ((sk != null) && (decStr != null)) { Cipher cipher; try { cipher = Cipher.getInstance("AES"); cipher.init(Cipher.ENCRYPT_MODE, sk); return new String(Base64.encodeBase64(cipher.doFinal(decStr.getBytes("UTF-8")))); } catch (NoSuchAlgorithmException e) { writeLog("encryptString: " + e.getMessage()); } catch (NoSuchPaddingException e) { writeLog("encryptString: " + e.getMessage()); } catch (InvalidKeyException e) { writeLog("encryptString: " + e.getMessage()); } catch (IllegalBlockSizeException e) { writeLog("encryptString: " + e.getMessage()); } catch (BadPaddingException e) { writeLog("encryptString: " + e.getMessage()); } catch (UnsupportedEncodingException e) { writeLog("encryptString: " + e.getMessage()); } } } return encStr; }
From source file:com.mercer.cpsg.swarm.oidc.deployment.OIDCAuthenticationMechanism.java
protected SecretKey stateKey() { // only generate the state encrpytion key if the HTTP session is going // to be used for nonance checking as well. if (!oidcProvider.isCheckNonce()) { try {/*from www. j av a2s. c o m*/ if (oidcProvider.getClientSecret() != null && !oidcProvider.getClientSecret().isEmpty()) { byte[] key = oidcProvider.getClientSecret().getBytes("UTF-8"); MessageDigest sha = MessageDigest.getInstance("SHA-1"); key = sha.digest(key); key = Arrays.copyOf(key, 16); SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES"); return secretKeySpec; } else { KeyGenerator keyGenerator = KeyGenerator.getInstance("AES"); keyGenerator.init(128); return keyGenerator.generateKey(); } } catch (Exception e) { LOG.log(Level.SEVERE, "", e); return null; } } return null; }
From source file:org.apache.ws.security.processor.EncryptedKeyProcessor.java
/** * Generates a random secret key using the algorithm specified in the * first DataReference URI// w w w . ja va 2s . co m * * @param dataRefURIs * @param doc * @param wsDocInfo * @return * @throws WSSecurityException */ private static byte[] getRandomKey(List<String> dataRefURIs, Document doc, WSDocInfo wsDocInfo) throws WSSecurityException { try { String alg = "AES"; int size = 16; if (!dataRefURIs.isEmpty()) { String uri = dataRefURIs.iterator().next(); Element ee = ReferenceListProcessor.findEncryptedDataElement(doc, uri); String algorithmURI = X509Util.getEncAlgo(ee); alg = JCEMapper.getJCEKeyAlgorithmFromURI(algorithmURI); size = WSSecurityUtil.getKeyLength(algorithmURI); } KeyGenerator kgen = KeyGenerator.getInstance(alg); kgen.init(size * 8); SecretKey k = kgen.generateKey(); return k.getEncoded(); } catch (Throwable ex) { // Fallback to just using AES to avoid attacks on EncryptedData algorithms try { KeyGenerator kgen = KeyGenerator.getInstance("AES"); kgen.init(128); SecretKey k = kgen.generateKey(); return k.getEncoded(); } catch (NoSuchAlgorithmException e) { throw new WSSecurityException(WSSecurityException.FAILED_CHECK, null, null, e); } } }
From source file:org.openintents.safe.CryptoHelper.java
/** * encrypt a file using a random session key * * @param contentResolver is used to be able to read the stream * @param fileUri is the stream or file to read from * @return Uri to the created plaintext file * @throws Exception/*from w w w. j a v a 2 s . com*/ * @author Peli */ public Uri encryptFileWithSessionKey(ContentResolver contentResolver, Uri fileUri) throws CryptoHelperException { if (debug) { Log.d(TAG, "Encrypt with session key"); } status = false; // assume failure if (password == null) { String msg = "Must call setPassword before runing encrypt."; throw new CryptoHelperException(msg); } String outputPath = ""; try { InputStream is; if (fileUri.getScheme().equals("file")) { is = new java.io.FileInputStream(fileUri.getPath()); outputPath = fileUri.getPath() + OISAFE_EXTENSION; } else { is = contentResolver.openInputStream(fileUri); outputPath = getTemporaryFileName(); } FileOutputStream os = new FileOutputStream(outputPath); byte[] cipherSessionKey = {}; // byte[] ciphertext = {}; // First create a session key SecretKey sessionKey = null; byte[] sessionKeyEncoded = null; // String sessionKeyString = null; try { KeyGenerator keygen; keygen = KeyGenerator.getInstance("AES"); keygen.init(256); // needs 96 bytes //keygen.init(128); // needs 64 bytes sessionKey = keygen.generateKey(); sessionKeyEncoded = sessionKey.getEncoded(); // sessionKeyString = new String(sessionKeyEncoded); } catch (NoSuchAlgorithmException e) { Log.e(TAG, "generateMasterKey(): " + e.toString()); return null; } // Encrypt the session key using the master key try { pbeCipher.init(Cipher.ENCRYPT_MODE, pbeKey, pbeParamSpec); cipherSessionKey = pbeCipher.doFinal(sessionKeyEncoded); status = true; } catch (IllegalBlockSizeException | BadPaddingException | InvalidAlgorithmParameterException | InvalidKeyException e) { Log.e(TAG, "encryptWithSessionKey(): " + e.toString()); } if (!status) { return null; } status = false; String stringCipherVersion = "A"; byte[] bytesCipherVersion = stringCipherVersion.getBytes(); os.write(bytesCipherVersion, 0, bytesCipherVersion.length); os.write(cipherSessionKey, 0, cipherSessionKey.length); if (debug) { Log.d(TAG, "bytesCipherVersion.length: " + bytesCipherVersion.length); } if (debug) { Log.d(TAG, "cipherSessionKey.length: " + cipherSessionKey.length); } Trivium tri = new Trivium(); try { tri.setupKey(Trivium.MODE_ENCRYPT, sessionKeyEncoded, 0); tri.setupNonce(sessionKeyEncoded, 10); // Create the byte array to hold the data final int bytesLen = 4096; // buffer length byte[] bytesIn = new byte[bytesLen]; byte[] bytesOut = new byte[bytesLen]; int offset = 0; int numRead = 0; while ((numRead = is.read(bytesIn, 0, bytesLen)) >= 0) { tri.process(bytesIn, 0, bytesOut, 0, numRead); os.write(bytesOut, 0, numRead); offset += numRead; } // Ensure all the bytes have been read in if (offset < is.available()) { throw new IOException("Could not completely read file "); } // Close the input stream and return bytes is.close(); os.close(); // Securely delete the original file: SecureDelete.delete(new File(fileUri.getPath())); status = true; } catch (ESJException e) { Log.e(TAG, "Error encrypting file", e); } } catch (FileNotFoundException e) { Log.e(TAG, "File not found", e); } catch (IOException e) { Log.e(TAG, "IO Exception", e); } if (status == false) { return null; } return Uri.fromFile(new File(outputPath)); //Uri.parse("file://" + outputPath); // TODO: UUEncode }
From source file:org.structr.util.StructrLicenseManager.java
private boolean checkVolumeLicense(final Map<String, String> properties, final String serversString) { try {/*from w ww.jav a 2 s . com*/ final KeyGenerator kgen = KeyGenerator.getInstance("AES"); final byte[] data = write(properties).getBytes("utf-8"); final String name = properties.get(NameKey); final byte[] expected = name.getBytes("utf-8"); kgen.init(128); for (final String part : serversString.split("[, ]+")) { final String address = part.trim(); if (StringUtils.isNotBlank(address)) { try { logger.info("Trying to verify volume license with server {}", address); final long t0 = System.currentTimeMillis(); final SecretKey aesKey = kgen.generateKey(); // symmetric stream key final byte[] ivspec = RandomUtils.nextBytes(16); // initialization vector for stream cipher final byte[] key = encryptSessionKey(aesKey.getEncoded()); final byte[] encryptedIV = encryptSessionKey(ivspec); final byte[] encryptedData = encryptData(data, aesKey, ivspec); final byte[] response = sendAndReceive(address, key, encryptedIV, encryptedData); final boolean result = verify(expected, response); if (result == true) { logger.info("License verified in {} ms", System.currentTimeMillis() - t0); } return result; } catch (Throwable t) { logger.warn("Unable to verify volume license: {}", t.getMessage()); } } } } catch (Throwable t) { t.printStackTrace(); } return false; }
From source file:com.mhs.hboxmaintenanceserver.utils.Utils.java
/** * Blowfish encryption// w w w . j ava2 s .co m * * @param value * @return * @throws java.lang.Exception */ public static String encrypt(String value) throws Exception { // create a key generator based upon the Blowfish cipher KeyGenerator keygenerator = KeyGenerator.getInstance("Blowfish"); File file = new File(DefaultConfig.SECRET_KEY); SecretKey secretkey; if (file.exists()) { // Load key from file secretkey = new SecretKeySpec(FileUtils.readFileToByteArray(file), "Blowfish"); } else { // create a key secretkey = keygenerator.generateKey(); FileUtils.writeByteArrayToFile(file, secretkey.getEncoded()); } // create a cipher based upon Blowfish Cipher cipher = Cipher.getInstance("Blowfish"); // initialise cipher to with secret key cipher.init(Cipher.ENCRYPT_MODE, secretkey); // encrypt message return bytesToHex(cipher.doFinal(value.getBytes())); }
From source file:org.apache.ws.security.message.WSEncryptBody.java
private KeyGenerator getKeyGenerator() throws WSSecurityException { KeyGenerator keyGen = null;// w ww . ja va 2s .co m try { /* * Assume AES as default, so initialize it */ keyGen = KeyGenerator.getInstance("AES"); if (symEncAlgo.equalsIgnoreCase(WSConstants.TRIPLE_DES)) { keyGen = KeyGenerator.getInstance("DESede"); } else if (symEncAlgo.equalsIgnoreCase(WSConstants.AES_128)) { keyGen.init(128); } else if (symEncAlgo.equalsIgnoreCase(WSConstants.AES_192)) { keyGen.init(192); } else if (symEncAlgo.equalsIgnoreCase(WSConstants.AES_256)) { keyGen.init(256); } else { return null; } } catch (NoSuchAlgorithmException e) { throw new WSSecurityException(WSSecurityException.UNSUPPORTED_ALGORITHM, null, null, e); } return keyGen; }