Example usage for javax.crypto KeyGenerator init

List of usage examples for javax.crypto KeyGenerator init

Introduction

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

Prototype

public final void init(int keysize, SecureRandom random) 

Source Link

Document

Initializes this key generator for a certain keysize, using a user-provided source of randomness.

Usage

From source file:info.fcrp.keepitsafe.bean.CryptBeanTest.java

@Test
public void symetric() throws NoSuchAlgorithmException, NoSuchProviderException, NoSuchPaddingException,
        InvalidKeyException, IllegalBlockSizeException, BadPaddingException {

    KeyGenerator kg = KeyGenerator.getInstance("AES");
    kg.init(256, new SecureRandom());
    Key k = kg.generateKey();/*from  w  w w .  ja  v a 2s . c o  m*/

    Cipher c = Cipher.getInstance("AES");
    String plain = "plain";
    byte[] plainBytes = plain.getBytes();

    c.init(Cipher.ENCRYPT_MODE, k);
    c.update(plainBytes);

    byte[] encBytes = c.doFinal();
    String enc = Base64.encodeBase64String(encBytes);
    assertNotSame(plain, enc);

    c.init(Cipher.DECRYPT_MODE, k);
    c.update(encBytes);
    byte[] decBytes = c.doFinal();
    String dec = new String(decBytes);

    assertEquals(plain, dec);
}

From source file:org.sonar.api.config.AesCipher.java

String generateRandomSecretKey() {
    try {//from ww w  .  ja  va2s .com
        KeyGenerator keyGen = KeyGenerator.getInstance(CRYPTO_KEY);
        keyGen.init(KEY_SIZE_IN_BITS, new SecureRandom());
        SecretKey secretKey = keyGen.generateKey();
        return new String(Base64.encodeBase64(secretKey.getEncoded()));

    } catch (Exception e) {
        throw new IllegalStateException("Fail to generate secret key", e);
    }
}

From source file:org.sonar.process.AesCipher.java

String generateRandomSecretKey() {
    try {/*from   w  ww .  j  ava  2 s .com*/
        KeyGenerator keyGen = KeyGenerator.getInstance(CRYPTO_KEY);
        keyGen.init(KEY_SIZE_IN_BITS, new SecureRandom());
        SecretKey secretKey = keyGen.generateKey();
        return Base64.encodeBase64String(secretKey.getEncoded());

    } catch (Exception e) {
        throw new IllegalStateException("Fail to generate secret key", e);
    }
}

From source file:com.adaptris.security.password.AesCrypto.java

public String encode(String plainText, String charset) throws PasswordException {
    String result = null;/*from  w w w .  j  a v a2s.c o  m*/
    try {
        KeyGenerator kg = KeyGenerator.getInstance(ALG);
        kg.init(KEY_LEN, SecurityUtil.getSecureRandom());
        SecretKey sessionKey = kg.generateKey();
        Cipher dataCipher = Cipher.getInstance(CIPHER);
        dataCipher.init(Cipher.ENCRYPT_MODE, sessionKey);
        byte[] encryptedBody = dataCipher.doFinal(seed(plainText, charset));
        Output output = new Output();
        output.setSessionKey(sessionKey.getEncoded());
        output.setSessionVector(dataCipher.getIV());
        output.setEncryptedData(encryptedBody);
        result = Password.PORTABLE_PASSWORD + output.write();
    } catch (Exception e) {
        throw new PasswordException(e);
    }
    return result;
}

From source file:org.talend.utils.security.AES.java

public AES() {
    try {/*from  w w  w.  ja  v  a  2s  . com*/
        // TDI-28380: Database password in tac db configuration page becomes empty once restart tomcat on Solaris.
        // TDI-30348: Whole tac configuration lost for the passwords.

        Provider p = Security.getProvider("BC");
        KeyGenerator keyGen = KeyGenerator.getInstance(ENCRYPTION_ALGORITHM, p);

        SecureRandom random = SecureRandom.getInstance(RANDOM_SHA1PRNG);
        random.setSeed(KeyValues);
        keyGen.init(128, random);

        Key key = keyGen.generateKey();

        ecipher = Cipher.getInstance(ENCRYPTION_ALGORITHM, p);
        dcipher = Cipher.getInstance(ENCRYPTION_ALGORITHM, p);

        ecipher.init(Cipher.ENCRYPT_MODE, key);
        dcipher.init(Cipher.DECRYPT_MODE, key);
    } catch (Exception e) {
        // log the error to avoid that break GWT service
        log.error(e.getMessage(), e);
    }
}

