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.fegor.alfresco.security.crypto.Crypto.java

/**
 * Encryption configuration/*from ww w . j a v  a  2s .  co m*/
 * 
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeySpecException
 * @throws NoSuchPaddingException
 * @throws InvalidParameterSpecException
 * @throws IllegalBlockSizeException
 * @throws BadPaddingException
 * @throws UnsupportedEncodingException
 * @throws InvalidKeyException
 */
public void configEncrypt() throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException,
        InvalidParameterSpecException, IllegalBlockSizeException, BadPaddingException,
        UnsupportedEncodingException, InvalidKeyException {
    SecretKeyFactory factory = null;
    SecretKey tmp = null;

    salt_pos = new byte[SALT_LEN];
    SecureRandom rnd = new SecureRandom();
    rnd.nextBytes(salt_pos);

    if (logger.isDebugEnabled())
        logger.debug(this.getClass().getName() + ": [salt: " + (new String(Hex.encodeHex(salt_pos))) + "]");

    factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");

    /*
     * http://www.javamex.com/tutorials/cryptography/unrestricted_policy_files
     * .shtml
     */
    KeySpec spec = new PBEKeySpec(password.toCharArray(), salt_pos, ITERATIONS, KEYLEN_BITS);
    tmp = factory.generateSecret(spec);
    SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES");

    eCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    eCipher.init(Cipher.ENCRYPT_MODE, secret);
    AlgorithmParameters params = eCipher.getParameters();

    vector_init = params.getParameterSpec(IvParameterSpec.class).getIV();

    if (logger.isDebugEnabled())
        logger.debug(
                this.getClass().getName() + ": [vector ini: " + (new String(Hex.encodeHex(vector_init))) + "]");
}

From source file:org.apache.xml.security.test.encryption.XMLCipherTester.java

public void testTrippleDesDocumentCipher() throws Exception {
    Document d = document(); // source
    Document ed = null; // target
    Document dd = null; // target
    Element e = d.getDocumentElement();
    Element ee = null;//ww w  .  j a v a  2  s .c  o  m

    String source = null;
    String target = null;

    if (haveISOPadding) {

        source = toString(d);

        // prepare for encryption
        byte[] passPhrase = "24 Bytes per DESede key!".getBytes();
        DESedeKeySpec keySpec = new DESedeKeySpec(passPhrase);
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DESede");
        SecretKey key = keyFactory.generateSecret(keySpec);

        // encrypt
        cipher = XMLCipher.getInstance(XMLCipher.TRIPLEDES);
        cipher.init(XMLCipher.ENCRYPT_MODE, key);
        ed = cipher.doFinal(d, e);

        //decrypt
        cipher = XMLCipher.getInstance(XMLCipher.TRIPLEDES);
        cipher.init(XMLCipher.DECRYPT_MODE, key);
        ee = (Element) ed.getElementsByTagName("xenc:EncryptedData").item(0);
        dd = cipher.doFinal(ed, ee);

        target = toString(dd);

        Assert.assertEquals(source, target);
    } else {
        log.warn("Test testTrippleDesDocumentCipher skipped as necessary algorithms not available");
    }
}

From source file:org.apache.xml.security.test.encryption.XMLCipherTester.java

public void testTrippleDesElementCipher() throws Exception {
    Document d = document(); // source
    Document ed = null; // target
    Document dd = null; // target
    Element e = (Element) d.getElementsByTagName(element()).item(index());
    Element ee = null;/*from   w ww. ja  v a  2 s  .  c o  m*/

    String source = null;
    String target = null;

    if (haveISOPadding) {

        source = toString(d);

        // prepare for encryption
        byte[] passPhrase = "24 Bytes per DESede key!".getBytes();
        DESedeKeySpec keySpec = new DESedeKeySpec(passPhrase);
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DESede");
        SecretKey key = keyFactory.generateSecret(keySpec);

        // encrypt
        cipher = XMLCipher.getInstance(XMLCipher.TRIPLEDES);
        cipher.init(XMLCipher.ENCRYPT_MODE, key);
        ed = cipher.doFinal(d, e);

        //decrypt
        cipher = XMLCipher.getInstance(XMLCipher.TRIPLEDES);
        cipher.init(XMLCipher.DECRYPT_MODE, key);
        ee = (Element) ed.getElementsByTagName("xenc:EncryptedData").item(0);
        EncryptedData encryptedData = cipher.loadEncryptedData(ed, ee);
        Assert.assertEquals(encryptedData.getEncryptionMethod().getAlgorithm(), XMLCipher.TRIPLEDES);
        dd = cipher.doFinal(ed, ee);

        target = toString(dd);
        Assert.assertEquals(source, target);
    } else {
        log.warn("Test testTrippleDesElementCipher skipped as necessary algorithms not available");
    }
}

