Example usage for javax.crypto KeyGenerator getInstance

List of usage examples for javax.crypto KeyGenerator getInstance

Introduction

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

Prototype

public static final KeyGenerator getInstance(String algorithm) throws NoSuchAlgorithmException 

Source Link

Document

Returns a KeyGenerator object that generates secret keys for the specified algorithm.

Usage

From source file:com.cloud.server.ConfigurationServerImpl.java

private void updateSSOKey() {
    try {//from  ww w . j a  v  a2 s  .c o  m
        String encodedKey = null;

        // Algorithm for SSO Keys is SHA1, should this be configurable?
        KeyGenerator generator = KeyGenerator.getInstance("HmacSHA1");
        SecretKey key = generator.generateKey();
        encodedKey = Base64.encodeBase64URLSafeString(key.getEncoded());

        _configDao.update(Config.SSOKey.key(), Config.SSOKey.getCategory(), encodedKey);
    } catch (NoSuchAlgorithmException ex) {
        s_logger.error("error generating sso key", ex);
    }
}

From source file:org.geoserver.security.GeoServerSecurityManager.java

/**
 * Determines if strong encryption is available.
 * <p>//  ww w .  j  av a 2 s  . c  o  m
 * This method does the determination by trying to encrypt a value with AES 256 Bit encryption.
 * </p>
 * 
 * @return True if strong encryption avaialble, otherwise false.
 */
public boolean isStrongEncryptionAvailable() {
    if (strongEncryptionAvaialble != null)
        return strongEncryptionAvaialble;

    KeyGenerator kgen;
    try {
        kgen = KeyGenerator.getInstance("AES");
        kgen.init(256);
        SecretKey skey = kgen.generateKey();
        byte[] raw = skey.getEncoded();
        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
        Cipher cipher = Cipher.getInstance("AES");

        cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
        cipher.doFinal("This is just an example".getBytes());
        strongEncryptionAvaialble = true;
        LOGGER.info("Strong cryptograhpy is available");
    } catch (InvalidKeyException e) {
        strongEncryptionAvaialble = false;
        LOGGER.warning("Strong cryptograhpy is NOT available"
                + "\nDownload and install of policy files recommended"
                + "\nfrom http://www.oracle.com/technetwork/java/javase/downloads/jce-6-download-429243.html");
    } catch (Exception ex) {
        LOGGER.log(Level.WARNING, "Strong cryptograhpy is NOT available, unexpected error", ex);
        strongEncryptionAvaialble = false; //should not happen
    }
    return strongEncryptionAvaialble;
}

From source file:org.sakaiproject.tool.rutgers.LinkTool.java

/**
 * Generate a secret key, and write it to a file
 * //w w  w. j  a  v a 2 s. c o m
 * @param dirname
 *        writes to file privkeyname in this 
 *        directory. dirname assumed to end in /
 */

private void genkey(String dirname) {

    try {
        /* Generate key. */
        M_log.info("Generating new key in " + dirname + privkeyname);
        SecretKey key = KeyGenerator.getInstance("Blowfish").generateKey();

        /* Write private key to file. */
        writeKey(key, dirname + privkeyname);
    } catch (Exception e) {
        M_log.debug("Error generating key", e);
    }

}

From source file:org.sakaiproject.tool.rutgers.LinkTool.java

/**
 * Generate a random salt, and write it to a file
 * /*from  w  ww .j av  a 2 s  . co m*/
 * @param dirname
 *        writes to file saltname in this 
 *        directory. dirname assumed to end in /
 */

private void gensalt(String dirname) {
    try {
        // Generate a key for the HMAC-SHA1 keyed-hashing algorithm
        KeyGenerator keyGen = KeyGenerator.getInstance("HmacSHA1");
        SecretKey key = keyGen.generateKey();
        writeKey(key, dirname + saltname);
    } catch (Exception e) {
        M_log.debug("Error generating salt", e);
    }
}

From source file:com.cloud.migration.Db20to21MigrationUtil.java

