Example usage for javax.crypto SecretKeyFactory getInstance

List of usage examples for javax.crypto SecretKeyFactory getInstance

Introduction

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

Prototype

public static final SecretKeyFactory getInstance(String algorithm) throws NoSuchAlgorithmException 

Source Link

Document

Returns a SecretKeyFactory object that converts secret keys of the specified algorithm.

Usage

From source file:JavaTron.JTP.java

/**
 * Encrypts a string// w ww .java  2  s .  c o m
 * @param property
 * @return An encrypted string
 */
public static String encrypt(String property) {
    String p = new String();
    try {
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
        SecretKey key = keyFactory.generateSecret(new PBEKeySpec(PASSWORD));
        Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");
        pbeCipher.init(Cipher.ENCRYPT_MODE, key, new PBEParameterSpec(SALT, 20));
        p = base64Encode(pbeCipher.doFinal(property.getBytes()));
    } catch (Exception e) {
        e.printStackTrace();
    }
    return p;
}

From source file:grails.plugin.springsecurity.authentication.encoding.PBKDF2PasswordEncoder.java

/**
 * Computes the PBKDF2 hash of a password.
 *
 * @param   password    the password to hash.
 * @param   salt        the salt/*from  ww w  . j  a v  a2  s. c om*/
 * @param   iterations  the iteration count (slowness factor)
 * @param   bytes       the length of the hash to compute in bytes
 * @return              the PBDKF2 hash of the password
 */
protected byte[] pbkdf2(char[] password, byte[] salt, int iterations, int bytes) {
    PBEKeySpec spec = new PBEKeySpec(password, salt, iterations, bytes * 8);
    try {
        return SecretKeyFactory.getInstance(PBKDF2_ALGORITHM).generateSecret(spec).getEncoded();
    } catch (InvalidKeySpecException e) {
        throw new RuntimeException(e);
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.anteam.demo.codec.cipher.symmetric.DESedeCoder.java

/**
 * Decodes a byte array and returns the results as a byte array.
 *
 * @param source A byte array which has been encoded with the appropriate encoder
 * @return ?byte.source, null//w  w  w  .ja  va  2  s.c o m
 * @throws org.apache.commons.codec.DecoderException A decoder exception is thrown if a Decoder encounters a failure condition during the decode process.
 */
@Override
public byte[] decode(byte[] source) throws DecoderException {
    if (source == null) {
        return null;
    }
    try {
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM_NAME);
        SecretKey secretKey = keyFactory.generateSecret(keySpec);
        Cipher cipher = Cipher.getInstance(CIPHER_NAME);
        cipher.init(Cipher.DECRYPT_MODE, secretKey, IvParameters);
        return cipher.doFinal(source);
    } catch (Exception e) {
        LOG.error(":" + key + ":" + source, e);
        throw new DecoderException(":" + key + ":" + source, e);
    }
}

From source file:bioLockJ.module.agent.MailAgent.java

private String decrypt(final String property) {
    String decryptedPassword = null;
    try {/*from   w w w.  ja va 2 s  .c o  m*/
        final SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
        final SecretKey key = keyFactory.generateSecret(new PBEKeySpec(PASSWORD));
        final Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");
        pbeCipher.init(Cipher.DECRYPT_MODE, key, new PBEParameterSpec(SALT, 20));
        decryptedPassword = new String(pbeCipher.doFinal(base64Decode(property)), "UTF-8");
    } catch (final Exception ex) {
        Log.out.error(ex.getMessage(), ex);
    }

    return decryptedPassword;

}

From source file:com.hernandez.rey.crypto.TripleDES.java

/**
 * Save the specified TripleDES SecretKey to the specified file
 * /*  w w  w  .  jav  a  2 s .co  m*/
 * @param key the key to write
 * @param keyFile
 * @throws IOException
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeySpecException
 */
public static void writeKey(final SecretKey key, final File keyFile)
        throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {
    // Convert the secret key to an array of bytes like this
    final SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("DESede");
    final DESedeKeySpec keyspec = (DESedeKeySpec) keyfactory.getKeySpec(key, DESedeKeySpec.class);
    final byte[] rawkey = keyspec.getKey();

    final byte[] encodedKey = Base64.encodeBase64(rawkey);

    // Write the raw key to the file
    FileOutputStream out = new FileOutputStream(keyFile);
    out.write(encodedKey);
    out.close();

    out = new FileOutputStream(new File(keyFile.toString().concat("-raw")));
    out.write(rawkey);
    out.close();
}

From source file:org.suren.autotest.web.framework.util.Encryptor.java

/** 
 * ?//  w w w.j a v a2  s . c o  m
 *  
 * @param desKey 
 * @param algorithm ??? {@link #DES}? {@link #DESEDE}?{@link #AES}?
 *            {@link #BLOWFISH}?{@link #RC2}? {@link #RC4}
 * @return 
 */
public static SecretKey getSecretKey(byte[] desKey, String algorithm) {
    if (ALG_DES.equalsIgnoreCase(algorithm)) {
        try {
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(algorithm);
            DESKeySpec dks = new DESKeySpec(desKey);
            return keyFactory.generateSecret(dks);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e.getCause());
        } catch (Exception e) {
            throw new IllegalArgumentException("?", e);
        }
    }

    return new SecretKeySpec(desKey, algorithm);
}

