List of usage examples for javax.crypto SecretKey getEncoded
public byte[] getEncoded();
From source file:com.microsoft.aad.adal.CordovaAdalPlugin.java
private SecretKey createSecretKey(String key) throws NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeySpecException { SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithSHA256And256BitAES-CBC-BC"); SecretKey tempkey = keyFactory .generateSecret(new PBEKeySpec(key.toCharArray(), "abcdedfdfd".getBytes("UTF-8"), 100, 256)); SecretKey secretKey = new SecretKeySpec(tempkey.getEncoded(), "AES"); return secretKey; }
From source file:org.fejoa.library.remote.LoginJob.java
@Override protected Result handleJson(JSONObject returnValue, InputStream binaryData) { try {//from w w w . j av a2 s .c o m UserKeyParameters loginUserKeyParams = new UserKeyParameters( returnValue.getJSONObject(AccountSettings.LOGIN_USER_KEY_PARAMS)); SecretKey kdfKey = context.getKDFKey(loginUserKeyParams.kdfParameters, password); SecretKey secretKey = UserKeyParameters.deriveUserKey(kdfKey, loginUserKeyParams); // EKE2 authenticates both sides and the server auth first. So we are the verifier and the server is the // prover. byte[] encGX = Base64.decodeBase64(returnValue.getString(ENC_GX)); AuthProtocolEKE2_SHA3_256_CTR.Verifier verifier = AuthProtocolEKE2_SHA3_256_CTR .createVerifier(RFC5114_2048_256, secretKey.getEncoded(), encGX); setFollowUpJob(new FinishAuthJob(userName, verifier)); return new Result(Errors.FOLLOW_UP_JOB, "parameters received"); } catch (JSONException e) { e.printStackTrace(); return new Result(Errors.ERROR, "parameter missing"); } catch (Exception e) { e.printStackTrace(); return new Result(Errors.ERROR, "Exception: " + e.getMessage()); } }
From source file:org.openengsb.ports.jms.JMSPortTest.java
@Test(timeout = 60000) public void testSendEncryptedMethodCall_shouldSendEncryptedResult() throws Exception { FilterChain secureChain = createSecureFilterChain(); incomingPort.setFilterChain(secureChain); incomingPort.start();/*from w ww. j ava 2 s . co m*/ SecretKey sessionKey = CipherUtils.generateKey(CipherUtils.DEFAULT_SYMMETRIC_ALGORITHM, CipherUtils.DEFAULT_SYMMETRIC_KEYSIZE); byte[] encryptedKey = CipherUtils.encrypt(sessionKey.getEncoded(), publicKey); byte[] encryptedContent = CipherUtils.encrypt(METHOD_CALL_REQUEST.getBytes(), sessionKey); EncryptedMessage encryptedMessage = new EncryptedMessage(encryptedContent, encryptedKey); final String encryptedString = new ObjectMapper().writeValueAsString(encryptedMessage); String resultString = sendWithTempQueue(encryptedString); byte[] result = CipherUtils.decrypt(Base64.decodeBase64(resultString), sessionKey); MethodResultMessage result2 = OBJECT_MAPPER.readValue(result, MethodResultMessage.class); MethodResult methodResult = result2.getResult(); Object realResultArg = OBJECT_MAPPER.convertValue(methodResult.getArg(), Class.forName(methodResult.getClassName())); assertThat(realResultArg, equalTo((Object) new TestClass("test"))); }
From source file:energy.usef.core.service.business.MessageEncryptionServiceIntegrationTest.java
@Before public void initTest() throws UnsupportedEncodingException { Whitebox.setInternalState(keystoreHelperService, "config", config); service = new MessageEncryptionService(); Whitebox.setInternalState(service, "keystoreHelperService", keystoreHelperService); energy.usef.core.util.encryption.NaCl.sodium().crypto_sign_ed25519_seed_keypair(publicKey, privateKey, SEED.getBytes(UTF_8));// w w w. j a va 2 s. com SecretKey secretKey = new SecretKeySpec(privateKey, ALGORITHM); LOGGER.info("Public Key: [{}]", new String(publicKey, StandardCharsets.UTF_8)); LOGGER.info("Private Key: [{}]", new String(privateKey, StandardCharsets.UTF_8)); LOGGER.info("Secret Key Algorithm: [{}]", secretKey.getAlgorithm()); LOGGER.info("Secret Key Format: [{}]", secretKey.getFormat()); LOGGER.info("Secret Key Encoded: [{}]", new String(secretKey.getEncoded(), StandardCharsets.UTF_8)); LOGGER.info("### Executing test: {}", name.getMethodName()); Mockito.when(keystoreHelperService.loadSecretKey()) .thenReturn(Arrays.copyOf(privateKey, privateKey.length)); }
From source file:com.microsoft.aad.adal.example.userappwithbroker.MainActivity.java
/** * To call broker, you have to ensure the following: * 1) You have to call {@link AuthenticationSettings#INSTANCE#setUseBroker(boolean)} * and the supplied value has to be true * 2) You have to have to correct set of permissions. * If target API version is lower than 23: * i) You have to have GET_ACCOUNTS, USE_CREDENTIAL, MANAGE_ACCOUNTS declared * in manifest.//from w w w . j av a 2 s . c o m * If target API version is 23: * i) USE_CREDENTIAL and MANAGE_ACCOUNTS is already deprecated. * ii) GET_ACCOUNTS permission is now at protection level "dangerous" calling app * is responsible for requesting it. * 3) If you're talking to the broker app without PRT support, you have to have an * WPJ account existed in broker(enroll with intune, or register with Azure * Authentication app). * 4) The two broker apps(Company Portal or Azure Authenticator) cannot go through * broker auth. */ private void setUpADALForCallingBroker() { // Set the calling app will talk to broker // Note: Starting from version 1.1.14, calling app has to explicitly call // AuthenticationSettings.Instance.setUserBroker(true) to call broker. // AuthenticationSettings.Instance.setSkipBroker(boolean) is already deprecated. AuthenticationSettings.INSTANCE.setUseBroker(true); // Provide secret key for token encryption. try { // For API version lower than 18, you have to provide the secret key. The secret key // needs to be 256 bits. You can use the following way to generate the secret key. And // use AuthenticationSettings.Instance.setSecretKey(secretKeyBytes) to supply us the key. // For API version 18 and above, we use android keystore to generate keypair, and persist // the keypair in AndroidKeyStore. Current investigation shows 1)Keystore may be locked with // a lock screen, if calling app has a lot of background activity, keystore cannot be // accessed when locked, we'll be unable to decrypt the cache items 2) AndroidKeystore could // be reset when gesture to unlock the device is changed. // We do recommend the calling app the supply us the key with the above two limitations. if (AuthenticationSettings.INSTANCE.getSecretKeyData() == null) { // use same key for tests SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithSHA256And256BitAES-CBC-BC"); SecretKey tempkey = keyFactory.generateSecret( new PBEKeySpec("test".toCharArray(), "abcdedfdfd".getBytes("UTF-8"), 100, 256)); SecretKey secretKey = new SecretKeySpec(tempkey.getEncoded(), "AES"); AuthenticationSettings.INSTANCE.setSecretKey(secretKey.getEncoded()); } } catch (NoSuchAlgorithmException | InvalidKeySpecException | UnsupportedEncodingException ex) { showMessage("Fail to generate secret key:" + ex.getMessage()); } ApplicationInfo appInfo = getApplicationContext().getApplicationInfo(); Log.v(TAG, "App info:" + appInfo.uid + " package:" + appInfo.packageName); // If you're directly talking to ADFS server, you should set validateAuthority=false. SampleTelemetry telemetryDispatcher = new SampleTelemetry(); Telemetry.getInstance().registerDispatcher(telemetryDispatcher, true); }
From source file:com.cactus.ClientChatGUI.java
private void Send_ButtonActionPerformed(ActionEvent evt) throws ClientProtocolException, IOException, Exception, UnsupportedEncodingException {//GEN-FIRST:event_Send_ButtonActionPerformed //posts message String message = Message_Area.getText(); //AES functions AES AESmanager = new AES(); //Generate two AES keys and encrypt the message with one of them byte[] messageByte = message.getBytes(); SecretKey aesEncryptKey = AESmanager.generateKey(); SecretKey aesHMACKey = AESmanager.generateKey(); byte[] cipherTextByte = AESmanager.encrypt(aesEncryptKey, messageByte); //Turn generated keys into bytes byte[] aesEncryptKeyByte = aesEncryptKey.getEncoded(); byte[] aesHMACKeyByte = aesHMACKey.getEncoded(); //HMAC functions and create integrity tag from HMAC key and ciphertext HMAC HMACmanager = new HMAC(); byte[] HMACintegrityTag = HMACmanager.encrypt(aesHMACKeyByte, cipherTextByte); //concatenate generated aes keys to make keys plaintext byte[] keysPlaintext = new byte[aesEncryptKeyByte.length + aesHMACKeyByte.length]; System.arraycopy(aesEncryptKeyByte, 0, keysPlaintext, 0, aesEncryptKeyByte.length); System.arraycopy(aesHMACKeyByte, 0, keysPlaintext, aesEncryptKeyByte.length, aesHMACKeyByte.length); //concatenate ciphertext with the integrity tag byte[] cipherTextAndTag = new byte[cipherTextByte.length + HMACintegrityTag.length]; System.arraycopy(cipherTextByte, 0, cipherTextAndTag, 0, cipherTextByte.length); System.arraycopy(HMACintegrityTag, 0, cipherTextAndTag, cipherTextByte.length, HMACintegrityTag.length); //encrypt keys plaintext using RSA OAEP RSA RSAmanager = new RSA(); byte[] keysCipherText = RSAmanager.encryptKeysPlaintext(keysPlaintext, user.getFriendPublicKey()); //turns CipherTextandTag into a String String encryptedMessage = Base64.encodeBase64String(cipherTextAndTag); //turns keysCipherText into a String String messageKey = Base64.encodeBase64String(keysCipherText); CloseableHttpClient client = HttpClients.createDefault(); HttpPost httpPost = new HttpPost("https://teamcactus.us/Post_Message.php"); String json = "{\"message\":\"" + encryptedMessage + "\",\"receiver\":\"" + user.getfriend() + "\",\"conversation_id\":\"" + user.getconversation() + "\",\"messageKey\":\"" + messageKey + "\"}"; StringEntity entity = new StringEntity(json); httpPost.setEntity(entity);/* w w w . ja va 2s . c om*/ httpPost.setHeader("Accept", "application/json"); httpPost.setHeader("Content-type", "application/json"); httpPost.setHeader("Authorization", "Bearer " + user.getJWT()); HttpResponse response = client.execute(httpPost); String responseBody = EntityUtils.toString(response.getEntity()); JSONObject obj = new JSONObject(responseBody); String status = obj.getString("status"); if (status.equals("success")) { System.out.print("message sent!"); updateChatBox(); Message_Area.setText(""); } // TODO add your handling code here: }
From source file:com.gfw.press.encrypt.Encrypt.java
/** * ?SecretKey/* w ww.ja va 2 s. co m*/ * * @param secretKey * SecretKey * * @return SecretKey * */ public String getStringKey(SecretKey secretKey) { if (secretKey == null) { return null; } return Base64.encodeBase64String(secretKey.getEncoded()); }
From source file:org.apache.hadoop.mapreduce.JobSubmitter.java
/** * Internal method for submitting jobs to the system. * /*from w w w .jav a2 s .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:test.unit.org.owasp.webscarab.plugin.saml.SamlTest.java
@Test public void testEncryptionAES() throws Exception { KeyGenerator keygen = KeyGenerator.getInstance("AES"); keygen.init(128);//from www . j a v a 2s. c om SecretKey secretKey = keygen.generateKey(); LOG.debug("secret key algo: " + secretKey.getAlgorithm()); LOG.debug("secret key format: " + secretKey.getFormat()); Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.ENCRYPT_MODE, secretKey); LOG.debug("cipher provider: " + cipher.getProvider().getName()); byte[] result = cipher.doFinal("hello world".getBytes()); assertNotNull(result); byte[] encodedSecretKey = secretKey.getEncoded(); LOG.debug("encoded secret key size: " + encodedSecretKey.length * 8); // decrypt cipher = Cipher.getInstance("AES"); SecretKeySpec secretKeySpec = new SecretKeySpec(encodedSecretKey, "AES"); cipher.init(Cipher.DECRYPT_MODE, secretKeySpec); byte[] decryptedResult = cipher.doFinal(result); assertEquals("hello world", new String(decryptedResult)); }
From source file:com.example.android.vault.EncryptedDocument.java
/** * Create an encrypted document.//from w w w .j av a2 s .c om * * @param docId the expected {@link Document#COLUMN_DOCUMENT_ID} to be * validated when reading metadata. * @param file location on disk where the encrypted document is stored. May * not exist yet. */ public EncryptedDocument(long docId, File file, SecretKey dataKey, SecretKey macKey) throws GeneralSecurityException { mRandom = new SecureRandom(); mCipher = Cipher.getInstance("AES/CTR/NoPadding"); mMac = Mac.getInstance("HmacSHA256"); if (dataKey.getEncoded().length != DATA_KEY_LENGTH) { throw new IllegalArgumentException("Expected data key length " + DATA_KEY_LENGTH); } if (macKey.getEncoded().length != MAC_KEY_LENGTH) { throw new IllegalArgumentException("Expected MAC key length " + MAC_KEY_LENGTH); } mDocId = docId; mFile = file; mDataKey = dataKey; mMacKey = macKey; }