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.mb.framework.util.SecurityUtil.java

/**
 * //from  w w w  .  jav a  2  s. c o m
 * This method is used for decrypt by using Algorithm - AES/CBC/PKCS5Padding
 * 
 * @param String
 * @return String
 * @throws Exception
 */
@SuppressWarnings("static-access")
public static String decryptAESPBKDF2(String encryptedText) throws Exception {

    byte[] saltBytes = salt.getBytes("UTF-8");
    byte[] encryptedTextBytes = new Base64().decodeBase64(encryptedText);

    // 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");

    // Decrypt the message
    Cipher cipher = Cipher.getInstance(AES_CBC_PKCS5PADDING_ALGO);
    cipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(ivBytes));

    byte[] decryptedTextBytes = null;
    try {
        decryptedTextBytes = cipher.doFinal(encryptedTextBytes);
    } catch (IllegalBlockSizeException e) {

        LOGGER.error("error " + e.getMessage());
    } catch (BadPaddingException e) {
        LOGGER.error("error " + e.getMessage());
    }

    return new String(decryptedTextBytes);
}

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

public static boolean isValid(String plainText, String HMAC, String key) {
    try {/*w ww.  ja v  a2  s.c  o m*/
        System.out.println("HMAC on = " + plainText);
        SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256",
                new BouncyCastleProvider());
        char password[] = key.toCharArray();
        byte salt[] = "salt".getBytes();
        KeySpec spec = new PBEKeySpec(password, salt, 65536, 256);
        SecretKey tmp = factory.generateSecret(spec);
        SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "HmacSHA256");
        // Get an hmac_sha1 Mac instance and initialize with the signing key
        Mac mac = Mac.getInstance("HmacSHA256", new BouncyCastleProvider());
        mac.init(secret);
        // Compute the hmac on input data bytes
        byte[] rawHmac = mac.doFinal(plainText.getBytes());
        // Convert raw bytes to Hex
        byte[] hexBytes = new Hex().encode(rawHmac);

        //  Covert array of Hex bytes to a String
        String check = new String(hexBytes, "UTF-8");
        System.out.println("Checking = " + check);
        return check.equals(HMAC);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

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

public static String hmacSha256(String key, String value) {
    try {//  w  ww .j av a  2s .  co  m
        //System.out.println(Base64.getEncoder().encodeToString(keyBytes));
        // Get an hmac_sha256 key from the raw key bytes
        System.out.println("First HMAC on = " + value);
        SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256",
                new BouncyCastleProvider());
        char password[] = key.toCharArray();
        byte salt[] = "salt".getBytes();
        KeySpec spec = new PBEKeySpec(password, salt, 65536, 256);
        SecretKey tmp = factory.generateSecret(spec);
        SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "HmacSHA256");

        // Get an hmac_sha256 Mac instance and initialize with the signing key
        Mac mac = Mac.getInstance("HmacSHA256", new BouncyCastleProvider());
        mac.init(secret);

        // Compute the hmac on input data bytes
        byte[] rawHmac = mac.doFinal(value.getBytes());

        // Convert raw bytes to Hex
        byte[] hexBytes = new Hex().encode(rawHmac);
        //  Covert array of Hex bytes to a String
        return new String(hexBytes, "UTF-8");
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

}

From source file:CipherProvider.java

/**
 * Create cipher for encrypt or decrypt backup content
 *
 * @param passwd passwd for encryption/* w w  w  .  ja v  a  2s . c  o  m*/
 * @param mode   encrypt/decrypt mode
 *
 * @return instance of cipher
 */
private static Cipher getCipher(final String passwd, final int mode) {
    /* Derive the key, given password and salt. */
    Cipher cipher = null;
    try {
        SecretKeyFactory factory = null;
        factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
        String salt = "slNadZlato#%^^&(&(5?@#5166?1561?#%^^*^&54431"; // only pseudorandom salt
        KeySpec spec = new PBEKeySpec(passwd.toCharArray(), salt.getBytes(), 65536, 128);
        SecretKey tmp = factory.generateSecret(spec);
        SecretKey secret = new SecretKeySpec(tmp.getEncoded(), CIPHER_TYPE);

        // initialization vector
        byte[] iv = Arrays.copyOfRange(DigestUtils.md5(passwd), 0, 16);
        AlgorithmParameterSpec paramSpec = new IvParameterSpec(iv);

        // Cipher for encryption
        cipher = Cipher.getInstance(CIPHER_TYPE + "/CBC/PKCS5Padding");
        cipher.init(mode, secret, paramSpec);
    } catch (Exception e) {
        e.printStackTrace(); //Todo implementovat
    }
    return cipher;
}

From source file:eu.eubrazilcc.lvl.storage.security.shiro.CryptProvider.java

/**
 * Joins the tokens and dates provided as parameters with a salt generated from {@link #DEFAULT_STRENGTH} random bytes and computes a digest using 
 * the PBKDF2 key derivation function./*w w w  . java  2  s  . com*/
 * @param tokens - list of input tokens
 * @param dates - list of input dates
 * @return a digest of the input parameters (tokens and dates).
 * @throws IOException is thrown if the computation of the digest fails.
 * @see <a href="http://docs.oracle.com/javase/7/docs/technotes/guides/security/StandardNames.html">JCA Standard Algorithm Name Documentation</a>
 */
