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:org.sonatype.sisu.encryptor.RsaAesEncryptor.java

public void encrypt(InputStream plainInput, OutputStream encryptedOutput, PublicKey key)
        throws IOException, GeneralSecurityException {
    KeyGenerator kgen = KeyGenerator.getInstance("AES");
    kgen.init(KEY_SIZE);/*from  www  . j a v a 2s. co m*/

    SecretKey aesKey = kgen.generateKey();

    byte[] data = IOUtil.toByteArray(plainInput);
    byte[] encryptedData = getCipher("AES", aesKey, Cipher.ENCRYPT_MODE).doFinal(data);

    byte[] raw = aesKey.getEncoded();
    byte[] encryptedKey = getCipher("RSA/ECB/PKCS1Padding", key, javax.crypto.Cipher.ENCRYPT_MODE).doFinal(raw);

    // useful when debugging but can't be left uncommented due to NEXUS-2530
    // if ( getLogger().isDebugEnabled() )
    // {
    // log.debug( "before encrypt: " + new String( Base64.encodeBase64( raw ) ) );
    // log.debug( "Encrypted key: " + new String( Base64.encodeBase64( encryptedKey ) ) );
    // log.debug( "Encrypted data: " + new String( Base64.encodeBase64( encryptedData ) ) );
    // }

    Base64OutputStream output = new Base64OutputStream(encryptedOutput);
    IOUtil.copy(encryptedKey, output);
    IOUtil.copy(encryptedData, output);
    output.close();
    encryptedOutput.flush();
}

From source file:org.apache.hadoop.mapreduce.security.TestTokenCache.java

private static void createTokenFileJson() throws IOException {
    Map<String, String> map = new HashMap<String, String>();

    try {/*from  w  w w .  ja v a  2s .  c om*/
        KeyGenerator kg = KeyGenerator.getInstance("HmacSHA1");
        for (int i = 0; i < NUM_OF_KEYS; i++) {
            SecretKeySpec key = (SecretKeySpec) kg.generateKey();
            byte[] enc_key = key.getEncoded();
            map.put("alias" + i, new String(Base64.encodeBase64(enc_key)));

        }
    } catch (NoSuchAlgorithmException e) {
        throw new IOException(e);
    }

    try {
        File p = new File(tokenFileName.getParent().toString());
        p.mkdirs();
        // convert to JSON and save to the file
        mapper.writeValue(new File(tokenFileName.toString()), map);

    } catch (Exception e) {
        System.out.println("failed with :" + e.getLocalizedMessage());
    }
}

From source file:org.nuxeo.ecm.core.blob.binary.TestAESBinaryManager.java

protected void createKeyStore(File file) throws GeneralSecurityException, IOException {
    AESBinaryManager.setUnlimitedJCEPolicy();

    KeyGenerator kgen = KeyGenerator.getInstance("AES");
    kgen.init(256);/*from  w  w  w .j a v a  2 s  .c om*/
    Key skey = kgen.generateKey();
    KeyStore keyStore = KeyStore.getInstance(KEY_STORE_TYPE);
    // keyStore.load(null, KEY_STORE_PASSWORD.toCharArray());
    keyStore.load(null, null);
    keyStore.setKeyEntry(KEY_ALIAS, skey, KEY_PASSWORD.toCharArray(), null);
    OutputStream out = new FileOutputStream(file);
    keyStore.store(out, KEY_STORE_PASSWORD.toCharArray());
    out.close();
}

From source file:org.craftercms.security.authentication.impl.CipheredAuthenticationCookieFactory.java

/**
 * Generates a random encryption key.//from ww w . ja  v a  2 s  .c o m
 */
