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:com.mb.framework.util.SecurityUtil.java

/**
 * //from   w  w w.ja v  a  2 s . c  om
 * This method is used for encrypt by using Algorithm - AES/CBC/PKCS5Padding
 * 
 * @param String
 * @return String
 * @throws Exception
 */
public static String encryptAESPBKDF2(String plainText) throws Exception {

    // get salt
    salt = generateSaltAESPBKDF2();
    byte[] saltBytes = salt.getBytes("UTF-8");

    // Derive the key
    SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
    PBEKeySpec spec = new PBEKeySpec(SECRET_KEY.toCharArray(), saltBytes, pswdIterations, keySize);

    SecretKey secretKey = factory.generateSecret(spec);
    SecretKeySpec secret = new SecretKeySpec(secretKey.getEncoded(), "AES");

    // encrypt the message
    Cipher cipher = Cipher.getInstance(AES_CBC_PKCS5PADDING_ALGO);
    cipher.init(Cipher.ENCRYPT_MODE, secret);
    AlgorithmParameters params = cipher.getParameters();
    ivBytes = params.getParameterSpec(IvParameterSpec.class).getIV();
    byte[] encryptedTextBytes = cipher.doFinal(plainText.getBytes("UTF-8"));
    return new Base64().encodeAsString(encryptedTextBytes);
}

From source file:de.phoenix.security.Encrypter.java

/**
 * Salt a given password with a random salt
 * /*from www . jav a 2s . com*/
 * @param password
 *            The password to salt
 * @param salt
 *            The random generated salt
 * @param iterations
 *            The number of iterations the password is salted by the
 *            algorithmn
 * @param bytes
 *            How many bytes the passwords contains
 * @return A salted password
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeySpecException
 */
private SaltedPassword saltPassword(char[] password, byte[] salt, int iterations, int bytes)
        throws NoSuchAlgorithmException, InvalidKeySpecException {
    PBEKeySpec spec = new PBEKeySpec(password, salt, iterations, bytes * 8);
    SecretKeyFactory skf = SecretKeyFactory.getInstance(KEY_ALGORITHM);
    String saltString = Hex.encodeHexString(salt);
    String saltedHash = Hex.encodeHexString(skf.generateSecret(spec).getEncoded());
    return new SaltedPassword(saltedHash, saltString, iterations);
}

From source file:JavaTron.JTP.java

/**
 * Decrypts an encrypted string//w w w  .ja v  a2 s.co m
 * @param property
 * @return A plaintext string
 */
public static String decrypt(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.DECRYPT_MODE, key, new PBEParameterSpec(SALT, 20));
        p = new String(pbeCipher.doFinal(base64Decode(property)));
    } catch (Exception e) {
        e.printStackTrace();
    }
    return p;
}

From source file:org.apache.ranger.plugin.util.PasswordUtils.java

private String decrypt() throws IOException {
    String ret = null;//from  w  w  w  . ja va 2 s .  c  om
    try {
        byte[] decodedPassword = Base64.decode(password);
        Cipher engine = Cipher.getInstance(CRYPT_ALGO);
        PBEKeySpec keySpec = new PBEKeySpec(encryptKey);
        SecretKeyFactory skf = SecretKeyFactory.getInstance(CRYPT_ALGO);
        SecretKey key = skf.generateSecret(keySpec);
        engine.init(Cipher.DECRYPT_MODE, key, new PBEParameterSpec(salt, ITERATION_COUNT));
        String decrypted = new String(engine.doFinal(decodedPassword));
        int foundAt = decrypted.indexOf(LEN_SEPARATOR_STR);
        if (foundAt > -1) {
            if (decrypted.length() > foundAt) {
                ret = decrypted.substring(foundAt + 1);
            } else {
                ret = "";
            }
        } else {
            ret = null;
        }
    } catch (Throwable t) {
        LOG.error("Unable to decrypt password due to error", t);
        throw new IOException("Unable to decrypt password due to error", t);
    }
    return ret;
}

From source file:org.hawk.core.security.FileBasedCredentialsStore.java

private String encrypt(String property) throws GeneralSecurityException, UnsupportedEncodingException {

    SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
    SecretKey key = keyFactory.generateSecret(new PBEKeySpec(encryptionKey));
    Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");
    pbeCipher.init(Cipher.ENCRYPT_MODE, key, new PBEParameterSpec(salt, 20));
    return base64Encode(pbeCipher.doFinal(property.getBytes("UTF-8")));
}

From source file:com.filelocker.encryption.AES_Encryption.java

/**
 * this must be called after creating the initial Crypto object. It creates a salt of SALT_LEN bytes
 * and generates the salt bytes using secureRandom().  The encryption secret key is created
 * along with the initialization vectory. The member variable vEcipher is created to be used
 * by the class later on when either creating a CipherOutputStream, or encrypting a buffer
 * to be written to disk.//from   w  w  w  .  j  a va 2 s.  c  o  m
 *
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeySpecException
 * @throws NoSuchPaddingException
 * @throws InvalidParameterSpecException
 * @throws IllegalBlockSizeException
 * @throws BadPaddingException
 * @throws UnsupportedEncodingException
 * @throws InvalidKeyException
 */
