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:com.cws.esolutions.security.utils.PasswordUtils.java

/**
 * Provides two-way (reversible) encryption of a provided string. Can be used where reversibility
 * is required but encryption (obfuscation, technically) is required.
 *
 * @param value - The plain text data to encrypt
 * @param salt - The salt value to utilize for the request
 * @param secretInstance - The cryptographic instance to use for the SecretKeyFactory
 * @param iterations - The number of times to loop through the keyspec
 * @param keyBits - The size of the key, in bits
 * @param algorithm - The algorithm to encrypt the data with
 * @param cipherInstance - The cipher instance to utilize
 * @param encoding - The text encoding//from w ww  .  j av  a 2s.  com
 * @return The encrypted string in a reversible format
 * @throws SecurityException {@link java.lang.SecurityException} if an exception occurs during processing
 */
public static final String decryptText(final String value, final String salt, final String secretInstance,
        final int iterations, final int keyBits, final String algorithm, final String cipherInstance,
        final String encoding) throws SecurityException {
    final String methodName = PasswordUtils.CNAME
            + "#encryptText(final String value, final String salt, final String secretInstance, final int iterations, final int keyBits, final String algorithm, final String cipherInstance, final String encoding) throws SecurityException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("Value: {}", secretInstance);
        DEBUGGER.debug("Value: {}", iterations);
        DEBUGGER.debug("Value: {}", keyBits);
        DEBUGGER.debug("Value: {}", algorithm);
        DEBUGGER.debug("Value: {}", cipherInstance);
        DEBUGGER.debug("Value: {}", encoding);
    }

    String decPass = null;

    try {
        String decoded = new String(Base64.getDecoder().decode(value));
        String iv = decoded.split(":")[0];
        String property = decoded.split(":")[1];

        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(secretInstance);
        PBEKeySpec keySpec = new PBEKeySpec(salt.toCharArray(), salt.getBytes(), iterations, keyBits);
        SecretKey keyTmp = keyFactory.generateSecret(keySpec);
        SecretKeySpec sks = new SecretKeySpec(keyTmp.getEncoded(), algorithm);

        Cipher pbeCipher = Cipher.getInstance(cipherInstance);
        pbeCipher.init(Cipher.DECRYPT_MODE, sks, new IvParameterSpec(Base64.getDecoder().decode(iv)));
        decPass = new String(pbeCipher.doFinal(Base64.getDecoder().decode(property)), encoding);
    } catch (InvalidKeyException ikx) {
        throw new SecurityException(ikx.getMessage(), ikx);
    } catch (NoSuchAlgorithmException nsx) {
        throw new SecurityException(nsx.getMessage(), nsx);
    } catch (NoSuchPaddingException npx) {
        throw new SecurityException(npx.getMessage(), npx);
    } catch (IllegalBlockSizeException ibx) {
        throw new SecurityException(ibx.getMessage(), ibx);
    } catch (BadPaddingException bpx) {
        throw new SecurityException(bpx.getMessage(), bpx);
    } catch (UnsupportedEncodingException uex) {
        throw new SecurityException(uex.getMessage(), uex);
    } catch (InvalidAlgorithmParameterException iapx) {
        throw new SecurityException(iapx.getMessage(), iapx);
    } catch (InvalidKeySpecException iksx) {
        throw new SecurityException(iksx.getMessage(), iksx);
    }

    return decPass;
}

From source file:com.meltmedia.jackson.crypto.EncryptionService.java

/**
 * Performs PBKDF2WithHmacSHA1 key stretching on password and returns a key of the specified length.
 * //from   w  ww. j a  v a  2s  . co  m
 * @param password the clear text password to base the key on.
 * @param salt the salt to add to the password
 * @param iterationCount the number of iterations used when stretching
 * @param keyLength the length of the resulting key in bits
 * @return the stretched key
 * @throws NoSuchAlgorithmException if PBKDF2WithHmacSHA1 is not available
 * @throws InvalidKeySpecException if the specification of the key is invalid.
 */
