Example usage for javax.crypto KeyGenerator generateKey

List of usage examples for javax.crypto KeyGenerator generateKey

Introduction

In this page you can find the example usage for javax.crypto KeyGenerator generateKey.

Prototype

public final SecretKey generateKey() 

Source Link

Document

Generates a secret key.

Usage

From source file:de.schildbach.wallet.util.FingerprintHelper.java

@RequiresApi(api = Build.VERSION_CODES.M)
private boolean initKeyStore() {
    try {// ww w.  j av a2  s.c o 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:com.jefftharris.passwdsafe.SavedPasswordsMgr.java

/**
 * Generate a saved password key for a file
 *///from w w  w. j a va  2s. co  m
@TargetApi(Build.VERSION_CODES.M)
public synchronized void generateKey(Uri fileUri) throws InvalidAlgorithmParameterException,
        NoSuchAlgorithmException, NoSuchProviderException, IOException {
    PasswdSafeUtil.dbginfo(TAG, "generateKey: %s", fileUri);

    if (!itsFingerprintMgr.hasEnrolledFingerprints()) {
        throw new IOException(itsContext.getString(R.string.no_fingerprints_registered));
    }

    String keyName = getPrefsKey(fileUri);
    try {
        KeyGenerator keyGen = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, KEYSTORE);
        keyGen.init(new KeyGenParameterSpec.Builder(keyName,
                KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
                        .setBlockModes(KeyProperties.BLOCK_MODE_CBC)
                        .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_PKCS7).setKeySize(256)
                        .setUserAuthenticationRequired(true).build());
        keyGen.generateKey();
    } catch (NoSuchAlgorithmException | NoSuchProviderException | InvalidAlgorithmParameterException e) {
        Log.e(TAG, "generateKey failure", e);
        removeSavedPassword(fileUri);
        throw e;
    }
}

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  ww  w.j  av  a2 s . c  om*/
            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.message.WSSecEncrypt.java

/**
 * Initialize a WSSec Encrypt./* w  w  w  . j  a  v a 2s.  c  o m*/
 * 
 * The method prepares and initializes a WSSec Encrypt structure after the
 * relevant information was set. After preparation of the token references
 * can be added and encrypted.
 * 
 * This method does not add any element to the security header. This must be
 * done explicitly.
 * 
 * @param doc The SOAP envelope as <code>Document</code>
 * @param crypto An instance of the Crypto API to handle keystore and certificates
 * @throws WSSecurityException
 */
public void prepare(Document doc, Crypto crypto) throws WSSecurityException {

    document = doc;

    //
    // If no external key (symmetricalKey) was set generate an encryption
    // key (session key) for this Encrypt element. This key will be
    // encrypted using the public key of the receiver
    //
    if (this.ephemeralKey == null) {
        if (symmetricKey == null) {
            KeyGenerator keyGen = getKeyGenerator();
            this.symmetricKey = keyGen.generateKey();
        }
        this.ephemeralKey = this.symmetricKey.getEncoded();
    }

    if (this.symmetricKey == null) {
        this.symmetricKey = WSSecurityUtil.prepareSecretKey(symEncAlgo, this.ephemeralKey);
    }

    //
    // Get the certificate that contains the public key for the public key
    // algorithm that will encrypt the generated symmetric (session) key.
    //
    if (this.encryptSymmKey) {
        X509Certificate remoteCert = null;
        if (useThisCert != null) {
            remoteCert = useThisCert;
        } else {
            X509Certificate[] certs = crypto.getCertificates(user);
            if (certs == null || certs.length <= 0) {
                throw new WSSecurityException(WSSecurityException.FAILURE, "noUserCertsFound",
                        new Object[] { user, "encryption" });
            }
            remoteCert = certs[0];
        }
        prepareInternal(this.ephemeralKey, remoteCert, crypto);
    } else {
        encryptedEphemeralKey = ephemeralKey;
    }
}

From source file:org.apache.usergrid.persistence.Schema.java

private static byte[] getRawKey(byte[] seed) throws Exception {
    KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
    SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
    sr.setSeed(seed);/*from  w ww  .  jav a 2 s  .c  o m*/
    keyGenerator.init(128, sr); // 192 and 256 bits may not be available
    SecretKey secretKey = keyGenerator.generateKey();
    return secretKey.getEncoded();
}

From source file:net.sourceforge.msscodefactory.cflib.v2_1.CFLib.Tip.CFTipClientHandler.java

public void initSessionKey() throws NoSuchAlgorithmException {
    KeyGenerator kg = KeyGenerator.getInstance("AES");
    kg.init(256, new SecureRandom());
    sessionKey = kg.generateKey();
}

From source file:org.apache.hadoop.mapreduce.JobSubmitter.java

/**
 * Internal method for submitting jobs to the system.
 * //from ww w.  ja  va2s  . 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.xml.security.test.encryption.XMLCipherTester.java

/**
 * Test encryption using a generated AES 128 bit key that is
 * encrypted using a AES 192 bit key.  Then reverse using the KEK
 *///from   w  ww . jav a 2 s .  c o m

public void testAES128ElementAES192KWCipherUsingKEK() throws Exception {

    Document d = document(); // source
    Document ed = null;
    Document dd = null;
    Element e = (Element) d.getElementsByTagName(element()).item(index());
    Element ee = null;

    String source = null;
    String target = null;

    if (haveISOPadding && haveKeyWraps) {

        source = toString(d);

        // Set up a Key Encryption Key
        byte[] bits192 = "abcdefghijklmnopqrstuvwx".getBytes();
        Key kek = new SecretKeySpec(bits192, "AES");

        // Generate a traffic key
        KeyGenerator keygen = KeyGenerator.getInstance("AES");
        keygen.init(128);
        Key key = keygen.generateKey();

        cipher = XMLCipher.getInstance(XMLCipher.AES_192_KeyWrap);
        cipher.init(XMLCipher.WRAP_MODE, kek);
        EncryptedKey encryptedKey = cipher.encryptKey(d, key);

        // encrypt
        cipher = XMLCipher.getInstance(XMLCipher.AES_128);
        cipher.init(XMLCipher.ENCRYPT_MODE, key);
        EncryptedData builder = cipher.getEncryptedData();

        KeyInfo builderKeyInfo = builder.getKeyInfo();
        if (builderKeyInfo == null) {
            builderKeyInfo = new KeyInfo(d);
            builder.setKeyInfo(builderKeyInfo);
        }

        builderKeyInfo.add(encryptedKey);

        ed = cipher.doFinal(d, e);

        //decrypt
        key = null;
        ee = (Element) ed.getElementsByTagName("xenc:EncryptedData").item(0);
        cipher = XMLCipher.getInstance(XMLCipher.AES_128);
        cipher.init(XMLCipher.DECRYPT_MODE, null);
        cipher.setKEK(kek);
        dd = cipher.doFinal(ed, ee);

        target = toString(dd);

        Assert.assertEquals(source, target);
    } else {
        log.warn("Test testAES128ElementAES192KWCipherUsingKEK skipped as necessary algorithms not available");
    }
}

From source file:org.apache.xml.security.test.encryption.XMLCipherTester.java

/**
 * Test encryption using a generated AES 256 bit key that is
 * encrypted using an RSA key.  Reverse using KEK
 *//*w w w .  j ava  2s.c  om*/

public void testAES128ElementRSAKWCipherUsingKEK() throws Exception {

    Document d = document(); // source
    Document ed = null;
    Document dd = null;
    Element e = (Element) d.getElementsByTagName(element()).item(index());
    Element ee = null;

    String source = null;
    String target = null;

    if (haveISOPadding) {

        source = toString(d);

        // Generate an RSA key
        KeyPairGenerator rsaKeygen = KeyPairGenerator.getInstance("RSA");
        KeyPair kp = rsaKeygen.generateKeyPair();
        PrivateKey priv = kp.getPrivate();
        PublicKey pub = kp.getPublic();

        // Generate a traffic key
        KeyGenerator keygen = KeyGenerator.getInstance("AES");
        keygen.init(256);
        Key key = keygen.generateKey();

        cipher = XMLCipher.getInstance(XMLCipher.RSA_v1dot5);
        cipher.init(XMLCipher.WRAP_MODE, pub);
        EncryptedKey encryptedKey = cipher.encryptKey(d, key);

        // encrypt
        cipher = XMLCipher.getInstance(XMLCipher.AES_256);
        cipher.init(XMLCipher.ENCRYPT_MODE, key);
        EncryptedData builder = cipher.getEncryptedData();

        KeyInfo builderKeyInfo = builder.getKeyInfo();
        if (builderKeyInfo == null) {
            builderKeyInfo = new KeyInfo(d);
            builder.setKeyInfo(builderKeyInfo);
        }

        builderKeyInfo.add(encryptedKey);

        ed = cipher.doFinal(d, e);
        log.debug("Encrypted document");
        log.debug(toString(ed));

        //decrypt
        key = null;
        ee = (Element) ed.getElementsByTagName("xenc:EncryptedData").item(0);
        cipher = XMLCipher.getInstance(XMLCipher.AES_128);
        cipher.init(XMLCipher.DECRYPT_MODE, null);
        cipher.setKEK(priv);
        dd = cipher.doFinal(ed, ee);

        target = toString(dd);
        log.debug("Output document");
        log.debug(target);

        Assert.assertEquals(source, target);
    } else {
        log.warn("Test testAES128ElementRSAKWCipherUsingKEK skipped as necessary algorithms not available");
    }
}

From source file:com.grarak.kerneladiutor.activities.SecurityActivity.java

private void loadFingerprint() {
    try {//  w  w  w  .  j ava  2 s.  co m
        KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
        KeyGenerator keyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES,
                "AndroidKeyStore");
        mCipher = Cipher.getInstance(KeyProperties.KEY_ALGORITHM_AES + "/" + KeyProperties.BLOCK_MODE_CBC + "/"
                + KeyProperties.ENCRYPTION_PADDING_PKCS7);

        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();

        SecretKey key = (SecretKey) keyStore.getKey(KEY_NAME, null);
        mCipher.init(Cipher.ENCRYPT_MODE, key);
    } catch (KeyStoreException | NoSuchProviderException | NoSuchAlgorithmException | NoSuchPaddingException
            | UnrecoverableKeyException | InvalidKeyException | CertificateException
            | InvalidAlgorithmParameterException | IOException e) {
        return;
    }

    mCryptoObject = new FingerprintManagerCompat.CryptoObject(mCipher);
    FrameLayout fingerprintParent = (FrameLayout) findViewById(R.id.fingerprint_parent);
    final SwirlView swirlView = new SwirlView(new ContextThemeWrapper(this, R.style.Swirl));
    swirlView.setLayoutParams(new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.MATCH_PARENT));
    fingerprintParent.addView(swirlView);
    fingerprintParent.setVisibility(View.VISIBLE);

    mFingerprintUiHelper = new FingerprintUiHelper.FingerprintUiHelperBuilder(mFingerprintManagerCompat)
            .build(swirlView, new FingerprintUiHelper.Callback() {
                @Override
                public void onAuthenticated() {
                    try {
                        mCipher.doFinal(SECRET_MESSAGE.getBytes());
                        mPasswordWrong.setVisibility(View.GONE);
                        setResult(1);
                        finish();
                    } catch (IllegalBlockSizeException | BadPaddingException e) {
                        e.printStackTrace();
                        swirlView.setState(SwirlView.State.ERROR);
                    }
                }

                @Override
                public void onError() {
                }
            });
    mFingerprintUiHelper.startListening(mCryptoObject);
}