From source file:org.apache.sling.discovery.base.connectors.ping.TopologyRequestValidator.java

/**
 * @param salt number of the key.//from   www.ja v  a 2 s  .  c om
 * @return the CupherKey.
 * @throws UnsupportedEncodingException
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeySpecException
 */
private Key getCiperKey(byte[] salt)
        throws UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeySpecException {
    SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
    // hashing the password 65K times takes 151ms, hashing 256 times takes 2ms.
    // Since the salt has 2^^72 values, 256 times is probably good enough.
    KeySpec spec = new PBEKeySpec(sharedKey.toCharArray(), salt, 256, 128);
    SecretKey tmp = factory.generateSecret(spec);
    SecretKey key = new SecretKeySpec(tmp.getEncoded(), "AES");
    return key;
}

From source file:org.apache.xml.security.test.encryption.XMLCipherTester.java

/**
 * Test encryption using a generated AES 192 bit key that is
 * encrypted using a 3DES key.  Then reverse by decrypting 
 * EncryptedKey by hand//w ww .  java 2 s  . com
 */

public void testAES192ElementAES256KWCipher() throws Exception {

    Document d = document(); // source
    Document ed = null;
    Document dd = null;
    Element e = (Element) d.getElementsByTagName(element()).item(index());
    Element ee = null;

    String source = null;
    String target = null;

    if (haveISOPadding && haveKeyWraps) {

        source = toString(d);

        // Set up a Key Encryption Key
        byte[] bits192 = "abcdefghijklmnopqrstuvwx".getBytes();
        DESedeKeySpec keySpec = new DESedeKeySpec(bits192);
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DESede");
        Key kek = keyFactory.generateSecret(keySpec);

        // Generate a traffic key
        KeyGenerator keygen = KeyGenerator.getInstance("AES");
        keygen.init(192);
        Key key = keygen.generateKey();

        cipher = XMLCipher.getInstance(XMLCipher.TRIPLEDES_KeyWrap);
        cipher.init(XMLCipher.WRAP_MODE, kek);
        EncryptedKey encryptedKey = cipher.encryptKey(d, key);

        // encrypt
        cipher = XMLCipher.getInstance(XMLCipher.AES_192);
        cipher.init(XMLCipher.ENCRYPT_MODE, key);
        EncryptedData builder = cipher.getEncryptedData();

        KeyInfo builderKeyInfo = builder.getKeyInfo();
        if (builderKeyInfo == null) {
            builderKeyInfo = new KeyInfo(d);
            builder.setKeyInfo(builderKeyInfo);
        }

        builderKeyInfo.add(encryptedKey);

        ed = cipher.doFinal(d, e);

        //decrypt
        key = null;
        ee = (Element) ed.getElementsByTagName("xenc:EncryptedData").item(0);
        cipher = XMLCipher.getInstance();
        cipher.init(XMLCipher.DECRYPT_MODE, null);

        EncryptedData encryptedData = cipher.loadEncryptedData(ed, ee);

        if (encryptedData == null) {
            System.out.println("ed is null");
        } else if (encryptedData.getKeyInfo() == null) {
            System.out.println("ki is null");
        }
        EncryptedKey ek = encryptedData.getKeyInfo().itemEncryptedKey(0);

        if (ek != null) {
            XMLCipher keyCipher = XMLCipher.getInstance();
            keyCipher.init(XMLCipher.UNWRAP_MODE, kek);
            key = keyCipher.decryptKey(ek, encryptedData.getEncryptionMethod().getAlgorithm());
        }

        // Create a new cipher just to be paranoid
        XMLCipher cipher3 = XMLCipher.getInstance();
        cipher3.init(XMLCipher.DECRYPT_MODE, key);
        dd = cipher3.doFinal(ed, ee);

        target = toString(dd);

        Assert.assertEquals(source, target);
    } else {
        log.warn("Test testAES192ElementAES256KWCipher skipped as necessary algorithms not available");
    }
}

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