private void updateSSOKey() {
    try {//from w w  w . ja  v  a2  s  . 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.apache.rampart.util.RampartUtil.java

public static KeyGenerator getEncryptionKeyGenerator(String symEncrAlgo) throws WSSecurityException {
    KeyGenerator keyGen;//from   w  w w  . j av  a2s . c  om
    try {
        /*
         * Assume AES as default, so initialize it
         */
        keyGen = KeyGenerator.getInstance("AES");
        if (symEncrAlgo.equalsIgnoreCase(WSConstants.TRIPLE_DES)) {
            keyGen = KeyGenerator.getInstance("DESede");
        } else if (symEncrAlgo.equalsIgnoreCase(WSConstants.AES_128)) {
            keyGen.init(128);
        } else if (symEncrAlgo.equalsIgnoreCase(WSConstants.AES_192)) {
            keyGen.init(192);
        } else if (symEncrAlgo.equalsIgnoreCase(WSConstants.AES_256)) {
            keyGen.init(256);
        } else {
            return null;
        }
    } catch (NoSuchAlgorithmException e) {
        throw new WSSecurityException(WSSecurityException.UNSUPPORTED_ALGORITHM, null, null, e);
    }
    return keyGen;
}

From source file:com.datatorrent.lib.io.fs.AbstractFileOutputOperatorTest.java

@Test
public void testChainFilters() throws NoSuchAlgorithmException, IOException {
    EvenOddHDFSExactlyOnceWriter writer = new EvenOddHDFSExactlyOnceWriter();
    KeyGenerator keygen = KeyGenerator.getInstance("AES");
    keygen.init(128);//  ww w  .  j a va  2  s  .  c o m
    final SecretKey secretKey = keygen.generateKey();
    byte[] iv = "TestParam16bytes".getBytes();
    final IvParameterSpec ivps = new IvParameterSpec(iv);
    FilterStreamProvider.FilterChainStreamProvider<FilterOutputStream, OutputStream> chainStreamProvider = new FilterStreamProvider.FilterChainStreamProvider<FilterOutputStream, OutputStream>();
    chainStreamProvider.addStreamProvider(new FilterStreamCodec.GZipFilterStreamProvider());

    // The filter is to keep track of the offsets to handle multi member gzip issue with openjdk
    // http://bugs.java.com/bugdatabase/view_bug.do?bug_id=4691425
    final CounterFilterStreamContext evenCounterContext = new CounterFilterStreamContext();
    final CounterFilterStreamContext oddCounterContext = new CounterFilterStreamContext();
    chainStreamProvider.addStreamProvider(
            new FilterStreamProvider.SimpleFilterReusableStreamProvider<CounterFilterOutputStream, OutputStream>() {
                @Override
                protected FilterStreamContext<CounterFilterOutputStream> createFilterStreamContext(
                        OutputStream outputStream) throws IOException {
                    if (evenCounterContext.isDoInit()) {
                        evenCounterContext.init(outputStream);
                        return evenCounterContext;
                    } else {
                        oddCounterContext.init(outputStream);
                        return oddCounterContext;
                    }
                }
            });
    chainStreamProvider.addStreamProvider(
            new FilterStreamProvider.SimpleFilterReusableStreamProvider<CipherOutputStream, OutputStream>() {
                @Override
                protected FilterStreamContext<CipherOutputStream> createFilterStreamContext(
                        OutputStream outputStream) throws IOException {
                    try {
                        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
                        cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivps);
                        return new FilterStreamCodec.CipherFilterStreamContext(outputStream, cipher);
                    } catch (Exception e) {
                        throw new IOException(e);
                    }
                }
            });
    writer.setFilterStreamProvider(chainStreamProvider);

    File evenFile = new File(testMeta.getDir(), EVEN_FILE);
    File oddFile = new File(testMeta.getDir(), ODD_FILE);

    List<Long> evenOffsets = new ArrayList<Long>();
    List<Long> oddOffsets = new ArrayList<Long>();

    writer.setFilePath(testMeta.getDir());
    writer.setAlwaysWriteToTmp(false);
    writer.setup(testMeta.testOperatorContext);

    for (int i = 0; i < 10; ++i) {
        writer.beginWindow(i);
        for (int j = 0; j < 1000; ++j) {
            writer.input.put(i);
        }
        writer.endWindow();
        if ((i % 2) == 1) {
            writer.beforeCheckpoint(i);
            evenOffsets.add(evenCounterContext.getCounter());
            oddOffsets.add(oddCounterContext.getCounter());
        }
    }

    writer.teardown();

    /*
    evenOffsets.add(evenFile.length());
    oddOffsets.add(oddFile.length());
    */

    checkCompressedFile(evenFile, evenOffsets, 0, 5, 1000, secretKey, iv);
    checkCompressedFile(oddFile, oddOffsets, 1, 5, 1000, secretKey, iv);
}

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  w  w.j  a va2 s .  c  om*/
    keyGenerator.init(128, sr); // 192 and 256 bits may not be available
    SecretKey secretKey = keyGenerator.generateKey();
    return secretKey.getEncoded();
}

From source file:com.cloud.user.AccountManagerImpl.java

private String createUserApiKey(long userId) {
    try {/*from  w  w w  .  j a  va  2 s. c  o  m*/
        UserVO updatedUser = _userDao.createForUpdate();

        String encodedKey = null;
        Pair<User, Account> userAcct = null;
        int retryLimit = 10;
        do {
            // FIXME: what algorithm should we use for API keys?
            KeyGenerator generator = KeyGenerator.getInstance("HmacSHA1");
            SecretKey key = generator.generateKey();
            encodedKey = Base64.encodeBase64URLSafeString(key.getEncoded());
            userAcct = _accountDao.findUserAccountByApiKey(encodedKey);
            retryLimit--;
        } while ((userAcct != null) && (retryLimit >= 0));

        if (userAcct != null) {
            return null;
        }
        updatedUser.setApiKey(encodedKey);
        _userDao.update(userId, updatedUser);
        return encodedKey;
    } catch (NoSuchAlgorithmException ex) {
        s_logger.error("error generating secret key for user id=" + userId, ex);
    }
    return null;
}

From source file:com.cloud.user.AccountManagerImpl.java

private String createUserSecretKey(long userId) {
    try {//w ww .  ja v a2 s.  c  o  m
        UserVO updatedUser = _userDao.createForUpdate();
        String encodedKey = null;
        int retryLimit = 10;
        UserVO userBySecretKey = null;
        do {
            KeyGenerator generator = KeyGenerator.getInstance("HmacSHA1");
            SecretKey key = generator.generateKey();
            encodedKey = Base64.encodeBase64URLSafeString(key.getEncoded());
            userBySecretKey = _userDao.findUserBySecretKey(encodedKey);
            retryLimit--;
        } while ((userBySecretKey != null) && (retryLimit >= 0));

        if (userBySecretKey != null) {
            return null;
        }

        updatedUser.setSecretKey(encodedKey);
        _userDao.update(userId, updatedUser);
        return encodedKey;
    } catch (NoSuchAlgorithmException ex) {
        s_logger.error("error generating secret key for user id=" + userId, ex);
    }
    return null;
}