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:TripleDES.java

/** Read a TripleDES secret key from the specified file */
public static SecretKey readKey(File f)
        throws IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidKeySpecException {
    // Read the raw bytes from the keyfile
    DataInputStream in = new DataInputStream(new FileInputStream(f));
    byte[] rawkey = new byte[(int) f.length()];
    in.readFully(rawkey);/*from www  . ja v a  2s . c o m*/
    in.close();

    // Convert the raw bytes to a secret key like this
    DESedeKeySpec keyspec = new DESedeKeySpec(rawkey);
    SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("DESede");
    SecretKey key = keyfactory.generateSecret(keyspec);
    return key;
}

From source file:com.aspose.showcase.qrcodegen.web.api.util.StringEncryptor.java

public static String encrypt(String data, String password) throws Exception {

    Security.addProvider(new BouncyCastleProvider());
    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding", "BC");

    final Random r = new SecureRandom();
    byte[] salt = new byte[SALT_SIZE];
    r.nextBytes(salt);/* w w  w .  j ava2s .  c om*/

    SecretKeyFactory fact = SecretKeyFactory.getInstance("PBEWITHMD5AND128BITAES-CBC-OPENSSL", "BC");

    cipher.init(Cipher.ENCRYPT_MODE,
            fact.generateSecret(new PBEKeySpec(password.toCharArray(), salt, PBE_KEY_SALE_SIZE)));

    byte[] encVal = cipher.doFinal(data.getBytes());

    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    // writing encrypted data along with the salt in the format readable by
    // open ssl api
    bos.write("Salted__".getBytes());
    bos.write(salt);
    bos.write(encVal);
    String encryptedValue = new String(Base64.encode(bos.toByteArray()));
    bos.close();

    return encryptedValue;

}

From source file:com.beligum.core.accounts.UserManager.java

private static String hash(String password, String salt) {
    KeySpec spec = new PBEKeySpec(password.toCharArray(), salt.getBytes(), 2048, 160);
    try {//from www. j  ava2s  .  c o m
        SecretKeyFactory f = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
        byte[] hash = f.generateSecret(spec).getEncoded();
        return new String(Hex.encodeHex(hash));
    } catch (Exception e) {
        return null;
    }

}

From source file:org.casbah.provider.KeyHelper.java

public static PrivateKey readKey(String keypass, byte[] keyData) throws CAProviderException {
    try {/*from w w w.  j  a va2 s  .  c  o m*/
        EncryptedPrivateKeyInfo pkInfo = new EncryptedPrivateKeyInfo(keyData);
        PBEKeySpec keySpec = new PBEKeySpec(keypass.toCharArray());
        SecretKeyFactory pbeKeyFactory = SecretKeyFactory.getInstance(pkInfo.getAlgName());
        PKCS8EncodedKeySpec encodedKeySpec = pkInfo.getKeySpec(pbeKeyFactory.generateSecret(keySpec));
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        return (RSAPrivateCrtKey) keyFactory.generatePrivate(encodedKeySpec);
    } catch (Exception e) {
        throw new CAProviderException("Could not decode private key", e);
    }

}

From source file:com.networknt.light.util.HashUtil.java

public static boolean validatePassword(String originalPassword, String storedPassword)
        throws NoSuchAlgorithmException, InvalidKeySpecException {
    String[] parts = storedPassword.split(":");
    int iterations = Integer.parseInt(parts[0]);
    byte[] salt = fromHex(parts[1]);
    byte[] hash = fromHex(parts[2]);

    PBEKeySpec spec = new PBEKeySpec(originalPassword.toCharArray(), salt, iterations, hash.length * 8);
    SecretKeyFactory skf = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
    byte[] testHash = skf.generateSecret(spec).getEncoded();

    int diff = hash.length ^ testHash.length;
    for (int i = 0; i < hash.length && i < testHash.length; i++) {
        diff |= hash[i] ^ testHash[i];//from ww  w  . jav a  2s  .  c o m
    }
    return diff == 0;
}

From source file:Main.java