@Override
public boolean changePassphrase(String oldPassphrase, String newPassphrase) {
    SecretKeyFactory secretKeyFactory;

    File headerFileOld = new File(this.vaultPath + VAULT_HEADER_FILENAME);
    File headerFileNew = new File(this.vaultPath + VAULT_HEADER_FILENAME + "NEW");
    if (!headerFileNew.exists()) {
        try {/* ww w. j  a v a2s .c  o  m*/
            // Decrypt AES encryption key
            secretKeyFactory = SecretKeyFactory.getInstance(SECRET_KEY_ALGORITHM);
            SecretKey oldKeyFromPassphrase = secretKeyFactory.generateSecret(
                    new PBEKeySpec(oldPassphrase.toCharArray(), vaultHeader.getSalt().toByteArray(),
                            vaultHeader.getPbkdf2Iterations(), AES_KEY_SIZE_BIT));
            Cipher c = Cipher.getInstance(HEADER_ENCRYPTION_MODE);
            c.init(Cipher.UNWRAP_MODE, oldKeyFromPassphrase,
                    new IvParameterSpec(vaultHeader.getVaultIV().toByteArray()));
            Key decryptedKey = c.unwrap(vaultHeader.getEncryptedAesKey().toByteArray(), KEY_ALGORITHM,
                    Cipher.SECRET_KEY);

            // Create new vault nonce and salt
            byte[] vaultNonce = new byte[NONCE_LENGTH_BYTE];
            byte[] salt = new byte[SALT_SIZE_BYTE];
            secureRandom.nextBytes(vaultNonce);
            secureRandom.nextBytes(salt);

            int pbkdf2Iterations = generatePBKDF2IterationCount(newPassphrase, salt);

            // Create new key for AES key encryption
            SecretKey newKeyFromPassphrase = secretKeyFactory.generateSecret(
                    new PBEKeySpec(newPassphrase.toCharArray(), salt, pbkdf2Iterations, AES_KEY_SIZE_BIT));

            writeVaultHeader(headerFileNew, vaultNonce, salt, pbkdf2Iterations, decryptedKey,
                    newKeyFromPassphrase);

        } catch (Exception e) {
            Util.log("Error while reading or creating new vault header!");
            return false;
        }
    } else {
        Util.log("New header file already exists. Cannot change passphrase!");
        return false;
    }

    // Try to parse new header file
    try {
        FileInputStream headerInputStream = new FileInputStream(headerFileNew);
        vaultHeader = VaultHeader.parseFrom(headerInputStream);
    } catch (Exception e) {
        Util.log("Cannot read vault header!");
        headerFileNew.delete();
        return false;
    }

    // Delete old header file and replace with new header file
    if (!headerFileOld.delete()) {
        headerFileNew.delete();
        Util.log("Cannot delete old vault header!");
        return false;
    }
    try {
        org.apache.commons.io.FileUtils.copyFile(headerFileNew, headerFileOld);
    } catch (IOException e) {
        Util.log("Cannot replace old vault header!");
        return false;
    }

    headerFileNew.delete();
    return true;
}

From source file:org.alfresco.encryption.AlfrescoKeyStoreImpl.java

