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.mastercard.mcbp.utils.crypto.CryptoServiceImpl.java

/**
 * {@inheritDoc}/*from  w w w  .j av a 2 s  .c  o  m*/
 */
@Override
public final byte[] desCbc(byte[] data, byte[] bKey, Mode mode) throws McbpCryptoException {
    try {
        SecretKey key = SecretKeyFactory.getInstance("DES").generateSecret(new DESKeySpec(bKey));
        final Cipher cipher = Cipher.getInstance("DES/CBC/noPadding");

        final IvParameterSpec ips = new IvParameterSpec(new byte[8]);
        if (mode == Mode.ENCRYPT) {
            cipher.init(Cipher.ENCRYPT_MODE, key, ips);
        } else {
            cipher.init(Cipher.DECRYPT_MODE, key, ips);
        }
        return cipher.doFinal(data);
    } catch (InvalidKeySpecException | NoSuchAlgorithmException | InvalidKeyException
            | IllegalBlockSizeException | BadPaddingException | InvalidAlgorithmParameterException
            | NoSuchPaddingException e) {
        throw new McbpCryptoException(e.toString());
    }
}

From source file:com.orig.gls.security.Encode.java

public Encode(String keyString, String ivString) {
    try {//  w  w  w .j  av a2 s  .  co  m
        final MessageDigest md = MessageDigest.getInstance("md5");
        final byte[] digestOfPassword = md.digest(Base64.decodeBase64(keyString.getBytes("utf-8")));
        final byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24);
        for (int j = 0, k = 16; j < 8;) {
            keyBytes[k++] = keyBytes[j++];
        }
        keySpec = new DESedeKeySpec(keyBytes);
        key = SecretKeyFactory.getInstance("DESede").generateSecret(keySpec);
        iv = new IvParameterSpec(ivString.getBytes());
    } catch (UnsupportedEncodingException asd) {
        System.out.println(asd.getMessage());
    } catch (InvalidKeyException asd) {
        System.out.println(asd.getMessage());
    } catch (NoSuchAlgorithmException asd) {
        System.out.println(asd.getMessage());
    } catch (InvalidKeySpecException asd) {
        System.out.println(asd.getMessage());
    }
}

From source file:com.ccstats.crypto.AESWorker.java

/**
 * Decrypting text that is encrypted by the advanced encryption standard.
 *
 * @param password The char array containing of the plaintext password
 * @param encryptedBlock The Encrypted text to be targeted and decrypted.
 *
 * @return The decrypted byte array of the encrypted text.
 *///from  w  w  w  .j  a v a 2s  .  c  om
public byte[] decrypt(char[] password, char[] encryptedBlock)
        throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeySpecException, InvalidKeyException,
        BadPaddingException, IllegalBlockSizeException, InvalidAlgorithmParameterException, DecoderException {

    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    if (Cipher.getMaxAllowedKeyLength("AES") < this.keyLength) {
        this.keyLength = Cipher.getMaxAllowedKeyLength("AES");
        System.err.printf(
                "WARNING: YOUR MAXIMUM AES KEY LENGTH POLICY IS %d BITS. KEY LENGTH LIMITED TO %d BITS.\n",
                this.keyLength, this.keyLength);
    }

    // hash the password with the MD5 function and decode the encryptedBlock
    password = hash(new String(password).getBytes(StandardCharsets.UTF_8));
    byte[] decoded = Hex.decodeHex(encryptedBlock);

    // The decoded byte array has the IV, encryptedText, and salt bytes stored in that order.
    // The IV bytes are of length 16 and salt is of length 20.
    byte[] encryptedText = new byte[decoded.length - 36], ivBytes = new byte[16], salt = new byte[20];

    // The decoded bytes are ordered in the following form: ivBytes + encryptedText + saltBytes.
    // Extract the bytes into their corresponding array.
    System.arraycopy(decoded, 0, ivBytes, 0, ivBytes.length);
    System.arraycopy(decoded, ivBytes.length, encryptedText, 0, encryptedText.length);
    System.arraycopy(decoded, decoded.length - salt.length, salt, 0, salt.length);

    // generate the key from the acquired data
    SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
    PBEKeySpec spec = new PBEKeySpec(password, salt, 16384, this.keyLength);
    SecretKey key = factory.generateSecret(spec);
    SecretKeySpec keySpec = new SecretKeySpec(key.getEncoded(), "AES");

    // finally, attempt to decrypt the encryptedText
    cipher.init(Cipher.DECRYPT_MODE, keySpec, new IvParameterSpec(ivBytes));
    return cipher.doFinal(encryptedText);
}