From source file:com.POLIS.licensing.common.license.AbstractSerializationBasedLicense.java

@Override
public String getEncryptedLicense(PublicKey targetKey) throws SystemStateException, OperationException {
    byte[] licenseAsBytes;
    try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
            ObjectOutput out = new ObjectOutputStream(bos)) {
        out.writeObject(this);
        licenseAsBytes = bos.toByteArray();
    } catch (IOException ex) {
        throw new OperationException("An error occured while serializing the license", ex);
    }/*from w w w .j  a v  a 2 s. c o m*/
    SecureRandom random = new SecureRandom();
    Cipher aescipher;
    Cipher rsacipher;

    KeyGenerator aesgenerator;
    Key symkey;
    try {
        aesgenerator = KeyGenerator.getInstance(symmetricKeyType, provider);
        aesgenerator.init(128, random);
        symkey = aesgenerator.generateKey();
    } catch (NoSuchAlgorithmException | NoSuchProviderException ex) {
        throw new SystemStateException("The specified symkey could not be generated.", ex);
    }

    try {
        aescipher = Cipher.getInstance(symmetricEncoding, provider);
        rsacipher = Cipher.getInstance(asymmetricEncoding, provider);

        aescipher.init(Cipher.ENCRYPT_MODE, symkey);
        rsacipher.init(Cipher.ENCRYPT_MODE, targetKey);
    } catch (NoSuchAlgorithmException | NoSuchProviderException
            | /*InvalidKeySpecException |*/ NoSuchPaddingException | InvalidKeyException ex) {
        throw new SystemStateException("The specified encryption provider or algorithm was not found", ex);
    }

    String encryptedLicense;
    try {
        byte[] encryptedsymkey = rsacipher.doFinal(symkey.getEncoded());

        byte[] encryptedlicense = aescipher.doFinal(licenseAsBytes);
        byte[] licenseWithKey = new byte[encryptedsymkey.length + encryptedlicense.length];
        System.arraycopy(encryptedsymkey, 0, licenseWithKey, 0, encryptedsymkey.length);
        System.arraycopy(encryptedlicense, 0, licenseWithKey, encryptedsymkey.length, encryptedlicense.length);
        encryptedLicense = Base64.encodeBase64String(licenseWithKey);
    } catch (IllegalBlockSizeException | BadPaddingException ex) {
        throw new OperationException("Could not encode to base64", ex);
    }
    return encryptedLicense;

}

From source file:com.floragunn.searchguard.service.SearchGuardService.java