protected Key generateRandomKey() throws CrafterSecurityException {
    KeyGenerator keyGenerator;
    try {
        keyGenerator = KeyGenerator.getInstance(CIPHER_ALGORITHM);
        keyGenerator.init(secureRandom);

        return keyGenerator.generateKey();
    } catch (Exception e) {
        throw new CrafterSecurityException("Unable to generate random encryption key", e);
    }
}

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 {/* w w  w .  j a  v a  2 s. co 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());
    }//  w  ww . ja  v  a2  s. co 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:com.tcloud.bee.key.server.service.impl.KeyManageServiceImpl.java

@Override
public QueryResult createKey(Param param, String owner)
        throws NoSuchAlgorithmException, FileNotFoundException, IOException {
    logger.info("User is trying to create key. userName:" + owner + ", keyName:" + param.getKeyName());
    File newKeyfile = new File(env.getProperty("keyfile.path") + param.getKeyName());
    if (newKeyfile.exists()) {
        logger.info("keyName \"" + param.getKeyName() + "\" exists, please choose another keyName.");
        return new QueryResult(BeeConstants.ResponseStatus.FAIL,
                BeeConstants.ErrorMap.get(BeeConstants.ResponseCode.ERROR_KM_KEYNAME_EXISTS), null);
    }// w  w  w.j  a v a  2  s  .c  om

    KeyGenerator keyGen = KeyGenerator.getInstance("AES");
    keyGen.init(256);
    SecretKey secretKey = keyGen.generateKey();
    String hexkey = Hex.encodeHexString(secretKey.getEncoded());

    Properties prop = new Properties();
    prop.setProperty("owner", owner);
    prop.setProperty("keyName", param.getKeyName());
    prop.setProperty("hexkey", hexkey);
    prop.setProperty("users", param.getUsers());

    File keyFileFolder = new File(env.getProperty("keyfile.path"));
    if (!keyFileFolder.exists()) {
        keyFileFolder.mkdirs();
        Runtime.getRuntime().exec("chmod 700 " + env.getProperty("keyfile.path"));
    }
    prop.store(new FileOutputStream(env.getProperty("keyfile.path") + param.getKeyName()), null);
    Runtime.getRuntime().exec("chmod 600 " + env.getProperty("keyfile.path") + param.getKeyName());
    logger.info("save keyfile \"{}\" to keyfile folder: {}", param.getKeyName(),
            env.getProperty("keyfile.path"));

    return new QueryResult(BeeConstants.ResponseStatus.SUCCESS, "Key(" + param.getKeyName() + ") created",
            null);
}

From source file:net.spfbl.core.Server.java

private static SecretKey getPrivateKey() {
    if (privateKey == null) {
        try {//from   ww w .  j a  va2s. co  m
            File file = new File("./data/server.key");
            if (file.exists()) {
                FileInputStream fileInputStream = new FileInputStream(file);
                try {
                    privateKey = SerializationUtils.deserialize(fileInputStream);
                } finally {
                    fileInputStream.close();
                }
            } else {
                KeyGenerator keyGen = KeyGenerator.getInstance("AES");
                keyGen.init(new SecureRandom());
                SecretKey key = keyGen.generateKey();
                FileOutputStream outputStream = new FileOutputStream(file);
                try {
                    SerializationUtils.serialize(key, outputStream);
                } finally {
                    outputStream.close();
                }
                privateKey = key;
            }
        } catch (Exception ex) {
            Server.logError(ex);
        }
    }
    return privateKey;
}

From source file:View.Processing.java

private String encryptMessage(String message) {
    String cipher = null;// w w w .  j a v a  2  s.c om
    try {
        String encptionAlgorithm = "DES";
        if (id == 1) {
        }
        SecretKey key = KeyGenerator.getInstance(encptionAlgorithm).generateKey();

    } catch (NoSuchAlgorithmException ex) {
        ex.printStackTrace();
    }

    return cipher;
}

From source file:org.apache.ws.security.message.SignatureAlgorithmSuiteTest.java

@org.junit.Test
public void testSymmetricKey() throws Exception {

    KeyGenerator keyGen = KeyGenerator.getInstance("AES");
    keyGen.init(128);/* w  w w . ja v  a  2 s.  c o  m*/
    SecretKey key = keyGen.generateKey();
    byte[] keyData = key.getEncoded();

    WSSecSignature builder = new WSSecSignature();
    builder.setKeyIdentifierType(WSConstants.ENCRYPTED_KEY_SHA1_IDENTIFIER);
    builder.setSecretKey(keyData);
    builder.setSignatureAlgorithm(SignatureMethod.HMAC_SHA1);

    Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG);
    WSSecHeader secHeader = new WSSecHeader();
    secHeader.insertSecurityHeader(doc);
    Document signedDoc = builder.build(doc, crypto, secHeader);

    if (LOG.isDebugEnabled()) {
        String outputString = XMLUtils.PrettyDocumentToString(signedDoc);
        LOG.debug(outputString);
    }

    byte[] encodedBytes = WSSecurityUtil.generateDigest(keyData);
    String identifier = Base64.encode(encodedBytes);
    SecretKeyCallbackHandler secretKeyCallbackHandler = new SecretKeyCallbackHandler();
    secretKeyCallbackHandler.addSecretKey(identifier, keyData);

    Element securityHeader = WSSecurityUtil.getSecurityHeader(signedDoc, null);
    AlgorithmSuite algorithmSuite = createAlgorithmSuite();

    WSSecurityEngine secEngine = new WSSecurityEngine();
    RequestData data = new RequestData();
    data.setSigCrypto(crypto);
    data.setCallbackHandler(secretKeyCallbackHandler);
    data.setAlgorithmSuite(algorithmSuite);

    try {
        secEngine.processSecurityHeader(securityHeader, data);
        fail("Expected failure as HMAC-SHA1 is not allowed");
    } catch (WSSecurityException ex) {
        // expected
    }

    algorithmSuite.addSignatureMethod(WSConstants.HMAC_SHA1);
    secEngine.processSecurityHeader(securityHeader, data);

    algorithmSuite.setMinimumSymmetricKeyLength(256);
    try {
        secEngine.processSecurityHeader(securityHeader, data);
        fail("Expected failure as a 128 bit key is not allowed");
    } catch (WSSecurityException ex) {
        // expected
    }

    algorithmSuite.setMinimumSymmetricKeyLength(64);
    algorithmSuite.setMaximumSymmetricKeyLength(120);
    try {
        secEngine.processSecurityHeader(securityHeader, data);
        fail("Expected failure as a 128 bit key is not allowed");
    } catch (WSSecurityException ex) {
        // expected
    }
}