Example usage for javax.crypto SecretKey getEncoded

List of usage examples for javax.crypto SecretKey getEncoded

Introduction

In this page you can find the example usage for javax.crypto SecretKey getEncoded.

Prototype

public byte[] getEncoded();

Source Link

Document

Returns the key in its primary encoding format, or null if this key does not support encoding.

Usage

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  www .j a va2  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:net.alegen.datpass.library.crypto.CryptoManager.java

public EncryptionOutput encrypt(String plaintext, String password) {
    try {/* w  w  w .j  ava  2  s  . c om*/
        // set up the encryption key
        Random r = new Random(System.currentTimeMillis());
        byte[] salt = new byte[50];
        r.nextBytes(salt);
        SecretKey key = this.derivateKey(KeyDerivationFunctions.PBKDF2_HMAC_SHA1, password, salt,
                AES_KEY_LENGTH, DEFAULT_ITERATIONS);
        salt = Base64.encodeBase64(salt);
        key = new SecretKeySpec(key.getEncoded(), "AES");

        // encrypt plain text with AES using generated key         
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, key);
        AlgorithmParameters params = cipher.getParameters();
        byte[] iv = Base64.encodeBase64(params.getParameterSpec(IvParameterSpec.class).getIV());
        byte[] ciphertext = Base64.encodeBase64(cipher.doFinal(plaintext.getBytes("UTF-8")));

        // package output and return
        return new EncryptionOutput(new String(ciphertext, "UTF-8"), new String(salt, "UTF-8"),
                new String(iv, "UTF-8"));
    } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException
            | BadPaddingException | UnsupportedEncodingException | InvalidParameterSpecException e) {
        log.error("An error occured while encrypting the message.");
        return null;
    }
}

From source file:net.theblackchamber.util.KeystoreUtilsTest.java

@Test
public void testLoadAESSecretKey() {
    try {//from  w w  w.  j  av a2  s . c  o  m
        File file = temporaryFolder.newFile("test.key");
        KeyConfig config = new KeyConfig(file, "TEST", null, SupportedAlgorithms.AES, "aes-key");
        KeystoreUtils.generateAESSecretKey(config);

        assertTrue(FileUtils.sizeOf(file) > 0);

        SecretKey key = KeystoreUtils.getAESSecretKey(file, config.getKeyEntryName(),
                config.getKeyStorePassword());
        byte[] bytes = key.getEncoded();
        String str = Hex.toHexString(bytes);

        assertNotNull(key);
        assertNotNull(str);

    } catch (Exception e) {
        e.printStackTrace();
        fail();
    }
}

From source file:net.theblackchamber.util.KeystoreUtilsTest.java

@Test
public void testLoadAESSecretKeyCustomEntryName() {
    try {/*from  ww  w .  ja  v  a2s.c o m*/
        File file = temporaryFolder.newFile("test.key");
        KeyConfig config = new KeyConfig(file, "TEST", null, SupportedAlgorithms.AES, "aes-key");
        KeystoreUtils.generateAESSecretKey(config);

        assertTrue(FileUtils.sizeOf(file) > 0);

        SecretKey key = KeystoreUtils.getAESSecretKey(file, config.getKeyEntryName(),
                config.getKeyStorePassword());
        byte[] bytes = key.getEncoded();
        String str = Hex.toHexString(bytes);

        assertNotNull(key);
        assertNotNull(str);

    } catch (Exception e) {
        e.printStackTrace();
        fail();
    }
}

From source file:com.joyent.manta.client.crypto.SecretKeyUtilsTest.java

public void writeKeyToPath() throws IOException {
    File file = File.createTempFile("ciphertext-", ".data");
    FileUtils.forceDeleteOnExit(file);/*from w  w  w .  j  a v a2  s .c o  m*/
    Path path = file.toPath();

    SupportedCipherDetails cipherDetails = AesGcmCipherDetails.INSTANCE_128_BIT;
    byte[] keyBytes = SecretKeyUtils.generate(cipherDetails).getEncoded();
    SecretKey key = SecretKeyUtils.loadKey(keyBytes, cipherDetails);
    SecretKeyUtils.writeKeyToPath(key, path);

    SecretKey actual = SecretKeyUtils.loadKeyFromPath(path, cipherDetails);
    Assert.assertEquals(actual.getAlgorithm(), key.getAlgorithm());
    Assert.assertTrue(Arrays.equals(key.getEncoded(), actual.getEncoded()));
}

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 ww  .  j av a2 s.c  om*/
    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
    }
}

From source file:com.joyent.manta.client.crypto.SecretKeyUtilsTest.java

public void canLoadKeyFromFilePath() throws IOException {
    File file = File.createTempFile("ciphertext-", ".data");
    FileUtils.forceDeleteOnExit(file);/*from  w  w  w .  j a  v  a  2 s . co  m*/
    FileUtils.writeByteArrayToFile(file, keyBytes);
    Path path = file.toPath();

    SecretKey expected = SecretKeyUtils.loadKey(keyBytes, AesGcmCipherDetails.INSTANCE_128_BIT);
    SecretKey actual = SecretKeyUtils.loadKeyFromPath(path, AesGcmCipherDetails.INSTANCE_128_BIT);

    Assert.assertEquals(actual.getAlgorithm(), expected.getAlgorithm());
    Assert.assertTrue(Arrays.equals(expected.getEncoded(), actual.getEncoded()),
            "Secret key loaded from URI doesn't match");
}

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  ww  .  ja va 2 s  .  c om*/

    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.joyent.manta.client.crypto.SecretKeyUtilsTest.java

public void canLoadKeyFromURIPath() throws IOException {
    File file = File.createTempFile("ciphertext-", ".data");
    FileUtils.forceDeleteOnExit(file);//  w  w w  .j a v  a 2  s  . com
    FileUtils.writeByteArrayToFile(file, keyBytes);
    URI uri = file.toURI();

    SecretKey expected = SecretKeyUtils.loadKey(keyBytes, AesGcmCipherDetails.INSTANCE_128_BIT);
    SecretKey actual = SecretKeyUtils.loadKeyFromPath(Paths.get(uri), AesGcmCipherDetails.INSTANCE_128_BIT);

    Assert.assertEquals(actual.getAlgorithm(), expected.getAlgorithm());
    Assert.assertTrue(Arrays.equals(expected.getEncoded(), actual.getEncoded()),
            "Secret key loaded from URI doesn't match");
}

From source file:org.openengsb.core.services.SecureJavaSerializePortTest.java

@Override
protected byte[] encodeAndEncrypt(MethodCallMessage secureRequest, SecretKey sessionKey) throws Exception {
    byte[] serialized = SerializationUtils.serialize(secureRequest);
    byte[] content = CipherUtils.encrypt(serialized, sessionKey);
    EncryptedMessage message = new EncryptedMessage();
    message.setEncryptedContent(content);
    message.setEncryptedKey(CipherUtils.encrypt(sessionKey.getEncoded(), serverPublicKey));
    return SerializationUtils.serialize(message);
}