Example usage for javax.crypto.spec PBEKeySpec PBEKeySpec

List of usage examples for javax.crypto.spec PBEKeySpec PBEKeySpec

Introduction

In this page you can find the example usage for javax.crypto.spec PBEKeySpec PBEKeySpec.

Prototype

public PBEKeySpec(char[] password, byte[] salt, int iterationCount, int keyLength) 

Source Link

Document

Constructor that takes a password, salt, iteration count, and to-be-derived key length for generating PBEKey of variable-key-size PBE ciphers.

Usage

From source file:ai.serotonin.backup.Base.java

SecretKey createSecretKey(final byte[] salt) throws Exception {
    final String password = getArchivePassword();
    final SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
    final KeySpec spec = new PBEKeySpec(password.toCharArray(), salt, 65536, 256);
    final SecretKey tmp = factory.generateSecret(spec);
    final SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES");
    return secret;
}

From source file:cz.muni.fi.airportservicelayer.services.StewardServiceImpl.java

private static byte[] pbkdf2(char[] password, byte[] salt, int iterations, int bytes) {
    try {//from   w  w w.j a v a 2 s  .com
        PBEKeySpec spec = new PBEKeySpec(password, salt, iterations, bytes * 8);
        return SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256").generateSecret(spec).getEncoded();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:org.chililog.server.common.CryptoUtils.java

/**
 * <p>/*from   w w w .j av a 2s.co m*/
 * Encrypt a plain text string using AES. The output is an encrypted plain text string. See
 * http://stackoverflow.com/questions/992019/java-256bit-aes-encryption/992413#992413
 * </p>
 * <p>
 * The algorithm used is <code>base64(aes(plainText))</code>
 * </p>
 * 
 * 
 * @param plainText
 *            text to encrypt
 * @param password
 *            password to use for encryption
 * @return encrypted text
 * @throws ChiliLogException
 */
public static String encryptAES(String plainText, String password) throws ChiliLogException {
    try {
        SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
        KeySpec spec = new PBEKeySpec(password.toCharArray(), AES_ENCRYPTION_STRING_SALT, 1024, 128);
        SecretKey tmp = factory.generateSecret(spec);
        SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES");

        byte[] plainTextBytes = plainText.getBytes("UTF-8");

        AlgorithmParameterSpec paramSpec = new IvParameterSpec(AES_ENCRYPTION_INTIALIZATION_VECTOR);
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, secret, paramSpec);
        byte[] cipherText = cipher.doFinal(plainTextBytes);

        // Convert hash to string
        Base64 encoder = new Base64(1000, new byte[] {}, false);
        return encoder.encodeToString(cipherText);
    } catch (Exception ex) {
        throw new ChiliLogException(ex, "Error attempting to encrypt. " + ex.getMessage());
    }
}

From source file:uk.ac.cam.cl.dtg.segue.auth.SegueLocalAuthenticator.java

/**
 * Compute the hash of a string using the preconfigured hashing function.
 *
 * @param str//  w w  w. ja  v a2  s .c om
 *            - string to hash
 * @param salt
 *            - random string to use as a salt.
 * @param keyLength
 *            - the key length
 * @return a byte array of the hash
 * @throws NoSuchAlgorithmException
 *             - if the configured algorithm is not valid.
 * @throws InvalidKeySpecException
 *             - if the preconfigured key spec is invalid.
 */
private byte[] computeHash(final String str, final String salt, final int keyLength)
        throws NoSuchAlgorithmException, InvalidKeySpecException {
    char[] strChars = str.toCharArray();
    byte[] saltBytes = salt.getBytes();

    PBEKeySpec spec = new PBEKeySpec(strChars, saltBytes, ITERATIONS, keyLength);

    SecretKeyFactory key = SecretKeyFactory.getInstance(CRYPTO_ALOGRITHM);
    return key.generateSecret(spec).getEncoded();
}

From source file:org.nuxeo.ecm.core.blob.binary.AESBinaryManager.java

/**
 * Generates an AES key from the password using PBKDF2.
 *
 * @param salt the salt/*ww w  .j  av a 2s .co m*/
 */
protected Key generateSecretKey(byte[] salt) throws GeneralSecurityException {
    char[] password = getPassword();
    SecretKeyFactory factory = SecretKeyFactory.getInstance(PBKDF2_WITH_HMAC_SHA1);
    PBEKeySpec spec = new PBEKeySpec(password, salt, PBKDF2_ITERATIONS, PBKDF2_KEY_LENGTH);
    clearPassword(password);
    Key derived = factory.generateSecret(spec);
    spec.clearPassword();
    return new SecretKeySpec(derived.getEncoded(), AES);
}

From source file:com.microsoft.aad.adal.example.userappwithbroker.MainActivity.java

/**
 * To call broker, you have to ensure the following:
 * 1) You have to call {@link AuthenticationSettings#INSTANCE#setUseBroker(boolean)}
 *    and the supplied value has to be true
 * 2) You have to have to correct set of permissions.
 *    If target API version is lower than 23:
 *    i) You have to have GET_ACCOUNTS, USE_CREDENTIAL, MANAGE_ACCOUNTS declared
 *       in manifest.//from   w  ww.j  a  va2 s  .c o m
 *    If target API version is 23:
 *    i)  USE_CREDENTIAL and MANAGE_ACCOUNTS is already deprecated.
 *    ii) GET_ACCOUNTS permission is now at protection level "dangerous" calling app
 *        is responsible for requesting it.
 * 3) If you're talking to the broker app without PRT support, you have to have an
 *    WPJ account existed in broker(enroll with intune, or register with Azure
 *    Authentication app).
 * 4) The two broker apps(Company Portal or Azure Authenticator) cannot go through
 *    broker auth.
 */
private void setUpADALForCallingBroker() {
    // Set the calling app will talk to broker
    // Note: Starting from version 1.1.14, calling app has to explicitly call
    // AuthenticationSettings.Instance.setUserBroker(true) to call broker.
    // AuthenticationSettings.Instance.setSkipBroker(boolean) is already deprecated.
    AuthenticationSettings.INSTANCE.setUseBroker(true);

    // Provide secret key for token encryption.
    try {
        // For API version lower than 18, you have to provide the secret key. The secret key
        // needs to be 256 bits. You can use the following way to generate the secret key. And
        // use AuthenticationSettings.Instance.setSecretKey(secretKeyBytes) to supply us the key.
        // For API version 18 and above, we use android keystore to generate keypair, and persist
        // the keypair in AndroidKeyStore. Current investigation shows 1)Keystore may be locked with
        // a lock screen, if calling app has a lot of background activity, keystore cannot be
        // accessed when locked, we'll be unable to decrypt the cache items 2) AndroidKeystore could
        // be reset when gesture to unlock the device is changed.
        // We do recommend the calling app the supply us the key with the above two limitations.
        if (AuthenticationSettings.INSTANCE.getSecretKeyData() == null) {
            // use same key for tests
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithSHA256And256BitAES-CBC-BC");
            SecretKey tempkey = keyFactory.generateSecret(
                    new PBEKeySpec("test".toCharArray(), "abcdedfdfd".getBytes("UTF-8"), 100, 256));
            SecretKey secretKey = new SecretKeySpec(tempkey.getEncoded(), "AES");
            AuthenticationSettings.INSTANCE.setSecretKey(secretKey.getEncoded());
        }
    } catch (NoSuchAlgorithmException | InvalidKeySpecException | UnsupportedEncodingException ex) {
        showMessage("Fail to generate secret key:" + ex.getMessage());
    }

    ApplicationInfo appInfo = getApplicationContext().getApplicationInfo();
    Log.v(TAG, "App info:" + appInfo.uid + " package:" + appInfo.packageName);

    // If you're directly talking to ADFS server, you should set validateAuthority=false.
    SampleTelemetry telemetryDispatcher = new SampleTelemetry();
    Telemetry.getInstance().registerDispatcher(telemetryDispatcher, true);
}

From source file:org.chililog.server.common.CryptoUtils.java

/**
 * <p>//from   ww  w. j  ava 2s .  c o  m
 * Decrypt an encrypted text string using AES. The output is the plain text string.
 * </p>
 * 
 * @param encryptedText
 *            encrypted text returned by <code>encrypt</code>
 * @param password
 *            password used at the time of encryption
 * @return decrypted plain text string
 * @throws ChiliLogException
 */
public static String decryptAES(String encryptedText, String password) throws ChiliLogException {
    try {
        SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
        KeySpec spec = new PBEKeySpec(password.toCharArray(), AES_ENCRYPTION_STRING_SALT, 1024, 128);
        SecretKey tmp = factory.generateSecret(spec);
        SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES");

        Base64 decoder = new Base64(1000, new byte[] {}, false);
        byte[] encryptedTextBytes = decoder.decode(encryptedText);

        AlgorithmParameterSpec paramSpec = new IvParameterSpec(AES_ENCRYPTION_INTIALIZATION_VECTOR);
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, secret, paramSpec);
        byte[] plainTextBytes = cipher.doFinal(encryptedTextBytes);

        return new String(plainTextBytes, "UTF-8");
    } catch (Exception ex) {
        throw new ChiliLogException(ex, "Error attempting to decrpt. " + ex.getMessage());
    }
}