@Inject
public SearchGuardService(final Settings settings, final RestController restController, final Client client,
        final Authorizator authorizator, final AuthenticationBackend authenticationBackend,
        final HTTPAuthenticator httpAuthenticator, final SessionStore sessionStore,
        final AuditListener auditListener, final SearchService searchService) {
    super(settings);
    this.restController = restController;
    this.client = client;
    this.settings = settings;
    //securityConfigurationIndex = settings
    //        .get(ConfigConstants.SEARCHGUARD_CONFIG_INDEX_NAME, ConfigConstants.DEFAULT_SECURITY_CONFIG_INDEX);
    this.authenticationBackend = authenticationBackend;
    this.authorizator = authorizator;
    this.httpAuthenticator = httpAuthenticator;
    this.sessionStore = sessionStore;

    try {/*from  w  w  w  .ja  v  a 2 s  .  c  o m*/
        method = RestController.class.getDeclaredMethod("getHandler", RestRequest.class);
        method.setAccessible(true);
    } catch (final Exception e) {
        log.error(e.toString(), e);
        throw new ElasticsearchException(e.toString());
    }

    try {
        searchServiceSetCallbackMethod = SearchService.class.getDeclaredMethod("setCallback",
                SearchContextCallback.class);
        searchServiceSetCallbackMethod.invoke(searchService,
                new ConfigurableSearchContextCallback(settings, auditListener));
    } catch (final Exception e) {
        log.error(e.toString(), e);
        //throw new ElasticsearchException(e.toString());
    }

    this.auditListener = auditListener;
    //TODO FUTURE index change audit trail

    final String keyPath = settings.get(ConfigConstants.SEARCHGUARD_KEY_PATH, ".");
    SecretKey sc = null;
    try {

        final File keyFile = new File(keyPath, "searchguard_node_key.key");

        if (keyFile.exists()) {
            log.debug("Loaded key from {}", keyFile.getAbsolutePath());
            sc = new SecretKeySpec(FileUtils.readFileToByteArray(keyFile), "AES");
        } else {

            final SecureRandom secRandom = SecureRandom.getInstance("SHA1PRNG");
            final KeyGenerator kg = KeyGenerator.getInstance("AES");
            kg.init(128, secRandom);
            final SecretKey secretKey = kg.generateKey();
            final byte[] enckey = secretKey.getEncoded();

            if (enckey == null || enckey.length != 16) {
                throw new Exception("invalid key " + (enckey == null ? -1 : enckey.length));
            }
            FileUtils.writeByteArrayToFile(keyFile, enckey);
            sc = secretKey;
            log.info("New key written to {}, make sure all nodes have this key", keyFile.getAbsolutePath());
        }

    } catch (final Exception e) {
        log.error("Cannot generate or read secrety key", e);
        throw new ElasticsearchException(e.toString());
    }

    final boolean checkForRoot = settings.getAsBoolean(ConfigConstants.SEARCHGUARD_CHECK_FOR_ROOT, true);

    if (SecurityUtil.isRootUser()) {

        if (checkForRoot) {
            throw new ElasticsearchException(
                    "You're trying to run elasticsearch as root or Windows Administrator and thats forbidden.");
        } else {
            log.warn(
                    "You're trying to run elasticsearch as root or Windows Administrator! Thats a potential security issue.");
        }

    }

    /*final String scriptingStatus = settings.get(ScriptService.DISABLE_DYNAMIC_SCRIPTING_SETTING,
        ScriptService.DISABLE_DYNAMIC_SCRIPTING_DEFAULT);
            
    if (scriptingStatus.equalsIgnoreCase(ScriptService.DISABLE_DYNAMIC_SCRIPTING_DEFAULT)) {
    log.warn("{} has the default value {}, consider setting it to false if not needed",
            ScriptService.DISABLE_DYNAMIC_SCRIPTING_SETTING, scriptingStatus);
    }
            
    if (scriptingStatus.equalsIgnoreCase("true")) {
    log.error("{} is configured insecure, consider setting it to false or " + ScriptService.DISABLE_DYNAMIC_SCRIPTING_DEFAULT,
            ScriptService.DISABLE_DYNAMIC_SCRIPTING_SETTING);
    }*/

    if (searchService == null) {
        throw new RuntimeException("ssnull");
    }

    SearchGuardService.secretKey = sc;
}

From source file:com.petalmd.armor.service.ArmorService.java

