List of usage examples for javax.crypto SecretKey getEncoded
public byte[] getEncoded();
From source file:com.evolveum.midpoint.prism.crypto.AESProtector.java
public String getSecretKeyDigest(SecretKey key) throws EncryptionException { MessageDigest sha1;/*w w w . j a v a 2s.c o m*/ try { sha1 = MessageDigest.getInstance(KEY_DIGEST_TYPE); } catch (NoSuchAlgorithmException ex) { throw new EncryptionException(ex.getMessage(), ex); } return Base64.encode(sha1.digest(key.getEncoded())); }
From source file:com.microsoft.azure.storage.blob.BlobEncryptionPolicy.java
/** * Set up the encryption context required for encrypting blobs. * @param metadata/*from www . ja v a2 s. c om*/ * Reference to blob metadata object that is used to set the encryption materials. * @param noPadding * Value indicating if the padding mode should be set or not. * @return The Cipher to use to decrypt the blob. * @throws StorageException * An exception representing any error which occurred during the operation. */ Cipher createAndSetEncryptionContext(Map<String, String> metadata, boolean noPadding) throws StorageException { Utility.assertNotNull("metadata", metadata); // The Key should be set on the policy for encryption. Otherwise, throw an error. if (this.keyWrapper == null) { throw new IllegalArgumentException(SR.KEY_MISSING); } try { KeyGenerator keyGen = KeyGenerator.getInstance("AES"); keyGen.init(256); Cipher myAes; if (noPadding) { myAes = Cipher.getInstance("AES/CBC/NoPadding"); } else { myAes = Cipher.getInstance("AES/CBC/PKCS5Padding"); } SecretKey aesKey = keyGen.generateKey(); myAes.init(Cipher.ENCRYPT_MODE, aesKey); BlobEncryptionData encryptionData = new BlobEncryptionData(); encryptionData.setEncryptionAgent(new EncryptionAgent( Constants.EncryptionConstants.ENCRYPTION_PROTOCOL_V1, EncryptionAlgorithm.AES_CBC_256)); // Wrap key Pair<byte[], String> encryptedKey = this.keyWrapper .wrapKeyAsync(aesKey.getEncoded(), null /* algorithm */).get(); encryptionData.setWrappedContentKey(new WrappedContentKey(this.keyWrapper.getKid(), encryptedKey.getKey(), encryptedKey.getValue())); encryptionData.setContentEncryptionIV(myAes.getIV()); metadata.put(Constants.EncryptionConstants.BLOB_ENCRYPTION_DATA, encryptionData.serialize()); return myAes; } catch (Exception e) { throw StorageException.translateClientException(e); } }
From source file:org.apache.hadoop.mapreduce.JobSubmitter.java
/** * Internal method for submitting jobs to the system. * // www .j ava 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 { 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.fegor.alfresco.security.crypto.Crypto.java
/** * Encryption configuration/*from ww w. jav a2s.com*/ * * @throws NoSuchAlgorithmException * @throws InvalidKeySpecException * @throws NoSuchPaddingException * @throws InvalidParameterSpecException * @throws IllegalBlockSizeException * @throws BadPaddingException * @throws UnsupportedEncodingException * @throws InvalidKeyException */ public void configEncrypt() throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidParameterSpecException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException, InvalidKeyException { SecretKeyFactory factory = null; SecretKey tmp = null; salt_pos = new byte[SALT_LEN]; SecureRandom rnd = new SecureRandom(); rnd.nextBytes(salt_pos); if (logger.isDebugEnabled()) logger.debug(this.getClass().getName() + ": [salt: " + (new String(Hex.encodeHex(salt_pos))) + "]"); factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); /* * http://www.javamex.com/tutorials/cryptography/unrestricted_policy_files * .shtml */ KeySpec spec = new PBEKeySpec(password.toCharArray(), salt_pos, ITERATIONS, KEYLEN_BITS); tmp = factory.generateSecret(spec); SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES"); eCipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); eCipher.init(Cipher.ENCRYPT_MODE, secret); AlgorithmParameters params = eCipher.getParameters(); vector_init = params.getParameterSpec(IvParameterSpec.class).getIV(); if (logger.isDebugEnabled()) logger.debug( this.getClass().getName() + ": [vector ini: " + (new String(Hex.encodeHex(vector_init))) + "]"); }
From source file:com.evolveum.midpoint.prism.crypto.ProtectorImpl.java
private boolean compareHashedPbkd(HashedDataType hashedDataType, String algorithmName, char[] clearChars) throws EncryptionException { DigestMethodType digestMethodType = hashedDataType.getDigestMethod(); byte[] salt = digestMethodType.getSalt(); Integer workFactor = digestMethodType.getWorkFactor(); byte[] digestValue = hashedDataType.getDigestValue(); int keyLen = digestValue.length * 8; SecretKeyFactory secretKeyFactory; try {// w w w . j av a 2s. c om secretKeyFactory = SecretKeyFactory.getInstance(algorithmName); } catch (NoSuchAlgorithmException e) { throw new EncryptionException(e.getMessage(), e); } PBEKeySpec keySpec = new PBEKeySpec(clearChars, salt, workFactor, keyLen); SecretKey key; try { key = secretKeyFactory.generateSecret(keySpec); } catch (InvalidKeySpecException e) { throw new EncryptionException(e.getMessage(), e); } byte[] hashBytes = key.getEncoded(); return Arrays.equals(digestValue, hashBytes); }
From source file:com.evolveum.midpoint.prism.crypto.ProtectorImpl.java
private HashedDataType hashPbkd(ProtectedData<String> protectedData, String algorithmUri, String algorithmName) throws EncryptionException { char[] clearChars = getClearChars(protectedData); byte[] salt = generatePbkdSalt(); int iterations = getPbkdIterations(); SecretKeyFactory secretKeyFactory; try {// w w w. j a va 2 s.c o m secretKeyFactory = SecretKeyFactory.getInstance(algorithmName); } catch (NoSuchAlgorithmException e) { throw new EncryptionException(e.getMessage(), e); } PBEKeySpec keySpec = new PBEKeySpec(clearChars, salt, iterations, getPbkdKeyLength()); SecretKey key; try { key = secretKeyFactory.generateSecret(keySpec); } catch (InvalidKeySpecException e) { throw new EncryptionException(e.getMessage(), e); } byte[] hashBytes = key.getEncoded(); HashedDataType hashedDataType = new HashedDataType(); DigestMethodType digestMethod = new DigestMethodType(); digestMethod.setAlgorithm(algorithmUri); digestMethod.setSalt(salt); digestMethod.setWorkFactor(iterations); hashedDataType.setDigestMethod(digestMethod); hashedDataType.setDigestValue(hashBytes); return hashedDataType; }
From source file:com.cloud.migration.Db20to21MigrationUtil.java
private void updateSSOKey() { try {//from ww w. ja va 2s . c om String encodedKey = null; // Algorithm for SSO Keys is SHA1, should this be configuable? KeyGenerator generator = KeyGenerator.getInstance("HmacSHA1"); SecretKey key = generator.generateKey(); encodedKey = Base64.encodeBase64URLSafeString(key.getEncoded()); _configDao.update("security.singlesignon.key", encodedKey); } catch (NoSuchAlgorithmException ex) { s_logger.error("error generating sso key", ex); } }
From source file:org.picketbox.json.enc.JSONWebEncryption.java
/** * Encrypt/*ww w . j a v a 2s . c om*/ * * @param plainText * @param recipientPublicKey * @param contentMasterKey * @return * @throws ProcessingException */ public String encrypt(String plainText, PublicKey recipientPublicKey, byte[] contentMasterKey) throws ProcessingException { if (jsonWebEncryptionHeader == null) { throw PicketBoxJSONMessages.MESSAGES.jsonEncryptionHeaderMissing(); } if (plainText == null) { throw PicketBoxJSONMessages.MESSAGES.invalidNullArgument("plainText"); } if (recipientPublicKey == null) { throw PicketBoxJSONMessages.MESSAGES.invalidNullArgument("recipientPublicKey"); } if (contentMasterKey == null) { return encrypt(plainText, recipientPublicKey); } SecretKey contentEncryptionKey = new SecretKeySpec(contentMasterKey, EncUtil.AES); // Encrypt using Recipient's public key to yield JWE Encrypted Key byte[] jweEncryptedKey = encryptKey(recipientPublicKey, contentMasterKey); String encodedJWEKey = PicketBoxJSONUtil.b64Encode(jweEncryptedKey); StringBuilder builder = new StringBuilder(PicketBoxJSONUtil.b64Encode(jsonWebEncryptionHeader.toString())); builder.append(PERIOD); builder.append(encodedJWEKey); if (jsonWebEncryptionHeader.needIntegrity()) { int cekLength = jsonWebEncryptionHeader.getCEKLength(); byte[] cek = generateCEK(contentEncryptionKey.getEncoded(), cekLength); // Deal with IV String iv; try { iv = jsonWebEncryptionHeader.getDelegate().getString("iv"); } catch (JSONException e) { throw PicketBoxJSONMessages.MESSAGES.ignorableError(e); } IvParameterSpec ivParameterSpec = new IvParameterSpec(iv.getBytes()); byte[] encryptedText = EncUtil.encryptUsingAES_CBC(plainText, cek, ivParameterSpec); String encodedJWEText = PicketBoxJSONUtil.b64Encode(encryptedText); builder.append(PERIOD); builder.append(encodedJWEText); int cikLength = jsonWebEncryptionHeader.getCIKLength(); byte[] cik = generateCIK(contentEncryptionKey.getEncoded(), cikLength); byte[] integrityValue = performMac(cik, builder.toString().getBytes()); String encodedIntegrityValue = PicketBoxJSONUtil.b64Encode(integrityValue); builder.append(PERIOD); builder.append(encodedIntegrityValue); } else { // Encrypt the plain text byte[] encryptedText = encryptText(plainText, recipientPublicKey); String encodedJWEText = PicketBoxJSONUtil.b64Encode(encryptedText); builder.append(PERIOD); builder.append(encodedJWEText); } return builder.toString(); }
From source file:com.kixeye.chassis.transport.WebSocketTransportTest.java
@Test public void testWebSocketServiceWithJsonWithPskEncryption() throws Exception { // create AES shared key cipher Security.addProvider(new BouncyCastleProvider()); KeyGenerator kgen = KeyGenerator.getInstance("AES", "BC"); kgen.init(128);//from w ww .j a va 2 s .c o m SecretKey key = kgen.generateKey(); byte[] aesKey = key.getEncoded(); Map<String, Object> properties = new HashMap<String, Object>(); properties.put("websocket.enabled", "true"); properties.put("websocket.port", "" + SocketUtils.findAvailableTcpPort()); properties.put("websocket.hostname", "localhost"); properties.put("http.enabled", "false"); properties.put("http.port", "" + SocketUtils.findAvailableTcpPort()); properties.put("http.hostname", "localhost"); properties.put("websocket.crypto.enabled", "true"); properties.put("websocket.crypto.cipherProvider", "BC"); properties.put("websocket.crypto.cipherTransformation", "AES/ECB/PKCS7Padding"); properties.put("websocket.crypto.secretKeyAlgorithm", "AES"); properties.put("websocket.crypto.secretKeyData", BaseEncoding.base16().encode(aesKey)); AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext(); StandardEnvironment environment = new StandardEnvironment(); environment.getPropertySources().addFirst(new MapPropertySource("default", properties)); context.setEnvironment(environment); context.register(PropertySourcesPlaceholderConfigurer.class); context.register(TransportConfiguration.class); context.register(TestWebSocketService.class); WebSocketClient wsClient = new WebSocketClient(); try { context.refresh(); final MessageSerDe serDe = context.getBean(JsonJacksonMessageSerDe.class); final WebSocketMessageRegistry messageRegistry = context.getBean(WebSocketMessageRegistry.class); messageRegistry.registerType("stuff", TestObject.class); wsClient.start(); QueuingWebSocketListener webSocket = new QueuingWebSocketListener(serDe, messageRegistry, context.getBean(WebSocketPskFrameProcessor.class)); Session session = wsClient.connect(webSocket, new URI( "ws://localhost:" + properties.get("websocket.port") + "/" + serDe.getMessageFormatName())) .get(5000, TimeUnit.MILLISECONDS); Envelope envelope = new Envelope("getStuff", null, null, Lists.newArrayList(new Header("testheadername", Lists.newArrayList("testheaderval"))), null); byte[] rawEnvelope = serDe.serialize(envelope); rawEnvelope = SymmetricKeyCryptoUtils.encrypt(rawEnvelope, 0, rawEnvelope.length, key, "AES/ECB/PKCS7Padding", "BC"); session.getRemote().sendBytes(ByteBuffer.wrap(rawEnvelope)); TestObject response = webSocket.getResponse(5, TimeUnit.SECONDS); Assert.assertNotNull(response); Assert.assertEquals("stuff", response.value); byte[] rawStuff = serDe.serialize(new TestObject("more stuff")); envelope = new Envelope("setStuff", "stuff", null, ByteBuffer.wrap(rawStuff)); rawEnvelope = serDe.serialize(envelope); rawEnvelope = SymmetricKeyCryptoUtils.encrypt(rawEnvelope, 0, rawEnvelope.length, key, "AES/ECB/PKCS7Padding", "BC"); session.getRemote().sendBytes(ByteBuffer.wrap(rawEnvelope)); response = webSocket.getResponse(5, TimeUnit.SECONDS); Assert.assertNotNull(response); Assert.assertEquals("stuff", response.value); envelope = new Envelope("getStuff", null, null, null); rawEnvelope = serDe.serialize(envelope); rawEnvelope = SymmetricKeyCryptoUtils.encrypt(rawEnvelope, 0, rawEnvelope.length, key, "AES/ECB/PKCS7Padding", "BC"); session.getRemote().sendBytes(ByteBuffer.wrap(rawEnvelope)); response = webSocket.getResponse(5, TimeUnit.SECONDS); Assert.assertNotNull(response); Assert.assertEquals("more stuff", response.value); rawStuff = serDe.serialize(new TestObject(RandomStringUtils.randomAlphanumeric(100))); envelope = new Envelope("setStuff", "stuff", null, ByteBuffer.wrap(rawStuff)); rawEnvelope = serDe.serialize(envelope); rawEnvelope = SymmetricKeyCryptoUtils.encrypt(rawEnvelope, 0, rawEnvelope.length, key, "AES/ECB/PKCS7Padding", "BC"); session.getRemote().sendBytes(ByteBuffer.wrap(rawEnvelope)); ServiceError error = webSocket.getResponse(5, TimeUnit.SECONDS); Assert.assertNotNull(error); Assert.assertEquals(ExceptionServiceErrorMapper.VALIDATION_ERROR_CODE, error.code); envelope = new Envelope("expectedError", null, null, null); rawEnvelope = serDe.serialize(envelope); rawEnvelope = SymmetricKeyCryptoUtils.encrypt(rawEnvelope, 0, rawEnvelope.length, key, "AES/ECB/PKCS7Padding", "BC"); session.getRemote().sendBytes(ByteBuffer.wrap(rawEnvelope)); error = webSocket.getResponse(5, TimeUnit.SECONDS); Assert.assertNotNull(error); Assert.assertEquals(TestWebSocketService.EXPECTED_EXCEPTION.code, error.code); Assert.assertEquals(TestWebSocketService.EXPECTED_EXCEPTION.description, error.description); envelope = new Envelope("unexpectedError", null, null, null); rawEnvelope = serDe.serialize(envelope); rawEnvelope = SymmetricKeyCryptoUtils.encrypt(rawEnvelope, 0, rawEnvelope.length, key, "AES/ECB/PKCS7Padding", "BC"); session.getRemote().sendBytes(ByteBuffer.wrap(rawEnvelope)); error = webSocket.getResponse(5, TimeUnit.SECONDS); Assert.assertNotNull(error); Assert.assertEquals(ExceptionServiceErrorMapper.UNKNOWN_ERROR_CODE, error.code); } finally { try { wsClient.stop(); } finally { context.close(); } } }
From source file:com.fegor.alfresco.security.crypto.Crypto.java
/** * Decryption configuration/*ww w. j a v a2 s . c o m*/ * * @param initvec * @param salt * @throws NoSuchAlgorithmException * @throws InvalidKeySpecException * @throws NoSuchPaddingException * @throws InvalidKeyException * @throws InvalidAlgorithmParameterException * @throws DecoderException */ public void configDecrypt(String initvec, String salt) throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, DecoderException { SecretKeyFactory factory = null; SecretKey tmp = null; SecretKey secret = null; salt_pos = Hex.decodeHex(salt.toCharArray()); if (logger.isDebugEnabled()) logger.debug(this.getClass().getName() + ": [salt: " + (new String(Hex.encodeHex(salt_pos))) + "]"); vector_init = Hex.decodeHex(initvec.toCharArray()); if (logger.isDebugEnabled()) logger.debug( this.getClass().getName() + ": [vector ini: " + (new String(Hex.encodeHex(vector_init))) + "]"); /* * http://www.javamex.com/tutorials/cryptography/unrestricted_policy_files * .shtml */ factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); KeySpec spec = new PBEKeySpec(password.toCharArray(), salt_pos, ITERATIONS, KEYLEN_BITS); tmp = factory.generateSecret(spec); secret = new SecretKeySpec(tmp.getEncoded(), "AES"); deCipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); deCipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(vector_init)); }