Example usage for javax.crypto SecretKeyFactory generateSecret

List of usage examples for javax.crypto SecretKeyFactory generateSecret

Introduction

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

Prototype

public final SecretKey generateSecret(KeySpec keySpec) throws InvalidKeySpecException 

Source Link

Document

Generates a SecretKey object from the provided key specification (key material).

Usage

From source file:eu.uqasar.service.AuthenticationService.java

/**
 *
 * @param password/* ww w. java2s . co  m*/
 * @param salt
 * @return
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeySpecException
 */
public static byte[] getEncryptedPassword(String password, byte[] salt)
        throws NoSuchAlgorithmException, InvalidKeySpecException {
    // PBKDF2 with SHA-1 as the hashing algorithm. Note that the NIST
    // specifically names SHA-1 as an acceptable hashing algorithm for
    // PBKDF2
    String algorithm = "PBKDF2WithHmacSHA1";
    // SHA-1 generates 160 bit hashes, so that's what makes sense here
    int derivedKeyLength = 160;
    // Pick an iteration count that works for you. The NIST recommends at
    // least 1,000 iterations:
    // http://csrc.nist.gov/publications/nistpubs/800-132/nist-sp800-132.pdf
    // iOS 4.x reportedly uses 10,000:
    // http://blog.crackpassword.com/2010/09/smartphone-forensics-cracking-blackberry-backup-passwords/
    int iterations = 20000;
    KeySpec spec = new PBEKeySpec(password.toCharArray(), salt, iterations, derivedKeyLength);
    SecretKeyFactory f = SecretKeyFactory.getInstance(algorithm);
    return f.generateSecret(spec).getEncoded();
}

From source file:com.aurel.track.report.query.ReportQueryBL.java

private static String dcl(String encryptedText, char[] password) {
    byte[] clearText = { ' ' };
    int count = 20;
    PBEKeySpec pbeKeySpec;//from  w w  w.  j av a  2s .  c  om
    PBEParameterSpec pbeParamSpec;
    SecretKeyFactory keyFac;
    // Create PBE parameter set
    pbeParamSpec = new PBEParameterSpec(salt, count);
    pbeKeySpec = new PBEKeySpec(password);
    try {
        keyFac = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
        SecretKey pbeKey = keyFac.generateSecret(pbeKeySpec);

        // Create PBE Cipher
        Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");

        // Initialize PBE Cipher with key and parameters
        pbeCipher.init(Cipher.DECRYPT_MODE, pbeKey, pbeParamSpec);

        byte[] ciphertext = Base64.decodeBase64(encryptedText);

        // Decrypt the cleartext
        clearText = pbeCipher.doFinal(ciphertext);
    } catch (Exception e) {
    }
    return new String(clearText);
}

From source file:com.aurel.track.admin.customize.category.filter.execute.ReportQueryBL.java

private static String dcl(String encryptedText, char[] password) {
    byte[] clearText = { ' ' };
    int count = 20;
    PBEKeySpec pbeKeySpec;/*from w  ww  . j a  v a 2  s. c o  m*/
    PBEParameterSpec pbeParamSpec;
    SecretKeyFactory keyFac;
    // Create PBE parameter set
    pbeParamSpec = new PBEParameterSpec(salt, count);
    pbeKeySpec = new PBEKeySpec(password);
    try {
        keyFac = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
        SecretKey pbeKey = keyFac.generateSecret(pbeKeySpec);

        // Create PBE Cipher
        Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");

        // Initialize PBE Cipher with key and parameters
        pbeCipher.init(Cipher.DECRYPT_MODE, pbeKey, pbeParamSpec);

        byte[] ciphertext = Base64.decodeBase64(encryptedText);

        //Decrypt the cleartext
        clearText = pbeCipher.doFinal(ciphertext);
    } catch (Exception e) {
        LOGGER.debug(ExceptionUtils.getStackTrace(e), e);
    }
    return new String(clearText);
}

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

/**
 * ???/*from   ww w  .j  a v  a  2s  . c  om*/
 * <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);
    }
}

From source file:org.nuclos.client.LocalUserCaches.java

private static Cipher createCipher(int mode, String password) throws GeneralSecurityException {
    String alg = "PBEWithSHA1AndDESede"; //BouncyCastle has better algorithms
    PBEKeySpec keySpec = new PBEKeySpec(password.toCharArray());
    SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(alg);
    SecretKey secretKey = keyFactory.generateSecret(keySpec);

    Cipher cipher = Cipher.getInstance("PBEWithSHA1AndDESede");
    // TODO: A fixed salt doesn't help anything.
    cipher.init(mode, secretKey, new PBEParameterSpec("saltsalt".getBytes(), 2000));

    return 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   w ww .j a v a 2s  .  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:Main.java

public static String enCrypto(String txt, String key) {

    if (txt != null && !"".equals(txt) && !"null".equals(txt)) {

        try {//  w  ww .  ja va  2s.c  o  m

            StringBuffer sb = new StringBuffer();
            DESKeySpec desKeySpec = new DESKeySpec(key.getBytes());
            SecretKeyFactory skeyFactory = null;
            Cipher cipher = null;
            try {
                skeyFactory = SecretKeyFactory.getInstance("DES");
                cipher = Cipher.getInstance("DES");
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            }
            SecretKey deskey = skeyFactory.generateSecret(desKeySpec);
            cipher.init(Cipher.ENCRYPT_MODE, deskey);
            byte[] cipherText = cipher.doFinal(txt.getBytes());
            for (int n = 0; n < cipherText.length; n++) {
                String stmp = (java.lang.Integer.toHexString(cipherText[n] & 0XFF));
                if (stmp.length() == 1) {
                    sb.append("0" + stmp);
                } else {
                    sb.append(stmp);
                }
            }
            return sb.toString().toUpperCase(Locale.US);

        } catch (Exception e) {

            e.printStackTrace();
        }
    }
    return null;
}

From source file:com.the_incognito.darry.incognitochatmessengertest.BouncyCastleImplementation.java

private static Key generateKeySpec(String key) throws NoSuchAlgorithmException, InvalidKeySpecException {
    SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256", new BouncyCastleProvider());
    char password[] = key.toCharArray();
    byte salt[] = "salt".getBytes();
    KeySpec spec = new PBEKeySpec(password, salt, 65536, 128);
    SecretKey tmp = factory.generateSecret(spec);
    SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES");
    return secret;
    //To change body of generated methods, choose Tools | Templates.
}

From source file:com.mb.framework.util.SecurityUtil.java

/**
 * /*from  www .ja v a 2 s .  c  o m*/
 * 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:org.artifactory.security.crypto.CryptoHelper.java

private static SecretKey generatePbeKey(String password) {
    try {/* ww w .j av  a 2  s. c  o m*/
        PBEKeySpec pbeKeySpec = new PBEKeySpec(password.toCharArray());
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(SYM_ALGORITHM);
        SecretKey secretKey = keyFactory.generateSecret(pbeKeySpec);
        return secretKey;
    } catch (NoSuchAlgorithmException e) {
        throw new IllegalArgumentException("No such algorithm: " + e.getMessage());
    } catch (InvalidKeySpecException e) {
        throw new RuntimeException("Unexpected exception: ", e);
    }
}