static SecretKey stretchKey(char[] password, byte[] salt, int iterationCount, int keyLength)
        throws NoSuchAlgorithmException, InvalidKeySpecException {
    SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
    KeySpec spec = new PBEKeySpec(password, salt, iterationCount, keyLength);
    return factory.generateSecret(spec);
}

From source file:com.cws.esolutions.security.utils.PasswordUtils.java

/**
 * Provides two-way (reversible) encryption of a provided string. Can be used where reversibility
 * is required but encryption (obfuscation, technically) is required.
 *
 * @param value - The plain text data to encrypt
 * @param salt - The salt value to utilize for the request
 * @param secretInstance - The cryptographic instance to use for the SecretKeyFactory
 * @param iterations - The number of times to loop through the keyspec
 * @param keyBits - The size of the key, in bits
 * @param algorithm - The algorithm to encrypt the data with
 * @param cipherInstance - The cipher instance to utilize
 * @param encoding - The text encoding/*from   w  w w  .j  av a2  s. c  o  m*/
 * @return The encrypted string in a reversible format
 * @throws SecurityException {@link java.lang.SecurityException} if an exception occurs during processing
 */
public static final String encryptText(final String value, final String salt, final String secretInstance,
        final int iterations, final int keyBits, final String algorithm, final String cipherInstance,
        final String encoding) throws SecurityException {
    final String methodName = PasswordUtils.CNAME
            + "#encryptText(final String value, final String salt, final String secretInstance, final int iterations, final int keyBits, final String algorithm, final String cipherInstance, final String encoding) throws SecurityException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("Value: {}", secretInstance);
        DEBUGGER.debug("Value: {}", iterations);
        DEBUGGER.debug("Value: {}", keyBits);
        DEBUGGER.debug("Value: {}", algorithm);
        DEBUGGER.debug("Value: {}", cipherInstance);
        DEBUGGER.debug("Value: {}", encoding);
    }

    String encPass = null;

    try {
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(secretInstance);
        PBEKeySpec keySpec = new PBEKeySpec(salt.toCharArray(), salt.getBytes(), iterations, keyBits);
        SecretKey keyTmp = keyFactory.generateSecret(keySpec);
        SecretKeySpec sks = new SecretKeySpec(keyTmp.getEncoded(), algorithm);

        Cipher pbeCipher = Cipher.getInstance(cipherInstance);
        pbeCipher.init(Cipher.ENCRYPT_MODE, sks);

        AlgorithmParameters parameters = pbeCipher.getParameters();
        IvParameterSpec ivParameterSpec = parameters.getParameterSpec(IvParameterSpec.class);

        byte[] cryptoText = pbeCipher.doFinal(value.getBytes(encoding));
        byte[] iv = ivParameterSpec.getIV();

        String combined = Base64.getEncoder().encodeToString(iv) + ":"
                + Base64.getEncoder().encodeToString(cryptoText);

        encPass = Base64.getEncoder().encodeToString(combined.getBytes());
    } catch (InvalidKeyException ikx) {
        throw new SecurityException(ikx.getMessage(), ikx);
    } catch (NoSuchAlgorithmException nsx) {
        throw new SecurityException(nsx.getMessage(), nsx);
    } catch (NoSuchPaddingException npx) {
        throw new SecurityException(npx.getMessage(), npx);
    } catch (IllegalBlockSizeException ibx) {
        throw new SecurityException(ibx.getMessage(), ibx);
    } catch (BadPaddingException bpx) {
        throw new SecurityException(bpx.getMessage(), bpx);
    } catch (UnsupportedEncodingException uex) {
        throw new SecurityException(uex.getMessage(), uex);
    } catch (InvalidKeySpecException iksx) {
        throw new SecurityException(iksx.getMessage(), iksx);
    } catch (InvalidParameterSpecException ipsx) {
        throw new SecurityException(ipsx.getMessage(), ipsx);
    }

    return encPass;
}

From source file:com.doplgangr.secrecy.filesystem.encryption.AES_Crypter.java