protected Key getSecretKey(KeyInformation keyInformation)
        throws NoSuchAlgorithmException, InvalidKeyException, InvalidKeySpecException {
    byte[] keyData = keyInformation.getKeyData();

    if (keyData == null) {
        if (keyInformation.getKeyAlgorithm().equals("DESede")) {
            // no key data provided, generate key data automatically
            keyData = generateKeyData();
        } else {/*from   w  w  w. java 2  s  .  co m*/
            throw new AlfrescoRuntimeException(
                    "Unable to generate secret key: key algorithm is not DESede and no keyData provided");
        }
    }

    DESedeKeySpec keySpec = new DESedeKeySpec(keyData);
    SecretKeyFactory kf = SecretKeyFactory.getInstance(keyInformation.getKeyAlgorithm());
    SecretKey secretKey = kf.generateSecret(keySpec);
    return secretKey;
}

From source file:org.tolven.config.model.CredentialManager.java

private void writeDER(char[] password, PrivateKey privateKey, File file)
        throws IOException, GeneralSecurityException {
    byte[] bytes = null;
    if (password == null) {
        bytes = privateKey.getEncoded();
    } else {/*from  w  ww .  j  ava  2 s . c om*/
        SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
        PBEKeySpec passwordSpec = new PBEKeySpec(password);
        SecretKey secretKey = secretKeyFactory.generateSecret(passwordSpec);
        Cipher cipher = Cipher.getInstance(secretKey.getAlgorithm());
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);
        byte[] encryptedPrivateKey = cipher.doFinal(privateKey.getEncoded());
        EncryptedPrivateKeyInfo encryptedPrivateKeyInfo = new EncryptedPrivateKeyInfo(cipher.getParameters(),
                encryptedPrivateKey);
        bytes = encryptedPrivateKeyInfo.getEncoded();
    }
    FileUtils.writeByteArrayToFile(file, bytes);
}

From source file:org.tolven.config.model.CredentialManager.java

private PrivateKey getDERPrivateKey(CertificateKeyDetail keyDetail, char[] password)
        throws IOException, GeneralSecurityException {
    File privateKeyFile = new File(keyDetail.getSource());
    if (!privateKeyFile.exists()) {
        throw new RuntimeException("Cannot find PrivateKey file: " + privateKeyFile.getPath());
    }//from  w  ww .  ja  v  a 2 s.c o m
    byte[] privateKey = FileUtils.readFileToByteArray(privateKeyFile);
    EncryptedPrivateKeyInfo encryptedKeyInfo = new EncryptedPrivateKeyInfo(privateKey);
    AlgorithmParameters params = encryptedKeyInfo.getAlgParameters();
    SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(encryptedKeyInfo.getAlgName());
    PBEKeySpec passwordSpec = new PBEKeySpec(password);
    SecretKey secretKey = secretKeyFactory.generateSecret(passwordSpec);
    Cipher cipher = Cipher.getInstance(encryptedKeyInfo.getAlgName());
    cipher.init(Cipher.DECRYPT_MODE, secretKey, params);
    PKCS8EncodedKeySpec keySpec = encryptedKeyInfo.getKeySpec(cipher);
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    return keyFactory.generatePrivate(keySpec);
}

From source file:com.evolveum.midpoint.prism.crypto.ProtectorImpl.java

private boolean compareHashedPbkd(HashedDataType hashedDataType, String algorithmName, char[] clearChars)
        throws EncryptionException {
    DigestMethodType digestMethodType = hashedDataType.getDigestMethod();
    byte[] salt = digestMethodType.getSalt();
    Integer workFactor = digestMethodType.getWorkFactor();
    byte[] digestValue = hashedDataType.getDigestValue();
    int keyLen = digestValue.length * 8;

    SecretKeyFactory secretKeyFactory;
    try {//  w ww.j a v  a2  s  .  c  o m
        secretKeyFactory = SecretKeyFactory.getInstance(algorithmName);
    } catch (NoSuchAlgorithmException e) {
        throw new EncryptionException(e.getMessage(), e);
    }
    PBEKeySpec keySpec = new PBEKeySpec(clearChars, salt, workFactor, keyLen);
    SecretKey key;
    try {
        key = secretKeyFactory.generateSecret(keySpec);
    } catch (InvalidKeySpecException e) {
        throw new EncryptionException(e.getMessage(), e);
    }
    byte[] hashBytes = key.getEncoded();

    return Arrays.equals(digestValue, hashBytes);
}