Example usage for javax.crypto.spec PBEKeySpec PBEKeySpec

List of usage examples for javax.crypto.spec PBEKeySpec PBEKeySpec

Introduction

In this page you can find the example usage for javax.crypto.spec PBEKeySpec PBEKeySpec.

Prototype

public PBEKeySpec(char[] password) 

Source Link

Document

Constructor that takes a password.

Usage

From source file:com.nextep.designer.core.services.impl.RepositoryService.java

public RepositoryService() {
    pbeParamSpec = new PBEParameterSpec(salt, iterations);
    pbeKeySpec = new PBEKeySpec(encryptionPassword.toCharArray());
    try {/*  www.j a va 2  s.c o m*/
        SecretKeyFactory factory = SecretKeyFactory.getInstance(ALGORITHM);
        key = factory.generateSecret(pbeKeySpec);
    } catch (NoSuchAlgorithmException e) {
        LOGGER.error(CoreMessages.getString("repositoryService.encryptionNotFound"), e); //$NON-NLS-1$
    } catch (InvalidKeySpecException e) {
        LOGGER.error(CoreMessages.getString("repositoryService.encryptionKeyFail"), e); //$NON-NLS-1$
    }
}

From source file:org.apache.nifi.processors.standard.util.PasswordBasedEncryptor.java

public PasswordBasedEncryptor(final String algorithm, final String providerName, final char[] password,
        KeyDerivationFunction kdf) {/*from   ww  w  .j  a  va2s .c  o  m*/
    super();
    try {
        // initialize cipher
        this.cipher = Cipher.getInstance(algorithm, providerName);
        this.kdf = kdf;

        if (isOpenSSLKDF()) {
            this.saltSize = OPENSSL_EVP_SALT_SIZE;
            this.iterationsCount = OPENSSL_EVP_KDF_ITERATIONS;
        } else {
            int algorithmBlockSize = cipher.getBlockSize();
            this.saltSize = (algorithmBlockSize > 0) ? algorithmBlockSize : DEFAULT_SALT_SIZE;
        }

        // initialize SecretKey from password
        final PBEKeySpec pbeKeySpec = new PBEKeySpec(password);
        final SecretKeyFactory factory = SecretKeyFactory.getInstance(algorithm, providerName);
        this.secretKey = factory.generateSecret(pbeKeySpec);
    } catch (Exception e) {
        throw new ProcessException(e);
    }
}

From source file:org.runway.utils.StringEncryptDecryptUtil.java

public static String decrypt(String value) throws RunwaySecurityException {
    String result = null;//  w w w.j a v a  2s  .  co m
    SecretKeyFactory keyFactory;

    try {

        keyFactory = SecretKeyFactory.getInstance(ALGORITHM);
        SecretKey key = keyFactory.generateSecret(new PBEKeySpec(PASSWORD));
        Cipher pbeCipher = Cipher.getInstance(ALGORITHM);
        pbeCipher.init(Cipher.DECRYPT_MODE, key, new PBEParameterSpec(SALT, 20));
        result = new String(pbeCipher.doFinal(base64Decode(value)));

    } catch (NoSuchAlgorithmException e) {
        throw new RunwaySecurityException(e);
    } catch (InvalidKeySpecException e) {
        throw new RunwaySecurityException(e);
    } catch (NoSuchPaddingException e) {
        throw new RunwaySecurityException(e);
    } catch (InvalidKeyException e) {
        throw new RunwaySecurityException(e);
    } catch (InvalidAlgorithmParameterException e) {
        throw new RunwaySecurityException(e);
    } catch (IllegalBlockSizeException e) {
        throw new RunwaySecurityException(e);
    } catch (BadPaddingException e) {
        throw new RunwaySecurityException(e);
    } catch (IOException e) {
        throw new RunwaySecurityException(e);
    }

    return result;
}

From source file:JavaTron.JTP.java

/**
 * Encrypts a string/*  w w w  . j  ava  2  s  . c om*/
 * @param property
 * @return An encrypted string
 */
public static String encrypt(String property) {
    String p = new String();
    try {
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
        SecretKey key = keyFactory.generateSecret(new PBEKeySpec(PASSWORD));
        Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");
        pbeCipher.init(Cipher.ENCRYPT_MODE, key, new PBEParameterSpec(SALT, 20));
        p = base64Encode(pbeCipher.doFinal(property.getBytes()));
    } catch (Exception e) {
        e.printStackTrace();
    }
    return p;
}

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

private String decrypt(final String property) {
    String decryptedPassword = null;
    try {/*from w  w  w . jav  a 2  s.c om*/
        final SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
        final SecretKey key = keyFactory.generateSecret(new PBEKeySpec(PASSWORD));
        final Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");
        pbeCipher.init(Cipher.DECRYPT_MODE, key, new PBEParameterSpec(SALT, 20));
        decryptedPassword = new String(pbeCipher.doFinal(base64Decode(property)), "UTF-8");
    } catch (final Exception ex) {
        Log.out.error(ex.getMessage(), ex);
    }

    return decryptedPassword;

}

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

/**
 * PKCS #8 encode and encrypt a private key.
 *
 * @return The encrypted encoding/*from w  w  w. j  a v 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.asquareb.kaaval.MachineKey.java

/**
 * Method to encrypt a string. Accepts the string to be encrypted and the
 * name of the file to store the key vale which can be used for decryption
 *//*from  ww w.java  2s. co m*/
