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.mhs.hboxmaintenanceserver.utils.Utils.java

/**
 * Blowfish encryption//from  w  ww .  ja  v a  2 s .c o m
 *
 * @param value
 * @return
 * @throws java.lang.Exception
 */
public static String encrypt(String value) throws Exception {
    // create a key generator based upon the Blowfish cipher
    KeyGenerator keygenerator = KeyGenerator.getInstance("Blowfish");

    File file = new File(DefaultConfig.SECRET_KEY);
    SecretKey secretkey;

    if (file.exists()) {
        // Load key from file
        secretkey = new SecretKeySpec(FileUtils.readFileToByteArray(file), "Blowfish");
    } else {
        // create a key
        secretkey = keygenerator.generateKey();
        FileUtils.writeByteArrayToFile(file, secretkey.getEncoded());
    }

    // create a cipher based upon Blowfish
    Cipher cipher = Cipher.getInstance("Blowfish");

    // initialise cipher to with secret key
    cipher.init(Cipher.ENCRYPT_MODE, secretkey);

    // encrypt message
    return bytesToHex(cipher.doFinal(value.getBytes()));
}

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

String generateRandomSecretKey() {
    try {//from   w w  w .j a  va  2 s  .co m
        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:org.sonar.api.config.AesCipher.java

String generateRandomSecretKey() {
    try {/*from   ww w.  java  2  s .  c o m*/
        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:edu.emory.cci.aiw.cvrg.eureka.etl.dest.EurekaCipherDeidConfig.java

@Override
public Key getKey(String keyId) throws KeyCreateException {
    synchronized (this.encryptionAlgorithm) {
        if (this.keyGenerator == null) {
            try {
                this.keyGenerator = this.encryptionAlgorithm.getKeyGeneratorInstance();
            } catch (NoSuchAlgorithmException ex) {
                throw new KeyCreateException(ex);
            }/* ww  w  .j  a  v a2 s  .c om*/
        }
    }
    DeidPerPatientParams byKeyId = this.eurekaDeidConfigDao.getOrCreatePatientParams(keyId, this.destination);
    String keyStr = byKeyId.getCipherKey();
    if (keyStr == null) {
        SecretKey generatedKey = this.keyGenerator.generateKey();
        byte[] encoded = generatedKey.getEncoded();
        byKeyId.setCipherKey(BASE64.encodeToString(encoded));
        this.eurekaDeidConfigDao.update(byKeyId);
        return generatedKey;
    } else {
        byte[] encoded = BASE64.decode(keyStr);
        return new SecretKeySpec(encoded, this.encryptionAlgorithm.getKeyAlgorithm());
    }
}

From source file:piecework.security.concrete.ExampleBouncyCastleEncryptionService.java

@Override
public String generateKey(int keySize)
        throws NoSuchAlgorithmException, InvalidKeySpecException, UnsupportedEncodingException {
    LOG.info("Generating a new encryption key of size " + keySize);
    KeyGenerator keyGen = KeyGenerator.getInstance("AES");
    keyGen.init(keySize);//from  w  w  w .  j  a va 2 s . c o m
    SecretKey secretKey = keyGen.generateKey();
    return new String(Base64.encode(secretKey.getEncoded()), "UTF-8");
}

From source file:org.starnub.utilities.crypto.PasswordHash.java

/**
 * using PBKDF2 from Sun, an alternative is https://github.com/wg/scrypt
 * cf. http://www.unlimitednovelty.com/2012/03/dont-use-bcrypt.html
 * @param password String password to be salted
 * @param salt Byte[] of the salt/*from ww  w  . j a v  a2 s  .  c o  m*/
 * @return String of the hashed password
 * @throws Exception
 */
private String hash(String password, byte[] salt) throws Exception {
    if (password == null || password.length() == 0)
        throw new IllegalArgumentException("Empty passwords are not supported.");
    SecretKeyFactory f = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
    SecretKey key = f.generateSecret(new PBEKeySpec(password.toCharArray(), salt, iterations, desiredKeyLen));
    return Base64.encodeBase64String(key.getEncoded());
}

From source file:org.apache.nifi.processors.standard.util.crypto.KeyedEncryptor.java

public KeyedEncryptor(final EncryptionMethod encryptionMethod, final SecretKey key) {
    this(encryptionMethod, key == null ? new byte[0] : key.getEncoded(), new byte[0]);
}

From source file:org.apache.accumulo.server.security.delegation.AuthenticationKey.java

public AuthenticationKey(int keyId, long creationDate, long expirationDate, SecretKey key) {
    requireNonNull(key);/*from  w  w w . j  a va  2  s. c  o  m*/
    authKey = new TAuthenticationKey(ByteBuffer.wrap(key.getEncoded()));
    authKey.setCreationDate(creationDate);
    authKey.setKeyId(keyId);
    authKey.setExpirationDate(expirationDate);
    this.secret = key;
}

From source file:org.pentaho.di.trans.steps.symmetriccrypto.symmetricalgorithm.SymmetricCrypto.java

public byte[] generateKey(int keySize) throws CryptoKeyException {
    try {//ww  w  .  j a  v a  2 s.  c o  m
        // Get a key generator for algorithm
        KeyGenerator kg = KeyGenerator.getInstance(meta.getAlgorithm());
        // SecureRandom random = new SecureRandom();
        kg.init(keySize);
        // Use it to generate a key
        SecretKey secretKey = kg.generateKey();

        return secretKey.getEncoded();

    } catch (Exception e) {
        throw new CryptoKeyException(e);
    }
}

From source file:org.openengsb.core.util.CipherUtilTest.java

@Test
public void testEncryptSymmetricKeyWithPublicKey_shouldBeTheSameWhenDecryptedWithPrivateKey() throws Exception {
    SecretKey secretKey = CipherUtils.generateKey("AES", 128);

    byte[] encoded = secretKey.getEncoded();
    byte[] encryptedKey = CipherUtils.encrypt(encoded, generatedPublickey);

    byte[] decryptKey = CipherUtils.decrypt(encryptedKey, generatedPrivatekey);
    SecretKeySpec secretKeySpec = new SecretKeySpec(decryptKey, "AES");

    assertThat(secretKeySpec, is(secretKey));
}