From source file:org.linagora.linshare.core.utils.SymmetricEnciphermentPBEwithAES.java

private static SecretKey getSecretKey(String pw) throws NoSuchAlgorithmException, InvalidKeySpecException {

    PBEKeySpec key_spec = new PBEKeySpec(pw.toCharArray());
    SecretKeyFactory key_factory = SecretKeyFactory.getInstance(SECRETKEYFACTORY_ALGO);
    SecretKey secret_key = key_factory.generateSecret(key_spec);

    return secret_key;
}

From source file:graphene.util.crypto.PasswordHash.java

/**
 * Computes the PBKDF2 hash of a password.
 * //from   w ww .java 2  s  .co m
 * @param password
 *            the password to hash.
 * @param salt
 *            the salt
 * @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(final char[] password, final byte[] salt, final int iterations, final int bytes)
        throws NoSuchAlgorithmException, InvalidKeySpecException {
    final PBEKeySpec spec = new PBEKeySpec(password, salt, iterations, bytes * 8);
    final SecretKeyFactory skf = SecretKeyFactory.getInstance(PBKDF2_ALGORITHM);
    return skf.generateSecret(spec).getEncoded();
}

From source file:org.apache.hadoop.hbase.io.crypto.Encryption.java

/**
 * Return a 128 bit key derived from the concatenation of the supplied
 * arguments using PBKDF2WithHmacSHA1 at 10,000 iterations.
 * //from ww w  . j a  v  a  2 s  .c o  m
 */