From source file:com.diona.fileReader.CipherUtil.java

/**
 * Generates the secret key to be used for encryption. The secret key is retrieved from the shared preferences if
 * previously calculated.//from  www.  j  av a2 s . c  o  m
 * 
 * @return A new secret key if not previously calculated.
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeySpecException
 * @throws UnsupportedEncodingException
 */
private SecretKeySpec getSecretKey(final Context context)
        throws NoSuchAlgorithmException, InvalidKeySpecException, UnsupportedEncodingException {
    // final SocialWorkerSharedPreferences sharedPreferences = SocialWorkerSharedPreferences.getInstance();
    // if (sharedPreferences.getSecretKey() == null) {
    final byte[] salt = generateRandomKeyBytes(SALT_LENGTH);
    final SecretKeyFactory factory = SecretKeyFactory.getInstance(SECRET_KEY_ALGORITHM);
    final PBEKeySpec spec = new PBEKeySpec(SECRET_KEY_PASSPHRASE.toCharArray(), salt, KEY_ITERATIONS, KEY_SIZE);
    final SecretKey secretKey = factory.generateSecret(spec);
    final SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getEncoded(), ENCRYPTION_ALGORITHM);

    // Set the value of the secret key in private shared preferences
    //sharedPreferences.setSecretKey(secretKeySpec);
    return secretKeySpec;
    /*} else {
      return sharedPreferences.getSecretKey();
    }*/
}