From source file:org.opendaylight.aaa.encrypt.AAAEncryptionServiceImpl.java

public AAAEncryptionServiceImpl(AaaEncryptServiceConfig encrySrvConfig, final DataBroker dataBroker) {
    SecretKey tempKey = null;/*  w  w  w.  j av a  2  s  .c  om*/
    IvParameterSpec tempIvSpec = null;
    if (encrySrvConfig.getEncryptSalt() == null) {
        throw new IllegalArgumentException(
                "null encryptSalt in AaaEncryptServiceConfig: " + encrySrvConfig.toString());
    }
    if (encrySrvConfig.getEncryptKey() != null && encrySrvConfig.getEncryptKey().isEmpty()) {
        LOG.debug("Set the Encryption service password and encrypt salt");
        String newPwd = RandomStringUtils.random(encrySrvConfig.getPasswordLength(), true, true);
        final Random random = new SecureRandom();
        byte[] salt = new byte[16];
        random.nextBytes(salt);
        String encodedSalt = Base64.getEncoder().encodeToString(salt);
        encrySrvConfig = new AaaEncryptServiceConfigBuilder(encrySrvConfig).setEncryptKey(newPwd)
                .setEncryptSalt(encodedSalt).build();
        updateEncrySrvConfig(newPwd, encodedSalt);
        initializeConfigDataTree(encrySrvConfig, dataBroker);
    }
    final byte[] enryptionKeySalt = Base64.getDecoder().decode(encrySrvConfig.getEncryptSalt());
    try {
        final SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(encrySrvConfig.getEncryptMethod());
        final KeySpec spec = new PBEKeySpec(encrySrvConfig.getEncryptKey().toCharArray(), enryptionKeySalt,
                encrySrvConfig.getEncryptIterationCount(), encrySrvConfig.getEncryptKeyLength());
        tempKey = keyFactory.generateSecret(spec);
        tempKey = new SecretKeySpec(tempKey.getEncoded(), encrySrvConfig.getEncryptType());
        tempIvSpec = new IvParameterSpec(enryptionKeySalt);
    } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
        LOG.error("Failed to initialize secret key", e);
    }
    key = tempKey;
    ivspec = tempIvSpec;
    Cipher cipher = null;
    try {
        cipher = Cipher.getInstance(encrySrvConfig.getCipherTransforms());
        cipher.init(Cipher.ENCRYPT_MODE, key, ivspec);
    } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidAlgorithmParameterException
            | InvalidKeyException e) {
        LOG.error("Failed to create encrypt cipher.", e);
    }
    this.encryptCipher = cipher;
    cipher = null;
    try {
        cipher = Cipher.getInstance(encrySrvConfig.getCipherTransforms());
        cipher.init(Cipher.DECRYPT_MODE, key, ivspec);
    } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidAlgorithmParameterException
            | InvalidKeyException e) {
        LOG.error("Failed to create decrypt cipher.", e);
    }
    this.decryptCipher = cipher;
}

From source file:edu.ku.brc.helpers.Encryption.java

/**
 * Encrypts the string from its array of bytes
 * @param input the actual string (in bytes) that is to be encrypted
 * @param password a password, which is really any string, but must be the same string that was used to decrypt it.
 * @return a byte array of the encrypted chars
 * @throws Exception in case something goes wrong
 *///from www .j  a v  a  2  s.  c  o  m