private static int generatePBKDF2IterationCount(String passphrase, byte[] salt) {
    int calculatedIterations = 0;
    try {// w  w w  .j  a va2 s.  com
        PBEKeySpec pbeKeySpec = new PBEKeySpec(passphrase.toCharArray(), salt,
                Config.PBKDF2_ITERATIONS_BENCHMARK, AES_KEY_SIZE_BIT);
        SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(SECRET_KEY_ALGORITHM);

        long startTime = System.currentTimeMillis();
        secretKeyFactory.generateSecret(pbeKeySpec);
        long finishTime = System.currentTimeMillis();

        calculatedIterations = (int) ((Config.PBKDF2_ITERATIONS_BENCHMARK / (double) (finishTime - startTime))
                * Config.PBKDF2_CREATION_TARGET_MS);
    } catch (Exception e) {
        Util.log("Cannot benchmark PBKDF2!");
    }

    if (calculatedIterations > Config.PBKDF2_ITERATIONS_MIN) {
        Util.log("Using " + calculatedIterations + " PBKDF2 iterations");
        return calculatedIterations;
    }
    Util.log("Using " + Config.PBKDF2_ITERATIONS_MIN + " PBKDF2 iterations");
    return Config.PBKDF2_ITERATIONS_MIN;
}

From source file:org.bremersee.common.security.crypto.password.PasswordEncoderImpl.java

/**
 * <p>/*from w  w  w.  jav  a  2 s .  c  o  m*/
 * Computes an odd DES key from 56 bits represented as a 7-bytes array.
 * </p>
 * <p>
 * Keeps elements from index {@code offset} to index
 * {@code offset + 7} of supplied array.
 * </p>
 *
 * @param keyData a byte array containing the 56 bits used to compute the DES
 *                key
 * @param offset  the offset of the first element of the 56-bits key data
 * @return the odd DES key generated
 * @throws InvalidKeyException      when key is invalid
 * @throws NoSuchAlgorithmException when algorithm is not available
 * @throws InvalidKeySpecException  when key spec is invalid
 */
private static Key computeDESKey(final byte[] keyData, final int offset)
        throws InvalidKeyException, NoSuchAlgorithmException, InvalidKeySpecException {

    byte[] desKeyData = new byte[8];
    int[] k = new int[7];

    for (int i = 0; i < 7; i++)
        k[i] = unsignedByteToInt(keyData[offset + i]);

    desKeyData[0] = (byte) (k[0] >>> 1);
    desKeyData[1] = (byte) (((k[0] & 0x01) << 6) | (k[1] >>> 2));
    desKeyData[2] = (byte) (((k[1] & 0x03) << 5) | (k[2] >>> 3));
    desKeyData[3] = (byte) (((k[2] & 0x07) << 4) | (k[3] >>> 4));
    desKeyData[4] = (byte) (((k[3] & 0x0F) << 3) | (k[4] >>> 5));
    desKeyData[5] = (byte) (((k[4] & 0x1F) << 2) | (k[5] >>> 6));
    desKeyData[6] = (byte) (((k[5] & 0x3F) << 1) | (k[6] >>> 7));
    desKeyData[7] = (byte) (k[6] & 0x7F);

    for (int i = 0; i < 8; i++)
        desKeyData[i] = (byte) (unsignedByteToInt(desKeyData[i]) << 1);

    KeySpec desKeySpec = new DESKeySpec(desKeyData);
    SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
    return keyFactory.generateSecret(desKeySpec);
}

From source file:energy.usef.environment.tool.security.VaultService.java

private static String computeMaskedPassword(String keystorePassword) throws Exception {
    // Create the PBE secret key
    SecretKeyFactory factory = SecretKeyFactory.getInstance(ToolConfig.VAULT_ENC_ALGORITHM);

    char[] password = "somearbitrarycrazystringthatdoesnotmatter".toCharArray();
    PBEParameterSpec cipherSpec = new PBEParameterSpec(ToolConfig.VAULT_SALT.getBytes(),
            ToolConfig.VAULT_ITERATION);
    PBEKeySpec keySpec = new PBEKeySpec(password);
    SecretKey cipherKey = factory.generateSecret(keySpec);

    String maskedPass = PBEUtils.encode64(keystorePassword.getBytes(), ToolConfig.VAULT_ENC_ALGORITHM,
            cipherKey, cipherSpec);//from w w w.ja  va  2s.c o  m

    return PicketBoxSecurityVault.PASS_MASK_PREFIX + maskedPass;
}