From source file:alfio.manager.CheckInManager.java

private static Pair<Cipher, SecretKeySpec> getCypher(String key) {
    try {/*from   w ww .j a  v  a 2  s  .c om*/
        SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
        int iterations = 1000;
        int keyLength = 256;
        PBEKeySpec spec = new PBEKeySpec(key.toCharArray(), key.getBytes(StandardCharsets.UTF_8), iterations,
                keyLength);
        SecretKey secretKey = factory.generateSecret(spec);
        SecretKeySpec secret = new SecretKeySpec(secretKey.getEncoded(), "AES");
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        return Pair.of(cipher, secret);
    } catch (GeneralSecurityException e) {
        throw new IllegalStateException(e);
    }
}

From source file:org.jasig.cas.extension.clearpass.EncryptedMapDecorator.java

private static Key getSecretKey(final String secretKeyAlgorithm, final String secretKey, final String salt)
        throws Exception {

    SecretKeyFactory factory = SecretKeyFactory.getInstance(SECRET_KEY_FACTORY_ALGORITHM);
    KeySpec spec = new PBEKeySpec(secretKey.toCharArray(), char2byte(salt), 65536, 128);
    SecretKey tmp = factory.generateSecret(spec);
    SecretKey secret = new SecretKeySpec(tmp.getEncoded(), secretKeyAlgorithm);

    return secret;
}