public static String encrypt(String property, String app) throws IOException, KaavalException {

    InetAddress ip = null;
    String ipAddress = null;
    ObjectOutputStream os = null;
    NetworkInterface macAddress = null;
    byte[] macId = null;
    Cipher pbeCipher = null;
    Random rand = new Random();
    rand.nextBytes(salt);
    try {
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
        SecretKey key = keyFactory.generateSecret(new PBEKeySpec(password));
        ip = InetAddress.getLocalHost();
        ipAddress = ip.getHostAddress();
        macAddress = NetworkInterface.getByInetAddress(ip);
        macId = macAddress.getHardwareAddress();
        MachineKey mKey = new MachineKey();
        mKey.api = ipAddress;
        mKey.macad = new String(macId);
        mKey.yek = key;
        mKey.tlas = salt;
        mKey.eti = rand.nextInt(1000);
        os = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(app)));
        os.writeObject(mKey);
        os.close();
        pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");
        pbeCipher.init(Cipher.ENCRYPT_MODE, key, new PBEParameterSpec(salt, mKey.eti));
        return base64Encode(pbeCipher.doFinal(property.getBytes()));
    } catch (IOException e) {
        throw new KaavalException(1, "Error in key file during encryption", e);
    } catch (Exception e) {
        throw new KaavalException(2, "Errors during encryption", e);
    } finally {
        if (os != null)
            os.close();
    }
}

From source file:org.kawanfw.commons.util.convert.Pbe.java

/**
 * Encrypt or decrypt a string using a password
 * //from ww  w  .  j  av  a  2  s  .  c  o m
 * @param mode
 *            Cipher.ENCRYPT_MODE or Cipher.DECRYPT_MODE
 * @param in
 *            the string to encrypt or Decrypt. if to decrypt: string must
 *            be Hex encoded
 * @param password
 *            the password to use
 * @return if Cipher.ENCRYPT_MODE: the encrypted string in hexadecimal if
 *         Cipher.DECRYPT_MODE: the decrypted string in clear readable
 *         format
 * 
 * @throws Exception
 */
private String cipher(int mode, String in, char[] password) throws Exception {
    if (mode != Cipher.ENCRYPT_MODE && mode != Cipher.DECRYPT_MODE) {
        throw new IllegalArgumentException("mode is not Cipher.ENCRYPT_MODE or Cipher.DECRYPT_MODE!");
    }

    if (in == null) {
        throw new IllegalArgumentException("in string can not be null!");
    }

    if (password == null) {
        throw new IllegalArgumentException("password can not be null!");
    }

    PBEKeySpec pbeKeySpec;
    PBEParameterSpec pbeParamSpec;
    SecretKeyFactory keyFac;

    // Salt
    byte[] salt = { (byte) 0xc7, (byte) 0x73, (byte) 0x21, (byte) 0x8c, (byte) 0x7e, (byte) 0xc8, (byte) 0xee,
            (byte) 0x99 };

    // Iteration count
    int count = 20;

    // Create PBE parameter set
    pbeParamSpec = new PBEParameterSpec(salt, count);

    pbeKeySpec = new PBEKeySpec(password);
    keyFac = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
    SecretKey pbeKey = keyFac.generateSecret(pbeKeySpec);

    // Create PBE Cipher
    Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");

    // Initialize PBE Cipher with key and parameters
    pbeCipher.init(mode, pbeKey, pbeParamSpec);

    // Our cleartext
    byte[] inText = null;

    if (mode == Cipher.ENCRYPT_MODE) {
        inText = in.getBytes();
    } else {
        inText = CodecHex.decodeHex(in.toCharArray());
    }

    // Encrypt the cleartext
    byte[] ciphertext = pbeCipher.doFinal(inText);

    if (mode == Cipher.ENCRYPT_MODE) {
        return new String(CodecHex.encodeHex(ciphertext));
    } else {
        return new String(ciphertext);
    }
}

From source file:org.zuinnote.flink.office.common.FlinkKeyStoreManager.java

/**
 * Sets the password in the currently openend keystore. Do not forget to store it afterwards
 * /* w ww.ja va  2s  . c  om*/
 * @param alias
 * @param password to store 
 * @param passwordPassword password for encrypting password. You can use the same as the keystore password
 * @throws NoSuchAlgorithmException 
 * @throws InvalidKeySpecException 
 * @throws KeyStoreException 
 */

public void setPassword(String alias, String password, String passwordPassword)
        throws NoSuchAlgorithmException, InvalidKeySpecException, KeyStoreException {
    SecretKeyFactory skf = SecretKeyFactory.getInstance("PBE");
    SecretKey pSecret = skf.generateSecret(new PBEKeySpec(password.toCharArray()));
    KeyStore.PasswordProtection kspp = new KeyStore.PasswordProtection(passwordPassword.toCharArray());
    this.keystore.setEntry(alias, new KeyStore.SecretKeyEntry(pSecret), kspp);
}

From source file:de.alpharogroup.crypto.simple.SimpleDecryptor.java

/**
 * Initializes the {@link SimpleDecryptor} object.
 *
 * @throws InvalidAlgorithmParameterException
 *             is thrown if initialization of the cypher object fails.
 * @throws NoSuchPaddingException/*  w  ww  .  ja  v  a  2s  . c o m*/
 *             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()) {
        KeySpec keySpec = null;
        if (this.getPrivateKey() != null) {
            keySpec = new PBEKeySpec(this.getPrivateKey().toCharArray());
        }
        if (this.getPrivateKey() == null) {
            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.DECRYPT_MODE, key, paramSpec);
        initialized = true;
    }
}