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.aurel.track.vc.bl.VersionControlBL.java

private static String encrypt(String clearText, char[] password) {
    // Create PBE parameter set
    PBEParameterSpec pbeParamSpec = new PBEParameterSpec(salt, count);
    byte[] ciphertext = { 0 };

    PBEKeySpec pbeKeySpec = new PBEKeySpec(password);
    try {//ww w .j av a2s  .com
        SecretKeyFactory 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(Cipher.ENCRYPT_MODE, pbeKey, pbeParamSpec);

        // Encrypt the cleartext
        ciphertext = pbeCipher.doFinal(clearText.getBytes());
    } catch (Exception e) {
        LOGGER.error(ExceptionUtils.getStackTrace(e));
    }
    return new String(Base64.encodeBase64String(ciphertext));
}

From source file:org.openintents.safe.CryptoHelper.java

/**
 * encrypt a string using a random session key
 *
 * @param plaintext//from  w  w w.  j  a va 2s .  com
 * @return encrypted String
 * @throws Exception
 * @author Peli
 */
public String encryptWithSessionKey(String plaintext) throws CryptoHelperException {
    if (debug) {
        Log.i(TAG, "Encrypt with session key");
    }
    status = false; // assume failure
    if (password == null) {
        String msg = "Must call setPassword before runing encrypt.";
        throw new CryptoHelperException(msg);
    }
    byte[] cipherSessionKey = {};
    byte[] ciphertext = {};

    // First create a session key
    SecretKey sessionKey = null;
    byte[] sessionKeyEncoded = null;
    String sessionKeyString = null;
    try {
        KeyGenerator keygen;
        keygen = KeyGenerator.getInstance("AES");
        keygen.init(256); // needs 96 bytes
        //keygen.init(128); // needs 64 bytes
        sessionKey = keygen.generateKey();
        sessionKeyEncoded = sessionKey.getEncoded();
        sessionKeyString = new String(sessionKeyEncoded);
    } catch (NoSuchAlgorithmException e) {
        Log.e(TAG, "generateMasterKey(): " + e.toString());
    }

    // Convert this to a Pbe key
    PBEKeySpec sessionPbeKeySpec = new PBEKeySpec(sessionKeyString.toCharArray());
    SecretKey sessionPbeKey = null;
    try {
        sessionPbeKey = keyFac.generateSecret(sessionPbeKeySpec);
    } catch (InvalidKeySpecException e) {
        Log.e(TAG, "setPassword(): " + e.toString());
    }

    // Encrypt the session key using the master key
    try {
        pbeCipher.init(Cipher.ENCRYPT_MODE, pbeKey, pbeParamSpec);
        cipherSessionKey = pbeCipher.doFinal(sessionKeyEncoded);
    } catch (IllegalBlockSizeException | BadPaddingException | InvalidAlgorithmParameterException
            | InvalidKeyException e) {
        Log.e(TAG, "encryptWithSessionKey(): " + e.toString());
    }

    // Now encrypt the text using the session key
    try {
        pbeCipher.init(Cipher.ENCRYPT_MODE, sessionPbeKey, pbeParamSpec);
        ciphertext = pbeCipher.doFinal(plaintext.getBytes());
        status = true;
    } catch (IllegalBlockSizeException | BadPaddingException | InvalidAlgorithmParameterException
            | InvalidKeyException e) {
        Log.e(TAG, "encryptWithSessionKey2(): " + e.toString());
    }

    String stringCipherVersion = "A";
    String stringCipherSessionKey = toHexString(cipherSessionKey);
    String stringCiphertext = toHexString(ciphertext);
    if (debug) {
        Log.i(TAG, "Length: " + stringCipherSessionKey.length() + ", " + stringCipherSessionKey);
    }

    StringBuilder sb = new StringBuilder(
            stringCipherVersion.length() + stringCipherSessionKey.length() + stringCiphertext.length());
    sb.append(stringCipherVersion);
    sb.append(stringCipherSessionKey);
    sb.append(stringCiphertext);
    return sb.toString();
}

