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:de.alpharogroup.crypto.simple.SimpleEncryptor.java

/**
 * Initializes the {@link SimpleEncryptor} object.
 * //w ww.j av a2 s.  co  m
 * @throws InvalidAlgorithmParameterException
 *             is thrown if initialization of the cypher object fails.
 * @throws NoSuchPaddingException
 *             is thrown if instantiation of the cypher object fails.
 * @throws InvalidKeySpecException
 *             is thrown if generation of the SecretKey object fails.
 * @throws NoSuchAlgorithmException
 *             is thrown if instantiation of the SecretKeyFactory object fails.
 * @throws InvalidKeyException
 *             is thrown if initialization of the cypher object fails.
 */
private void initialize() throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException,
        InvalidKeyException, InvalidAlgorithmParameterException {
    if (!isInitialized()) {
        final KeySpec keySpec;
        if (this.getPrivateKey() != null) {
            keySpec = new PBEKeySpec(this.getPrivateKey().toCharArray());
        } else {
            keySpec = new PBEKeySpec(CryptConst.PRIVATE_KEY.toCharArray());
        }
        final SecretKeyFactory factory = SecretKeyFactory.getInstance(CryptConst.PBEWITH_MD5AND_DES);
        final SecretKey key = factory.generateSecret(keySpec);
        this.cipher = Cipher.getInstance(key.getAlgorithm());
        final AlgorithmParameterSpec paramSpec = new PBEParameterSpec(CryptConst.SALT,
                CryptConst.ITERATIONCOUNT);
        this.cipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);
        initialized = true;
    }
}

From source file:com.fegor.alfresco.security.crypto.Crypto.java

/**
 * Decryption configuration/*from   w  ww  .jav a  2s  .  c o  m*/
 * 
 * @param initvec
 * @param salt
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeySpecException
 * @throws NoSuchPaddingException
 * @throws InvalidKeyException
 * @throws InvalidAlgorithmParameterException
 * @throws DecoderException
 */
public void configDecrypt(String initvec, String salt) throws NoSuchAlgorithmException, InvalidKeySpecException,
        NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, DecoderException {
    SecretKeyFactory factory = null;
    SecretKey tmp = null;
    SecretKey secret = null;

    salt_pos = Hex.decodeHex(salt.toCharArray());

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

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

    /*
     * http://www.javamex.com/tutorials/cryptography/unrestricted_policy_files
     * .shtml
     */
    factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
    KeySpec spec = new PBEKeySpec(password.toCharArray(), salt_pos, ITERATIONS, KEYLEN_BITS);

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

    deCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    deCipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(vector_init));
}

From source file:org.opennms.features.scv.impl.JCEKSSecureCredentialsVault.java

@Override
public void setCredentials(String alias, Credentials credentials) {
    try {/*from  w w  w . java 2 s  .  c  om*/
        byte[] credentialBytes = toBase64EncodedByteArray(credentials);
        SecretKeyFactory factory = SecretKeyFactory.getInstance("PBE");
        SecretKey generatedSecret = factory.generateSecret(new PBEKeySpec(
                new String(credentialBytes).toCharArray(), m_salt, m_iterationCount, m_keyLength));

        KeyStore.PasswordProtection keyStorePP = new KeyStore.PasswordProtection(m_password);
        m_keystore.setEntry(alias, new KeyStore.SecretKeyEntry(generatedSecret), keyStorePP);
        writeKeystoreToDisk();
    } catch (KeyStoreException | InvalidKeySpecException | NoSuchAlgorithmException | IOException e) {
        throw Throwables.propagate(e);
    }
}

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

private static int generatePBKDF2IterationCount(String passphrase, byte[] salt) {
    int calculatedIterations = 0;
    try {/*from w  ww  .  j a va2s.c o m*/
        PBEKeySpec pbeKeySpec = new PBEKeySpec(passphrase.toCharArray(), salt,
                Config.PBKDF2_ITERATIONS_BENCHMARK, AES_KEY_SIZE_BIT);
        SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(SECRET_KEY_ALGORITHM);

        long startTime = System.currentTimeMillis();
        secretKeyFactory.generateSecret(pbeKeySpec);
        long finishTime = System.currentTimeMillis();

        calculatedIterations = (int) ((Config.PBKDF2_ITERATIONS_BENCHMARK / (double) (finishTime - startTime))
                * Config.PBKDF2_CREATION_TARGET_MS);
    } catch (Exception e) {
        Util.log("Cannot benchmark PBKDF2!");
    }

    if (calculatedIterations > Config.PBKDF2_ITERATIONS_MIN) {
        Util.log("Using " + calculatedIterations + " PBKDF2 iterations");
        return calculatedIterations;
    }
    Util.log("Using " + Config.PBKDF2_ITERATIONS_MIN + " PBKDF2 iterations");
    return Config.PBKDF2_ITERATIONS_MIN;
}

From source file:com.cherong.mock.common.base.util.EncryptionUtil.java

