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:alfio.manager.CheckInManager.java

private static Pair<Cipher, SecretKeySpec> getCypher(String key) {
    try {// w  w  w .ja v  a  2 s  .  com
        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:net.sf.keystore_explorer.crypto.privatekey.Pkcs8Util.java

/**
 * Load an encrypted PKCS #8 private key from the specified stream. The
 * encoding of the private key may be PEM or DER.
 *
 * @param is/*from  w  ww .  java 2  s .c o m*/
 *            Stream load the encrypted private key from
 * @param password
 *            Password to decrypt
 * @return The private key
 * @throws PrivateKeyUnencryptedException
 *             If private key is unencrypted
 * @throws PrivateKeyPbeNotSupportedException
 *             If private key PBE algorithm is not supported
 * @throws CryptoException
 *             Problem encountered while loading the private key
 * @throws IOException
 *             If an I/O error occurred
 */
public static PrivateKey loadEncrypted(InputStream is, Password password) throws CryptoException, IOException {
    byte[] streamContents = ReadUtil.readFully(is);

    // Check pkcs #8 is not unencrypted
    EncryptionType encType = getEncryptionType(new ByteArrayInputStream(streamContents));

    if (encType == null) {
        // Not a valid PKCS #8 private key
        throw new CryptoException(res.getString("NotValidPkcs8.exception.message"));
    }

    if (encType == UNENCRYPTED) {
        throw new PrivateKeyUnencryptedException(res.getString("Pkcs8IsUnencrypted.exception.message"));
    }

    byte[] encPvk = null;
    // Check if stream is PEM encoded
    PemInfo pemInfo = PemUtil.decode(new ByteArrayInputStream(streamContents));

    if (pemInfo != null) {
        // It is - get DER from PEM
        encPvk = pemInfo.getContent();
    }

    /*
     * If we haven't got the encrypted bytes via PEM then just use
     * stream contents directly (assume it is DER encoded)
     */
    if (encPvk == null) {
        // Read in encrypted private key bytes
        encPvk = streamContents;
    }

    try {
        // Create encrypted private key information from bytes
        EncryptedPrivateKeyInfo epki = new EncryptedPrivateKeyInfo(encPvk);

        // Get wrapping algorithm
        String encAlg = epki.getAlgName();

        // Check algorithm is supported
        if (!checkSupportedForDecrypt(encAlg)) {
            throw new PrivateKeyPbeNotSupportedException(encAlg, MessageFormat
                    .format(res.getString("PrivateKeyWrappingAlgUnsupported.exception.message"), encAlg));
        }

        // Create algorithm parameters and decryption key
        AlgorithmParameters encAlgParams = epki.getAlgParameters();
        PBEKeySpec pbeKeySpec = new PBEKeySpec(password.toCharArray());
        SecretKeyFactory keyFact = SecretKeyFactory.getInstance(encAlg);
        SecretKey pbeKey = keyFact.generateSecret(pbeKeySpec);

        // Create cipher to create
        Cipher cipher = Cipher.getInstance(encAlg);

        // Do decryption
        cipher.init(Cipher.DECRYPT_MODE, pbeKey, encAlgParams);
        PKCS8EncodedKeySpec privateKeySpec = epki.getKeySpec(cipher);

        // Get encoding of private key
        byte[] pvkBytes = privateKeySpec.getEncoded();

        // Determine private key algorithm from key bytes
        String privateKeyAlgorithm = getPrivateKeyAlgorithm(pvkBytes);

        // Use Key Factory to create private key from encoding
        KeyFactory keyFactory = KeyFactory.getInstance(privateKeyAlgorithm);
        PrivateKey pvk = keyFactory.generatePrivate(privateKeySpec);

        return pvk;
    } catch (GeneralSecurityException ex) {
        throw new CryptoException(res.getString("NoLoadPkcs8PrivateKey.exception.message"), ex);
    }
}

From source file:org.ejbca.util.StringTools.java

public static String pbeDecryptStringWithSha256Aes192(final String in) throws IllegalBlockSizeException,
        BadPaddingException, InvalidKeyException, InvalidKeySpecException, NoSuchAlgorithmException,
        NoSuchProviderException, NoSuchPaddingException, UnsupportedEncodingException {
    if (CryptoProviderTools.isUsingExportableCryptography()) {
        log.warn("De-obfuscation not possible due to weak crypto policy.");
        return in;
    }/*from  www  .ja  va2 s .c  o m*/

    final String algorithm = "PBEWithSHA256And192BitAES-CBC-BC";
    final Cipher c = Cipher.getInstance(algorithm, "BC");
    final PBEKeySpec keySpec = new PBEKeySpec(p, getSalt(), iCount);
    final SecretKeyFactory fact = SecretKeyFactory.getInstance(algorithm, "BC");

    c.init(Cipher.DECRYPT_MODE, fact.generateSecret(keySpec));

    final byte[] dec = c.doFinal(Hex.decode(in.getBytes("UTF-8")));
    return new String(dec);
}

From source file:net.sf.keystore_explorer.crypto.privatekey.Pkcs8Util.java

/**
 * PKCS #8 encode and encrypt a private key.
 *
 * @return The encrypted encoding/* ww  w  . j av  a 2  s  .  c o  m*/
 * @param privateKey
 *            The private key
 * @param pbeType
 *            PBE algorithm to use for encryption
 * @param password
 *            Encryption password
 * @throws CryptoException
 *             Problem encountered while getting the encoded private key
 * @throws IOException
 *             If an I/O error occurred
 */
public static byte[] getEncrypted(PrivateKey privateKey, Pkcs8PbeType pbeType, Password password)
        throws CryptoException, IOException {
    try {
        byte[] pkcs8 = get(privateKey);

        // Generate PBE secret key from password
        SecretKeyFactory keyFact = SecretKeyFactory.getInstance(pbeType.jce());
        PBEKeySpec pbeKeySpec = new PBEKeySpec(password.toCharArray());
        SecretKey pbeKey = keyFact.generateSecret(pbeKeySpec);

        // Generate random salt and iteration count
        byte[] salt = generateSalt();
        int iterationCount = generateIterationCount();

        // Store in algorithm parameters
        PBEParameterSpec pbeParameterSpec = new PBEParameterSpec(salt, iterationCount);
        AlgorithmParameters params = AlgorithmParameters.getInstance(pbeType.jce());
        params.init(pbeParameterSpec);

        // Create PBE cipher from key and params
        Cipher cipher = Cipher.getInstance(pbeType.jce());
        cipher.init(Cipher.ENCRYPT_MODE, pbeKey, params);

        // Encrypt key
        byte[] encPkcs8 = cipher.doFinal(pkcs8);

        // Create and return encrypted private key information
        EncryptedPrivateKeyInfo encPrivateKeyInfo = new EncryptedPrivateKeyInfo(params, encPkcs8);

        return encPrivateKeyInfo.getEncoded();
    } catch (GeneralSecurityException ex) {
        throw new CryptoException("NoEncryptPkcs8PrivateKey.exception.message", ex);
    }
}

From source file:com.denel.facepatrol.MainActivity.java

private static SecretKey generateKey(char[] passphraseOrPin, byte[] salt)
        throws NoSuchAlgorithmException, InvalidKeySpecException {
    // Number of PBKDF2 hardening rounds to use. Larger values increase 
    // computation time. You should select a value that causes computation 
    // to take >100ms. 
    final int iterations = 1000;
    // Generate a 256-bit key
    final int outputKeyLength = 256;
    SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
    KeySpec keySpec = new PBEKeySpec(passphraseOrPin, salt, iterations, outputKeyLength);
    SecretKey secretKey = secretKeyFactory.generateSecret(keySpec);
    return secretKey;
}

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

/**
 * /*from   ww w . ja  va2s  .co m*/
 * @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:com.yaxin.utils.StringUtils.java

/**
 * //  ww  w. j  a  va  2  s.  c om
 * @param src   
 * @param key   8
 * @return      
 * @throws Exception
 */
public static byte[] decrypt(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.DECRYPT_MODE, securekey, sr);
    // 
    // 
    return cipher.doFinal(src);
}

From source file:com.bcmcgroup.flare.client.ClientUtil.java

/**
 * Encrypt plain text using AES/*from   w  ww . j  a v  a  2s .  com*/
 *
 * @param plainText the String text to be encrypted in AES
 * @return the encrypted text String
 *
 */
public static String encrypt(String plainText) {
    try {
        byte[] saltBytes = salt.getBytes("UTF-8");
        SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
        PBEKeySpec spec = new PBEKeySpec(seeds, saltBytes, iterations, keySize);
        SecretKey secretKey = factory.generateSecret(spec);
        SecretKeySpec secret = new SecretKeySpec(secretKey.getEncoded(), "AES");
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, secret, new IvParameterSpec(ivBytes));
        byte[] encryptedTextBytes = cipher.doFinal(plainText.getBytes("UTF-8"));
        return new Base64().encodeAsString(encryptedTextBytes);
    } catch (NoSuchAlgorithmException e) {
        logger.error("NoSuchAlgorithmException when attempting to encrypt a string. ");
    } catch (InvalidKeySpecException e) {
        logger.error("InvalidKeySpecException when attempting to encrypt a string. ");
    } catch (NoSuchPaddingException e) {
        logger.error("NoSuchPaddingException when attempting to encrypt a string. ");
    } catch (IllegalBlockSizeException e) {
        logger.error("IllegalBlockSizeException when attempting to encrypt a string. ");
    } catch (BadPaddingException e) {
        logger.error("BadPaddingException when attempting to encrypt a string. ");
    } catch (UnsupportedEncodingException e) {
        logger.error("UnsupportedEncodingException when attempting to encrypt a string. ");
    } catch (InvalidKeyException e) {
        logger.error("InvalidKeyException when attempting to encrypt a string. ");
    } catch (InvalidAlgorithmParameterException e) {
        logger.error("InvalidAlgorithmParameterException when attempting to encrypt a string. ");
    }
    return null;
}