From source file:eap.util.EDcodeUtil.java

private static byte[] des(byte[] data, byte[] key, int opMode) {
    try {// www.ja  va  2s . c  o  m
        DESKeySpec desKey = new DESKeySpec(key);
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES", provider);
        SecretKey secureKey = keyFactory.generateSecret(desKey);

        Cipher cipher = Cipher.getInstance("DES", provider);
        //         SecureRandom secureRandom = new SecureRandom();
        SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG"); // provider
        cipher.init(opMode, secureKey, secureRandom);

        return cipher.doFinal(data);
    } catch (Exception e) {
        throw new IllegalArgumentException(e.getMessage(), e);
    }
}

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

/**
 * <p>/*from   w  w w. ja  v a2 s  .  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:org.chililog.server.common.CryptoUtils.java

/**
 * <p>//  w w  w  . j  ava2s.c  o  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.ox.webauth.crypto.Des3CbcSha1Kd.java

/**
 * From RFC 3961:/*from   w w  w  .ja va2  s . c  om*/
 * DR(Key, Constant) = k-truncate(E(Key, Constant, initial-cipher-state))
 *
 * Here DR is the random-octet generation function described below, and
 * DK is the key-derivation function produced from it.  In this
 * construction, E(Key, Plaintext, CipherState) is a cipher, Constant is
 * a well-known constant determined by the specific usage of this
 * function, and k-truncate truncates its argument by taking the first k
 * bits.  Here, k is the key generation seed length needed for the
 * encryption system.
 *
 * The output of the DR function is a string of bits; the actual key is
 * produced by applying the cryptosystem's random-to-key operation on
 * this bitstring.
 *
 * If the Constant is smaller than the cipher block size of E, then it
 * must be expanded with n-fold() so it can be encrypted.  If the output
 * of E is shorter than k bits, it is fed back into the encryption as
 * many times as necessary.  The construct is as follows (where |
 * indicates concatentation):
 *
 *    K1 = E(Key, n-fold(Constant), initial-cipher-state)
 *    K2 = E(Key, K1, initial-cipher-state)
 *    K3 = E(Key, K2, initial-cipher-state)
 *    K4 = ...
 *
 *    DR(Key, Constant) = k-truncate(K1 | K2 | K3 | K4 ...)
 */
private static byte[] dr(byte[] key, byte[] constant) throws GeneralSecurityException {
    // first make a DES3 key
    SecretKeyFactory factory = SecretKeyFactory.getInstance("DESede");
    KeySpec spec = new DESedeKeySpec(key);
    SecretKey secretKey = factory.generateSecret(spec);

    // initialise the cipher to use
    Cipher cipher = Cipher.getInstance("DESede/CBC/NoPadding");
    cipher.init(ENCRYPT_MODE, secretKey, IV);

    // ensure the constant is not smaller than the blocksize
    if (constant.length < cipher.getBlockSize()) {
        constant = nFold(constant, cipher.getBlockSize() * 8);
    }

    // now encrypt until we have at least 21 bytes, the length of a DES3 key
    byte[] input = constant;
    byte[] kn = new byte[0];
    do {
        byte[] newKn = cipher.doFinal(input);
        byte[] oldKn = kn;
        kn = new byte[oldKn.length + newKn.length];
        System.arraycopy(oldKn, 0, kn, 0, oldKn.length);
        System.arraycopy(newKn, 0, kn, oldKn.length, newKn.length);
        input = newKn;
    } while (kn.length < 21);

    // make sure we are returning exactly 21 bytes
    if (kn.length != 21) {
        byte[] newKn = new byte[21];
        System.arraycopy(kn, 0, newKn, 0, 21);
        kn = newKn;
    }

    return kn;
}