public void setupEncrypt() throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException,
        InvalidParameterSpecException, IllegalBlockSizeException, BadPaddingException,
        UnsupportedEncodingException, InvalidKeyException {
    SecretKeyFactory factory = null;
    SecretKey tmp = null;

    // crate secureRandom salt and store  as member var for later use
    vSalt = new byte[SALT_LEN];
    SecureRandom rnd = new SecureRandom();
    rnd.nextBytes(vSalt);
    Db("generated salt :" + Hex.encodeHexString(vSalt));

    factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");

    /* Derive the key, given password and salt.
     *
     * in order to do 256 bit crypto, you have to muck with the files for Java's "unlimted security"
     * The end user must also install them (not compiled in) so beware.
     * see here:  http://www.javamex.com/tutorials/cryptography/unrestricted_policy_files.shtml
     */
    KeySpec spec = new PBEKeySpec(vPassword.toCharArray(), vSalt, ITERATIONS, KEYLEN_BITS);
    tmp = factory.generateSecret(spec);
    SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES");

    /* Create the Encryption cipher object and store as a member variable
     */
    vEcipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    vEcipher.init(Cipher.ENCRYPT_MODE, secret);
    AlgorithmParameters params = vEcipher.getParameters();

    // get the initialization vectory and store as member var
    vInitVec = params.getParameterSpec(IvParameterSpec.class).getIV();

    Db("vInitVec is :" + Hex.encodeHexString(vInitVec));
}

From source file:org.everit.password.encryptor.pbkdf2.PBKDF2PasswordEncryptorImpl.java

private String encryptSecure(final byte[] salt, final String plainPassword, final String algorithm)
        throws NoSuchAlgorithmException, InvalidKeySpecException {
    int deriverdKeyLenght = Algorithm.SUPPORTED_ALGORITHMS_AND_KEY_LENGTHS.get(algorithm);
    KeySpec spec = new PBEKeySpec(plainPassword.toCharArray(), salt, iterationCount, deriverdKeyLenght);
    SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(algorithm);
    byte[] passwordDigest = secretKeyFactory.generateSecret(spec).getEncoded();
    byte[] passwordDigestBase64 = Base64.encodeBase64(passwordDigest);
    String passwordDigestBase64StringUTF8 = StringUtils.newStringUtf8(passwordDigestBase64);
    byte[] saltBase64 = Base64.encodeBase64(salt);
    String saltBase64StringUTF8 = StringUtils.newStringUtf8(saltBase64);
    return SEPARATOR_START + algorithm + SEPARATOR_END + SEPARATOR_START + saltBase64StringUTF8 + SEPARATOR_END
            + passwordDigestBase64StringUTF8;
}

From source file:de.alpharogroup.crypto.simple.SimpleDecryptor.java

/**
 * Initializes the {@link SimpleDecryptor} object.
 *
 * @throws InvalidAlgorithmParameterException
 *             is thrown if initialization of the cypher object fails.
 * @throws NoSuchPaddingException/*w ww.ja v a 2 s  .  c om*/
 *             is thrown if instantiation of the cypher object fails.
 * @throws InvalidKeySpecException
 *             is thrown if generation of the SecretKey object fails.
 * @throws NoSuchAlgorithmException
 *             is thrown if instantiation of the SecretKeyFactory object fails.
 * @throws InvalidKeyException
 *             is thrown if initialization of the cypher object fails.
 */
private void initialize() throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException,
        InvalidKeyException, InvalidAlgorithmParameterException {
    if (!isInitialized()) {
        KeySpec keySpec = null;
        if (this.getPrivateKey() != null) {
            keySpec = new PBEKeySpec(this.getPrivateKey().toCharArray());
        }
        if (this.getPrivateKey() == null) {
            keySpec = new PBEKeySpec(CryptConst.PRIVATE_KEY.toCharArray());
        }
        final SecretKeyFactory factory = SecretKeyFactory.getInstance(CryptConst.PBEWITH_MD5AND_DES);
        final SecretKey key = factory.generateSecret(keySpec);
        this.cipher = Cipher.getInstance(key.getAlgorithm());
        final AlgorithmParameterSpec paramSpec = new PBEParameterSpec(CryptConst.SALT,
                CryptConst.ITERATIONCOUNT);
        this.cipher.init(Cipher.DECRYPT_MODE, key, paramSpec);
        initialized = true;
    }
}

From source file:io.stallion.utils.Encrypter.java

private static SecretKeySpec makeKeySpec(String password, String salt) {
    byte[] saltBytes = new byte[0];
    try {//from  w  w  w .  ja va  2s .  c  o  m
        saltBytes = Hex.decodeHex(salt.toCharArray());
    } catch (DecoderException e) {
        throw new RuntimeException(e);
    }
    PBEKeySpec keySpec = new PBEKeySpec(password.toCharArray(), saltBytes, ITERATIONS, KEY_LENGTH);
    SecretKey secretKey;
    try {
        SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
        secretKey = factory.generateSecret(keySpec);
    } catch (NoSuchAlgorithmException e) {
        throw new IllegalArgumentException("Not a valid encryption algorithm", e);
    } catch (InvalidKeySpecException e) {
        throw new IllegalArgumentException("Not a valid secret key", e);
    }
    SecretKeySpec skeySpec = new SecretKeySpec(secretKey.getEncoded(), "AES");
    return skeySpec;
}

From source file:com.github.aynu.mosir.core.standard.util.SecurityHelper.java

/**
 * ???//ww  w . j  a  v  a2 s. c  o m
 * <dl>
 * <dt>?
 * <dd>PBKDF2WithHmacSHA1?????????65536?128??????
 * </dl>
 * @param password 
 * @param salt 
 * @return ?
 */
public static SecretKey createSecretKey(final char[] password, final byte[] salt) {
    try {
        final SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
        final KeySpec spec = new PBEKeySpec(password, salt, 65536, 128);
        return factory.generateSecret(spec);
    } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
        throw new StandardRuntimeException(e);
    }
}