private static byte[] digest(final @Nullable String[] tokens, @Nullable final Date[] dates) throws IOException {
    try {
        String mixName = "";
        if (tokens != null) {
            for (final String token : tokens) {
                mixName += (token != null ? token.trim() : "");
            }
        }
        if (dates != null) {
            for (final Date date : dates) {
                mixName += (date != null ? Long.toString(date.getTime()) : "");
            }
        }
        // compute digest
        final byte[] bytesOfMixName = mixName.getBytes(UTF_8.name());
        final char[] charOfMixName = new String(bytesOfMixName).toCharArray();
        final byte[] salt = generateSalt(SALT_BYTES_SIZE);
        final SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
        final PBEKeySpec spec = new PBEKeySpec(charOfMixName, salt, KEY_DEVIATION_ITERATIONS,
                SALT_BYTES_SIZE * 8);
        return factory.generateSecret(spec).getEncoded();
    } catch (Exception e) {
        throw new IOException("Digest computation has failed", e);
    }
}

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

public static boolean doComparePbkdf2(String crypted, String password) {
    try {/*from w  w  w. ja  v a 2s. c om*/
        int typeEnd = crypted.indexOf("}");
        String hashType = crypted.substring(1, typeEnd);
        String[] parts = crypted.split("\\$");
        int iterations = Integer.parseInt(parts[0].substring(typeEnd + 1));
        byte[] salt = org.apache.ofbiz.base.util.Base64.base64Decode(parts[1]).getBytes();
        byte[] hash = Base64.decodeBase64(parts[2].getBytes());

        PBEKeySpec spec = new PBEKeySpec(password.toCharArray(), salt, iterations, hash.length * 8);
        switch (hashType.substring(hashType.indexOf("-") + 1)) {
        case "SHA256":
            hashType = "PBKDF2WithHmacSHA256";
            break;
        case "SHA384":
            hashType = "PBKDF2WithHmacSHA384";
            break;
        case "SHA512":
            hashType = "PBKDF2WithHmacSHA512";
            break;
        default:
            hashType = "PBKDF2WithHmacSHA1";
        }
        SecretKeyFactory skf = SecretKeyFactory.getInstance(hashType);
        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];
        }

        return diff == 0;
    } catch (NoSuchAlgorithmException e) {
        throw new GeneralRuntimeException("Error while computing SecretKeyFactory", e);
    } catch (InvalidKeySpecException e) {
        throw new GeneralRuntimeException("Error while creating SecretKey", e);
    }
}

From source file:bioLockJ.module.agent.MailAgent.java

private static String encrypt(final String password)
        throws GeneralSecurityException, UnsupportedEncodingException {
    final SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
    final SecretKey key = keyFactory.generateSecret(new PBEKeySpec(PASSWORD));
    final Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");
    pbeCipher.init(Cipher.ENCRYPT_MODE, key, new PBEParameterSpec(SALT, 20));
    return base64Encode(pbeCipher.doFinal(password.getBytes("UTF-8")));
}

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();//from  w  ww .  jav a 2  s.co  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.glaf.core.security.SecurityUtils.java

/**
 * DES//from   w  w  w.j  av a2 s . c om
 * 
 * @param data
 *            
 * @param key
 *            ???8?
 * @return ?
 */
public static String decode(String key, String data) {
    if (data == null) {
        return null;
    }
    try {
        DESKeySpec dks = new DESKeySpec(key.getBytes());
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        // key??8?
        Key secretKey = keyFactory.generateSecret(dks);
        Cipher cipher = Cipher.getInstance(ALGORITHM_DES);
        IvParameterSpec iv = new IvParameterSpec("12345678".getBytes());
        AlgorithmParameterSpec paramSpec = iv;
        cipher.init(Cipher.DECRYPT_MODE, secretKey, paramSpec);
        return new String(cipher.doFinal(hex2byte(data.getBytes())));
    } catch (Exception ex) {
        ex.printStackTrace();
        throw new SecurityException(ex);
    }
}

From source file:com.glaf.core.security.SecurityUtils.java

/**
 * DES/*  ww  w. j  a v a  2  s. c  om*/
 * 
 * @param data
 *            
 * @param key
 *            ???8?
 * @return ?
 */
public static String encode(String key, String data) {
    if (data == null) {
        return null;
    }
    try {
        DESKeySpec dks = new DESKeySpec(key.getBytes());
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        // key??8?
        Key secretKey = keyFactory.generateSecret(dks);
        Cipher cipher = Cipher.getInstance(ALGORITHM_DES);
        IvParameterSpec iv = new IvParameterSpec("12345678".getBytes());
        AlgorithmParameterSpec paramSpec = iv;
        cipher.init(Cipher.ENCRYPT_MODE, secretKey, paramSpec);
        byte[] bytes = cipher.doFinal(data.getBytes());
        return byte2hex(bytes);
    } catch (Exception ex) {
        throw new SecurityException(ex);
    }
}