public static byte[] pbkdf128(byte[]... args) {
    byte[] salt = new byte[128];
    Bytes.random(salt);
    StringBuilder sb = new StringBuilder();
    for (byte[] b : args) {
        sb.append(Arrays.toString(b));
    }
    PBEKeySpec spec = new PBEKeySpec(sb.toString().toCharArray(), salt, 10000, 128);
    try {
        return SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1").generateSecret(spec).getEncoded();
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    } catch (InvalidKeySpecException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.jumpmind.security.SecurityService.java

protected SecretKey getDefaultSecretKey() throws Exception {
    String keyPassword = nextSecureHexString(8);
    KeySpec keySpec = new PBEKeySpec(keyPassword.toCharArray(), SecurityConstants.SALT,
            SecurityConstants.ITERATION_COUNT, 56);
    SecretKey secretKey = SecretKeyFactory.getInstance(SecurityConstants.ALGORITHM).generateSecret(keySpec);
    return secretKey;
}

From source file:org.apache.ofbiz.base.crypto.HashCrypt.java

public static String pbkdf2HashCrypt(String hashType, String salt, String value) {
    char[] chars = value.toCharArray();
    if (UtilValidate.isEmpty(salt)) {
        salt = getSalt();//w  ww  .  j  a  va2  s .  c  o  m
    }
    try {
        PBEKeySpec spec = new PBEKeySpec(chars, salt.getBytes(UtilIO.getUtf8()), PBKDF2_ITERATIONS, 64 * 4);
        SecretKeyFactory skf = SecretKeyFactory.getInstance(hashType);
        byte[] hash = Base64.encodeBase64(skf.generateSecret(spec).getEncoded());
        String pbkdf2Type = null;
        switch (hashType) {
        case "PBKDF2WithHmacSHA1":
            pbkdf2Type = PBKDF2_SHA1;
            break;
        case "PBKDF2WithHmacSHA256":
            pbkdf2Type = PBKDF2_SHA256;
            break;
        case "PBKDF2WithHmacSHA384":
            pbkdf2Type = PBKDF2_SHA384;
            break;
        case "PBKDF2WithHmacSHA512":
            pbkdf2Type = PBKDF2_SHA512;
            break;
        default:
            pbkdf2Type = PBKDF2_SHA1;
        }
        StringBuilder sb = new StringBuilder();
        sb.append("{").append(pbkdf2Type).append("}");
        sb.append(PBKDF2_ITERATIONS).append("$");
        sb.append(org.apache.ofbiz.base.util.Base64.base64Encode(salt)).append("$");
        sb.append(new String(hash)).toString();
        return sb.toString();
    } catch (InvalidKeySpecException e) {
        throw new GeneralRuntimeException("Error while creating SecretKey", e);
    } catch (NoSuchAlgorithmException e) {
        throw new GeneralRuntimeException("Error while computing SecretKeyFactory", e);
    }
}

From source file:com.yaxin.utils.StringUtils.java

/**
 * //from w  w  w  .  j  a v  a 2 s  .  c om
 * @param src 
 * @param key 8
 * @return     
 * @throws Exception
 */
public static byte[] encrypt(byte[] src, byte[] key) throws Exception {
    //      DES
    SecureRandom sr = new SecureRandom();
    // DESKeySpec
    DESKeySpec dks = new DESKeySpec(key);
    // DESKeySpec
    // SecretKey
    SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
    SecretKey securekey = keyFactory.generateSecret(dks);
    // Cipher
    Cipher cipher = Cipher.getInstance(DES);
    // Cipher
    cipher.init(Cipher.ENCRYPT_MODE, securekey, sr);
    // 
    // 
    return cipher.doFinal(src);
}

From source file:ropes.Crypto.java

/**
* If a file is being decrypted, we need to know the pasword, the salt and the initialization vector (iv). 
* We have the password from initializing the class. pass the iv and salt here which is
* obtained when encrypting the file initially.
*   /*from   www  .j a v  a  2 s.  co m*/
* @param initvec
* @param salt
* @throws NoSuchAlgorithmException
* @throws InvalidKeySpecException
* @throws NoSuchPaddingException
* @throws InvalidKeyException
* @throws InvalidAlgorithmParameterException
* @throws DecoderException
*/
public void setupDecrypt(String initvec, String salt) {
    try {
        SecretKeyFactory factory = null;
        SecretKey tmp = null;
        SecretKey secret = null;

        // since we pass it as a string of input, convert to a actual byte buffer here
        mSalt = Hex.decodeHex(salt.toCharArray());
        Db("got salt " + Hex.encodeHexString(mSalt));

        // get initialization vector from passed string
        mInitVec = Hex.decodeHex(initvec.toCharArray());
        Db("got initvector :" + Hex.encodeHexString(mInitVec));

        /* 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
        factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
        KeySpec spec = new PBEKeySpec(mPassword.toCharArray(), mSalt, ITERATIONS, KEYLEN_BITS);

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

        /* Decrypt the message, given derived key and initialization vector. */
        mDecipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        mDecipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(mInitVec));

    } catch (DecoderException ex) {
        Logger.getLogger(Crypto.class.getName()).log(Level.SEVERE, null, ex);
    } catch (NoSuchAlgorithmException ex) {
        Logger.getLogger(Crypto.class.getName()).log(Level.SEVERE, null, ex);
    } catch (NoSuchPaddingException ex) {
        Logger.getLogger(Crypto.class.getName()).log(Level.SEVERE, null, ex);
    } catch (InvalidKeySpecException ex) {
        Logger.getLogger(Crypto.class.getName()).log(Level.SEVERE, null, ex);
    } catch (InvalidKeyException ex) {
        Logger.getLogger(Crypto.class.getName()).log(Level.SEVERE, null, ex);
    } catch (InvalidAlgorithmParameterException ex) {
        Logger.getLogger(Crypto.class.getName()).log(Level.SEVERE, null, ex);
    }
}