public static byte[] encrypt(byte[] input, char[] password) throws Exception {
    /*
     * Get ourselves a random number generator, needed in a number of places for encrypting.
     */
    SecureRandom sr = SecureRandom.getInstance("SHA1PRNG"); //$NON-NLS-1$

    /*
     * A "salt" is considered an essential part of password-based encryption. The salt is
     * selected at random for each encryption. It is not considered "sensitive", so it is tacked
     * onto the generated ciphertext without any special processing. It doesn't matter if an
     * attacker actually gets the salt. The salt is used as part of the key, with the very
     * useful result that if you Encryption the same plaintext with the same password twice, you
     * get *different* ciphertexts. There are lots of pages on the 'net with information about
     * salts and password-based encryption, so read them if you want more details. Suffice to
     * say salt=good, no salt=bad.
     */
    byte[] salt = new byte[SALT_LENGTH];
    sr.nextBytes(salt);

    /*
     * We've now got enough information to build the actual key. We do this by encapsulating the
     * variables in a PBEKeySpec and using a SecretKeyFactory to transform the spec into a key.
     */
    PBEKeySpec keyspec = new PBEKeySpec(password, salt, ITERATION_COUNT);
    SecretKeyFactory skf = SecretKeyFactory.getInstance(ALGORITHM);
    SecretKey key = skf.generateSecret(keyspec);

    /*
     * We'll use a ByteArrayOutputStream to conveniently gather up data as it's encrypted.
     */
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    /*
     * We've to a key, but to actually Encryption something, we need a "cipher". The cipher is
     * created, then initialized with the key, salt, and iteration count. We use a
     * PBEParameterSpec to hold the salt and iteration count needed by the Cipher object.
     */
    PBEParameterSpec paramspec = new PBEParameterSpec(salt, ITERATION_COUNT);
    Cipher cipher = Cipher.getInstance(ALGORITHM);
    cipher.init(Cipher.ENCRYPT_MODE, key, paramspec, sr);

    /*
     * First, in our output, we need to save the salt in plain unencrypted form.
     */
    baos.write(salt);

    /*
     * Next, Encryption our plaintext using the Cipher object, and write it into our output buffer.
     */
    baos.write(cipher.doFinal(input));

    /*
     * We're done. For security reasons, we probably want the PBEKeySpec object to clear its
     * internal copy of the password, so it can't be stolen later.
     */
    keyspec.clearPassword();
    return baos.toByteArray();
}

From source file:org.cryptonode.jncryptor.AES256v2Cryptor.java

@Override
public SecretKey keyForPassword(char[] password, byte[] salt) throws CryptorException {

    Validate.notNull(salt, "Salt value cannot be null.");
    Validate.isTrue(salt.length == SALT_LENGTH, "Salt value must be %d bytes.", SALT_LENGTH);

    try {//from   w  ww . j  a va 2s.c  om
        SecretKeyFactory factory = SecretKeyFactory.getInstance(KEY_DERIVATION_ALGORITHM);
        SecretKey tmp = factory
                .generateSecret(new PBEKeySpec(password, salt, PBKDF_ITERATIONS, AES_256_KEY_SIZE * 8));
        return new SecretKeySpec(tmp.getEncoded(), AES_NAME);
    } catch (GeneralSecurityException e) {
        throw new CryptorException(
                String.format("Failed to generate key from password using %s.", KEY_DERIVATION_ALGORITHM), e);
    }
}

From source file:org.tdmx.core.system.env.StringEncrypter.java

/**
 * Constructor used to create this object. Responsible for setting and initializing this object's encrypter and
 * decrypter Cipher instances given a Pass Phrase and algorithm.
 * //from   ww w . j  a  v  a 2  s. com
 * @param passPhrase
 *            Pass Phrase used to initialize both the encrypter and decrypter instances.
 */
public StringEncrypter(String passPhrase) {

    // 8-bytes Salt
    byte[] salt = { (byte) 0xA4, (byte) 0x9B, (byte) 0xC8, (byte) 0x72, (byte) 0x46, (byte) 0x45, (byte) 0xE3,
            (byte) 0x93 };

    // Iteration count
    int iterationCount = 1024;
    try {
        KeySpec keySpec = new PBEKeySpec(passPhrase.toCharArray(), salt, iterationCount);
        key = SecretKeyFactory.getInstance("PBEWithSHA1AndDESede").generateSecret(keySpec);

        ecipher = Cipher.getInstance(key.getAlgorithm());
        dcipher = Cipher.getInstance(key.getAlgorithm());

        // Prepare the parameters to the ciphers
        paramSpec = new PBEParameterSpec(salt, iterationCount);

        initCipher();
    } catch (InvalidKeySpecException e) {
        log.error("EXCEPTION: InvalidKeySpecException", e);
    } catch (NoSuchPaddingException e) {
        log.error("EXCEPTION: NoSuchPaddingException", e);
    } catch (NoSuchAlgorithmException e) {
        log.error("EXCEPTION: NoSuchAlgorithmException", e);
    }
}