From source file:com.bcmcgroup.flare.client.ClientUtil.java

/**
 * Decrypt a string value/*from   www.j  a v a  2s  .co  m*/
 *
 * @param encryptedText the text String to be decrypted
 * @return the decrypted String
 *
 */
public static String decrypt(String encryptedText) {
    try {
        byte[] saltBytes = salt.getBytes("UTF-8");
        byte[] encryptedTextBytes = Base64.decodeBase64(encryptedText);
        SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
        PBEKeySpec spec = new PBEKeySpec(seeds, saltBytes, iterations, keySize);
        SecretKey secretKey = factory.generateSecret(spec);
        SecretKeySpec secret = new SecretKeySpec(secretKey.getEncoded(), "AES");

        // Decrypt the message, given derived key and initialization vector.
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(ivBytes));
        byte[] decryptedTextBytes = null;
        try {
            decryptedTextBytes = cipher.doFinal(encryptedTextBytes);
        } catch (IllegalBlockSizeException e) {
            logger.error("IllegalBlockSizeException when attempting to decrypt a string.");
        } catch (BadPaddingException e) {
            logger.error("BadPaddingException when attempting to decrypt a string.");
        }
        if (decryptedTextBytes != null) {
            return new String(decryptedTextBytes);
        }

    } catch (NoSuchAlgorithmException e) {
        logger.error("NoSuchAlgorithmException when attempting to decrypt a string. ");
    } catch (InvalidKeySpecException e) {
        logger.error("InvalidKeySpecException when attempting to decrypt a string. ");
    } catch (NoSuchPaddingException e) {
        logger.error("NoSuchPaddingException when attempting to decrypt a string. ");
    } catch (UnsupportedEncodingException e) {
        logger.error("UnsupportedEncodingException when attempting to decrypt a string. ");
    } catch (InvalidKeyException e) {
        logger.error("InvalidKeyException when attempting to decrypt a string. ");
    } catch (InvalidAlgorithmParameterException e) {
        logger.error("InvalidAlgorithmParameterException when attempting to decrypt a string. ");
    }
    return null;
}

From source file:com.pdftron.pdf.utils.Utils.java

public static String encryptIt(Context context, String value) {
    String cryptoPass = context.getString(context.getApplicationInfo().labelRes);
    try {/* w w  w . j  av  a  2s . c o m*/
        DESKeySpec keySpec = new DESKeySpec(cryptoPass.getBytes("UTF8"));
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        SecretKey key = keyFactory.generateSecret(keySpec);

        byte[] clearText = value.getBytes("UTF8");
        // Cipher is not thread safe
        Cipher cipher = Cipher.getInstance("DES");
        cipher.init(Cipher.ENCRYPT_MODE, key);

        String encrypedValue = Base64.encodeToString(cipher.doFinal(clearText), Base64.DEFAULT);
        Log.d("MiscUtils", "Encrypted: " + value + " -> " + encrypedValue);
        return encrypedValue;

    } catch (Exception e) {
        Log.d(e.getClass().getName(), e.getMessage());
    }
    return value;
}