From source file:org.fuin.utils4j.Utils4J.java

/**
 * Creates a cipher for encryption or decryption.
 * /*  www.j  av  a2s. c  om*/
 * @param algorithm
 *            PBE algorithm like "PBEWithMD5AndDES" or
 *            "PBEWithMD5AndTripleDES".
 * @param mode
 *            Encyrption or decyrption.
 * @param password
 *            Password.
 * @param salt
 *            Salt usable with algorithm.
 * @param count
 *            Iterations.
 * 
 * @return Ready initialized cipher.
 * 
 * @throws GeneralSecurityException
 *             Error creating the cipher.
 */
private static Cipher createCipher(final String algorithm, final int mode, final char[] password,
        final byte[] salt, final int count) throws GeneralSecurityException {

    final SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(algorithm);
    final PBEKeySpec keySpec = new PBEKeySpec(password);
    final SecretKey key = keyFactory.generateSecret(keySpec);
    final Cipher cipher = Cipher.getInstance(algorithm);
    final PBEParameterSpec params = new PBEParameterSpec(salt, count);
    cipher.init(mode, key, params);
    return cipher;

}

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  va2s. com*/
    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:org.openintents.safe.CryptoHelper.java

/**
 * unencrypt encrypted string previously encrypted with
 * encryptWithSessionKey()/* www  . j  a va  2 s  .  com*/
 *
 * @param ciphertext
 * @return decrypted String
 * @throws Exception
 * @author Peli
 */
public String decryptWithSessionKey(String ciphertext) throws CryptoHelperException {
    status = false; // assume failure
    if (password == null) {
        String msg = "Must call setPassword before running decrypt.";
        throw new CryptoHelperException(msg);
    }

    if ((ciphertext == null) || (ciphertext == "")) {
        return "";
    }
    String cipherVersion = null;
    String cipherSessionKey = null;

    // Split cipher into session key and text
    try {
        cipherVersion = ciphertext.substring(0, 1);
        if (cipherVersion.equals("A")) {
            cipherSessionKey = ciphertext.substring(1, 97); // 64 if init(128) had been chosen
            ciphertext = ciphertext.substring(97);
        } else {
            Log.e(TAG, "Unknown cipher version" + cipherVersion);
            return "";
        }
    } catch (IndexOutOfBoundsException e) {
        Log.e(TAG, "Invalid ciphertext (with session key)");
        return "";
    }

    // Decrypt the session key
    byte[] byteCipherSessionKey = hexStringToBytes(cipherSessionKey);
    byte[] byteSessionKey = {};

    try {
        pbeCipher.init(Cipher.DECRYPT_MODE, pbeKey, pbeParamSpec);
        byteSessionKey = pbeCipher.doFinal(byteCipherSessionKey);
        status = true;
    } catch (IllegalBlockSizeException | BadPaddingException | InvalidAlgorithmParameterException
            | InvalidKeyException e) {
        Log.e(TAG, "decrypt(): " + e.toString());
    }

    // Convert the session key into a Pbe key
    String stringSessionKey = new String(byteSessionKey);
    PBEKeySpec sessionPbeKeySpec = new PBEKeySpec(stringSessionKey.toCharArray());
    SecretKey sessionPbeKey = null;
    try {
        sessionPbeKey = keyFac.generateSecret(sessionPbeKeySpec);
    } catch (InvalidKeySpecException e) {
        Log.e(TAG, "setPassword(): " + e.toString());
    }

    // Use the session key to decrypt the text
    byte[] byteCiphertext = hexStringToBytes(ciphertext);
    byte[] plaintext = {};

    try {
        pbeCipher.init(Cipher.DECRYPT_MODE, sessionPbeKey, pbeParamSpec);
        plaintext = pbeCipher.doFinal(byteCiphertext);
        status = true;
    } catch (IllegalBlockSizeException | BadPaddingException | InvalidAlgorithmParameterException
            | InvalidKeyException e) {
        Log.e(TAG, "decrypt(): " + e.toString());
    }

    return new String(plaintext);
}