/**
 * DES bytKey8?/*from ww w  .  ja v  a  2  s  .  c  om*/
 * 
 * @param bytP
 * @param bytKey
 * @return
 * @throws Exception
 */
public static byte[] encryptByDES(byte[] bytP, byte[] bytKey) throws Exception {
    DESKeySpec dks = new DESKeySpec(bytKey);
    SecretKeyFactory skf = SecretKeyFactory.getInstance("DES");
    SecretKey sk = skf.generateSecret(dks);
    Cipher cip = Cipher.getInstance(DES_CIPHER_ALGORITHM);
    cip.init(Cipher.ENCRYPT_MODE, sk);
    return cip.doFinal(bytP);
}

From source file:com.sangupta.passcode.PassCode.java

/**
 * Hash the given password.//  ww w.j a  v a  2  s. c  om
 * 
 * @param password
 *            the master password or passphrase
 * 
 * @param salt
 *            the salt to be used
 * 
 * @param entropy
 *            the entropy to be used
 * 
 * @return the byte-array representing the hash
 */
private byte[] hash(String password, String salt, int entropy) {
    // generate the hash
    try {
        PBEKeySpec spec = new PBEKeySpec(password.toCharArray(), salt.getBytes(), this.config.iterations,
                entropy + 12);
        SecretKeyFactory skf = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
        return skf.generateSecret(spec).getEncoded();
    } catch (GeneralSecurityException e) {
        System.out.println("Something went wrong!");
        System.exit(0);
    }

    return null;
}

From source file:org.artifactory.security.CryptoHelper.java

public static SecretKey generatePbeKey(String password) {
    try {//from  w  w w.j a va2s  . com
        PBEKeySpec pbeKeySpec = new PBEKeySpec(password.toCharArray());
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(SYM_ALGORITHM);
        SecretKey secretKey = keyFactory.generateSecret(pbeKeySpec);
        return secretKey;
    } catch (NoSuchAlgorithmException e) {
        throw new IllegalArgumentException("No such algorithm: " + e.getMessage());
    } catch (InvalidKeySpecException e) {
        throw new RuntimeException("Unexpected exception: ", e);
    }
}

From source file:org.eclipse.che.api.crypt.server.JCEEncryptTextService.java

private SecretKey generateSecret() throws NoSuchAlgorithmException, InvalidKeySpecException {
    final SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(this.secretKeyFactoryAlgorithm);
    final KeySpec keySpec = new PBEKeySpec(getMasterPassword(), this.salt, 65536, this.keySize);
    final SecretKey tempKey = keyFactory.generateSecret(keySpec);
    final SecretKey secret = new SecretKeySpec(tempKey.getEncoded(), this.cipher);
    return secret;
}

From source file:org.xdi.util.security.StringEncrypter.java

/**
 * Constructor specifying scheme and key
 * //  w  ww .j  a  v  a  2s  .  co m
 * @param encryptionScheme
 *            Encryption scheme to use
 * @param encryptionKey
 *            Encryption key to use
 * @throws EncryptionException
 */
public StringEncrypter(final String encryptionScheme, final String encryptionKey) throws EncryptionException {
    if (encryptionKey == null) {
        throw new IllegalArgumentException("encryption key was null");
    }
    if (encryptionKey.trim().length() < 24) {
        throw new IllegalArgumentException("encryption key was less than 24 characters");
    }

    try {
        final byte[] keyAsBytes = encryptionKey.getBytes(StringEncrypter.UNICODE_FORMAT);

        if (encryptionScheme.equalsIgnoreCase(StringEncrypter.DESEDE_ENCRYPTION_SCHEME)) {
            keySpec = new DESedeKeySpec(keyAsBytes);
        } else if (encryptionScheme.equalsIgnoreCase(StringEncrypter.DES_ENCRYPTION_SCHEME)) {
            keySpec = new DESKeySpec(keyAsBytes);
        } else {
            throw new IllegalArgumentException("Encryption scheme not supported: " + encryptionScheme);
        }

        keyFactory = SecretKeyFactory.getInstance(encryptionScheme);
        cipher = Cipher.getInstance(encryptionScheme);
    } catch (final InvalidKeyException e) {
        throw new EncryptionException(e);
    } catch (final UnsupportedEncodingException e) {
        throw new EncryptionException(e);
    } catch (final NoSuchAlgorithmException e) {
        throw new EncryptionException(e);
    } catch (final NoSuchPaddingException e) {
        throw new EncryptionException(e);
    }
}

From source file:org.hawk.core.security.FileBasedCredentialsStore.java

private String decrypt(String property) throws GeneralSecurityException, IOException {
    SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
    SecretKey key = keyFactory.generateSecret(new PBEKeySpec(encryptionKey));
    Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");
    pbeCipher.init(Cipher.DECRYPT_MODE, key, new PBEParameterSpec(salt, 20));
    return new String(pbeCipher.doFinal(base64Decode(property)), "UTF-8");
}