@Inject
public ArmorService(final Settings settings, final RestController restController, final Client client,
        final Authorizator authorizator, final AuthenticationBackend authenticationBackend,
        final HTTPAuthenticator httpAuthenticator, final SessionStore sessionStore,
        final AuditListener auditListener, final SearchService searchService) {
    super(settings);
    this.restController = restController;
    this.client = client;
    this.settings = settings;
    //securityConfigurationIndex = settings
    //        .get(ConfigConstants.ARMOR_CONFIG_INDEX_NAME, ConfigConstants.DEFAULT_SECURITY_CONFIG_INDEX);
    this.authenticationBackend = authenticationBackend;
    this.authorizator = authorizator;
    this.httpAuthenticator = httpAuthenticator;
    this.sessionStore = sessionStore;

    SecurityManager sm = System.getSecurityManager();
    if (sm != null) {
        sm.checkPermission(new SpecialPermission());
    }//from   w w  w.  ja  v  a 2s  .  c o m

    try {
        AccessController.doPrivileged(new PrivilegedExceptionAction<Boolean>() {
            @Override
            public Boolean run() throws Exception {
                method = RestController.class.getDeclaredMethod("getHandler", RestRequest.class);
                method.setAccessible(true);

                return true;
            }
        });
    } catch (final Exception e) {
        log.error(e.toString(), e);
        throw new ElasticsearchException(e.toString());
    }

    final String keyPath = settings.get(ConfigConstants.ARMOR_KEY_PATH, ".");
    //        AccessController.checkPermission(new FilePermission(keyPath+File.separator+"armor_node_key.key", "write"));
    SecretKey sc = null;
    try {
        sc = AccessController.doPrivileged(new PrivilegedExceptionAction<SecretKey>() {
            @Override
            public SecretKey run() throws Exception {
                final File keyFile = new File(keyPath, "armor_node_key.key");
                SecretKey sc = null;
                if (keyFile.exists()) {
                    log.debug("Loaded key from {}", keyFile.getAbsolutePath());
                    sc = new SecretKeySpec(FileUtils.readFileToByteArray(keyFile), "AES");
                } else {
                    final SecureRandom secRandom = SecureRandom.getInstance("SHA1PRNG");
                    final KeyGenerator kg = KeyGenerator.getInstance("AES");
                    kg.init(128, secRandom);
                    final SecretKey secretKey = kg.generateKey();
                    final byte[] enckey = secretKey.getEncoded();

                    if (enckey == null || enckey.length != 16) {
                        throw new Exception("invalid key " + (enckey == null ? -1 : enckey.length));
                    }
                    FileUtils.writeByteArrayToFile(keyFile, enckey);
                    sc = secretKey;
                    log.info("New key written to {}, make sure all nodes have this key",
                            keyFile.getAbsolutePath());
                }
                return sc;
            }
        });
    } catch (final Exception e) {
        log.error("Cannot generate or read secrety key", e);
        throw new ElasticsearchException(e.toString());
    }

    this.auditListener = auditListener;
    //TODO FUTURE index change audit trail

    final boolean checkForRoot = settings.getAsBoolean(ConfigConstants.ARMOR_CHECK_FOR_ROOT, true);

    if (SecurityUtil.isRootUser()) {

        if (checkForRoot) {
            throw new ElasticsearchException(
                    "You're trying to run elasticsearch as root or Windows Administrator and thats forbidden.");
        } else {
            log.warn(
                    "You're trying to run elasticsearch as root or Windows Administrator! Thats a potential security issue.");
        }

    }

    /*final String scriptingStatus = settings.get(ScriptService.DISABLE_DYNAMIC_SCRIPTING_SETTING,
        ScriptService.DISABLE_DYNAMIC_SCRIPTING_DEFAULT);
            
    if (scriptingStatus.equalsIgnoreCase(ScriptService.DISABLE_DYNAMIC_SCRIPTING_DEFAULT)) {
    log.warn("{} has the default value {}, consider setting it to false if not needed",
            ScriptService.DISABLE_DYNAMIC_SCRIPTING_SETTING, scriptingStatus);
    }
            
    if (scriptingStatus.equalsIgnoreCase("true")) {
    log.error("{} is configured insecure, consider setting it to false or " + ScriptService.DISABLE_DYNAMIC_SCRIPTING_DEFAULT,
            ScriptService.DISABLE_DYNAMIC_SCRIPTING_SETTING);
    }*/
    if (searchService == null) {
        throw new RuntimeException("ssnull");
    }

    ArmorService.secretKey = sc;
}

From source file:org.lsc.utils.security.SymmetricEncryption.java

/**
 * Generate a random key file./*from  w w  w  .ja  v  a2s .  c  o  m*/
 * @param keyPath The filename where to write the key
 * @param algo The supported algorithm to use
 * @param strength The encryption strength
 * @return boolean false if an error occurred
 * @throws NoSuchAlgorithmException 
 * @throws NoSuchProviderException 
 */
public boolean generateRandomKeyFile(String keyPath, String algo, int strength)
        throws NoSuchAlgorithmException, NoSuchProviderException {
    OutputStream os = null;
    try {
        KeyGenerator kg = KeyGenerator.getInstance(algo, securityProvider.getName());
        SecretKey cipherKey = kg.generateKey();
        SecureRandom sr = new SecureRandom();
        kg.init(strength, sr);
        os = new FileOutputStream(keyPath);
        os.write(cipherKey.getEncoded());
    } catch (IOException e) {
        LOGGER.error("Unable to write new generated key in " + keyPath + ". Encountered exception is : "
                + e.getLocalizedMessage(), e);
        return false;
    } finally {
        try {
            if (os != null) {
                os.close();
            }
        } catch (IOException e1) {
        }
    }
    return true;
}

From source file:net.sourceforge.jencrypt.lib.CryptoWrapper.java

private Key getInitializationVector(CryptoWrapperBuilder builder) throws NoSuchAlgorithmException {

    KeyGenerator generator = KeyGenerator.getInstance(builder.cipherName);
    generator.init(CryptoWrapper.AES_BLOCK_SIZE_IN_BITS, new SecureRandom());
    return generator.generateKey();
}