From source file:org.eclipse.orion.internal.server.core.metastore.SimpleMetaStoreMigration.java

private ISecurePreferences initSecurePreferences(File orionSecureStorageFile) {
    try {/*from   ww w . ja  v a  2 s.  c o  m*/
        ISecurePreferences storage = null;
        URL location = orionSecureStorageFile.toURI().toURL();
        if (location != null) {
            Map<String, Object> options = new HashMap<String, Object>();
            options.put(PROMPT_USER, Boolean.FALSE);
            String password = System.getProperty(ORION_STORAGE_PASSWORD, ""); //$NON-NLS-1$
            options.put(DEFAULT_PASSWORD, new PBEKeySpec(password.toCharArray()));
            try {
                storage = SecurePreferencesFactory.open(location, options);
            } catch (IOException e) {
                LogHelper.log(new Status(IStatus.ERROR, ServerConstants.PI_SERVER_CORE,
                        "Error initializing user storage location", e)); //$NON-NLS-1$
            }
        } else {
            LogHelper.log(new Status(IStatus.WARNING, ServerConstants.PI_SERVER_CORE,
                    "No instance location set. Storing user data in user home directory")); //$NON-NLS-1$
        }
        return storage;
    } catch (MalformedURLException e1) {
        LogHelper.log(e1);
    }
    return null;
}

From source file:com.aimluck.eip.mail.util.ALMailUtils.java

/**
 * ??????? ??PBEWithMD5AndDES/*from   w  w  w  .j a  v a2 s . c o m*/
 *
 * @param cipherMode
 *          Cipher.ENCRYPT_MODE ???? Cipher.DECRYPT_MODE
 * @param password
 * @param data
 * @return
 */
public static final byte[] cryptPBEWithMD5AndDES(int cipherMode, char[] password, byte[] data) {
    byte[] ciphertext = 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);
    try {
        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(cipherMode, pbeKey, pbeParamSpec);

        // Encrypt/Decrypt the cleartext
        ciphertext = pbeCipher.doFinal(data);
    } catch (Exception e) {
        logger.error("ALMailUtils.cryptPBEWithMD5AndDES", e);
        return null;
    }
    return ciphertext;
}

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 .ja  va 2s. co m
        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:csh.cryptonite.Cryptonite.java

public static String encrypt(String value, Context context) throws RuntimeException {

    try {/*  w w w  . j  ava  2  s. co  m*/
        final byte[] bytes = value != null ? value.getBytes("utf-8") : new byte[0];
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
        SecretKey key = keyFactory.generateSecret(new PBEKeySpec(jniFullPw().toCharArray()));
        Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");
        pbeCipher.init(Cipher.ENCRYPT_MODE, key,
                new PBEParameterSpec(Settings.Secure
                        .getString(context.getContentResolver(), Settings.Secure.ANDROID_ID).getBytes("utf-8"),
                        20));
        return new String(Base64.encode(pbeCipher.doFinal(bytes), Base64.NO_WRAP), "utf-8");

    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:csh.cryptonite.Cryptonite.java

public static String decrypt(String value, Context context) throws RuntimeException {
    try {//from   w w w  .j a  va  2  s  .c  o  m
        final byte[] bytes = value != null ? Base64.decode(value, Base64.DEFAULT) : new byte[0];
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
        SecretKey key = keyFactory.generateSecret(new PBEKeySpec(jniFullPw().toCharArray()));
        Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");
        pbeCipher.init(Cipher.DECRYPT_MODE, key,
                new PBEParameterSpec(Settings.Secure
                        .getString(context.getContentResolver(), Settings.Secure.ANDROID_ID).getBytes("utf-8"),
                        20));
        return new String(pbeCipher.doFinal(bytes), "utf-8");

    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}