private static int generateIterationCount(String passphrase, byte[] salt) {
    int TARGET_ITERATION_TIME = 50; //ms
    int MINIMUM_ITERATION_COUNT = 100; //default for low-end devices
    int BENCHMARK_ITERATION_COUNT = 10000; //baseline starting iteration count

    try {/*from  ww  w .  j  a  v  a 2 s  .  c  o  m*/
        PBEKeySpec keyspec = new PBEKeySpec(passphrase.toCharArray(), salt, BENCHMARK_ITERATION_COUNT);
        SecretKeyFactory skf = SecretKeyFactory.getInstance("PBEWITHSHA1AND128BITAES-CBC-BC");

        long startTime = System.currentTimeMillis();
        skf.generateSecret(keyspec);
        long finishTime = System.currentTimeMillis();

        int scaledIterationTarget = (int) (((double) BENCHMARK_ITERATION_COUNT
                / (double) (finishTime - startTime)) * TARGET_ITERATION_TIME);

        if (scaledIterationTarget < MINIMUM_ITERATION_COUNT)
            return MINIMUM_ITERATION_COUNT;
        else
            return scaledIterationTarget;
    } catch (NoSuchAlgorithmException e) {
        Log.w("MasterSecretUtil", e);
        return MINIMUM_ITERATION_COUNT;
    } catch (InvalidKeySpecException e) {
        Log.w("MasterSecretUtil", e);
        return MINIMUM_ITERATION_COUNT;
    }
}

From source file:com.ikon.util.SecureStore.java

/**
 * DES encoder//from  www  .j av  a 2 s .c  o  m
 */
public static byte[] desEncode(String key, byte[] src)
        throws InvalidKeyException, UnsupportedEncodingException, NoSuchAlgorithmException,
        InvalidKeySpecException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException {
    DESKeySpec keySpec = new DESKeySpec(key.getBytes("UTF8"));
    SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
    SecretKey sKey = keyFactory.generateSecret(keySpec);

    Cipher cipher = Cipher.getInstance("DES"); // cipher is not thread safe
    cipher.init(Cipher.ENCRYPT_MODE, sKey);
    byte[] dst = cipher.doFinal(src);

    return dst;
}

From source file:com.ikon.util.SecureStore.java

/**
 * DES decoder/* www  . j av  a2  s  .  c  o  m*/
 */
public static byte[] desDecode(String key, byte[] src)
        throws InvalidKeyException, UnsupportedEncodingException, NoSuchAlgorithmException,
        InvalidKeySpecException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException {
    DESKeySpec keySpec = new DESKeySpec(key.getBytes("UTF8"));
    SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
    SecretKey sKey = keyFactory.generateSecret(keySpec);

    Cipher cipher = Cipher.getInstance("DES"); // cipher is not thread safe
    cipher.init(Cipher.DECRYPT_MODE, sKey);
    byte[] dst = cipher.doFinal(src);

    return dst;
}

From source file:bit.changepurse.wdk.util.CheckedExceptionMethods.java

public static byte[] generateSecret(SecretKeyFactory skf, PBEKeySpec spec) {
    try {//from  ww  w . j  a v  a2  s  . com
        return skf.generateSecret(spec).getEncoded();
    } catch (InvalidKeySpecException e) {
        throw new UncheckedException(e);
    }
}

From source file:club.jmint.crossing.specs.Security.java

public static String desDecrypt(String data, String key) throws CrossException {
    String ret = null;/*  w  ww . j a v a  2  s  . c o m*/
    try {
        DESKeySpec desKey = new DESKeySpec(key.getBytes("UTF-8"));
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        SecretKey securekey = keyFactory.generateSecret(desKey);

        Cipher cipher = Cipher.getInstance(CIPHER_DES_ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, securekey);

        ret = new String(cipher.doFinal(Base64.decodeBase64(data)));
    } catch (Exception e) {
        CrossLog.printStackTrace(e);
        throw new CrossException(ErrorCode.COMMON_ERR_DECRYPTION.getCode(),
                ErrorCode.COMMON_ERR_DECRYPTION.getInfo());
    }
    return ret;
}