CipherProvider.java Source code

Java tutorial

Introduction

Here is the source code for CipherProvider.java

Source

/*
This softtware use BSD licence (http://opensource.org/licenses/BSD-3-Clause)
    
Copyright (c) 2013, Martin Lebeda
All rights reserved.
    
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
    
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
    
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
    
3. Neither the name of the Martin Lebeda nor the names of its contributors may
be used to endorse or promote products derived from this software without
specific prior written permission.
    
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

import java.security.spec.AlgorithmParameterSpec;
import java.security.spec.KeySpec;
import java.util.Arrays;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;

/**
 * @author <a href="mailto:martin.lebeda@gmail.com">Martin Lebeda</a>
 *         Date: 15.9.13
 */
class CipherProvider {

    private Cipher encryptCipher = null;
    private Cipher decryptCipher = null;

    private String password = null;

    private static String CIPHER_TYPE = "AES"; // "Blowfish"; // "AES"

    /**
     * Create cipher for encrypt or decrypt backup content
     *
     * @param passwd passwd for encryption
     * @param mode   encrypt/decrypt mode
     *
     * @return instance of cipher
     */
    private static Cipher getCipher(final String passwd, final int mode) {
        /* Derive the key, given password and salt. */
        Cipher cipher = null;
        try {
            SecretKeyFactory factory = null;
            factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
            String salt = "slNadZlato#%^^&(&(5?@#5166?1561?#%^^*^&54431"; // only pseudorandom salt
            KeySpec spec = new PBEKeySpec(passwd.toCharArray(), salt.getBytes(), 65536, 128);
            SecretKey tmp = factory.generateSecret(spec);
            SecretKey secret = new SecretKeySpec(tmp.getEncoded(), CIPHER_TYPE);

            // initialization vector
            byte[] iv = Arrays.copyOfRange(DigestUtils.md5(passwd), 0, 16);
            AlgorithmParameterSpec paramSpec = new IvParameterSpec(iv);

            // Cipher for encryption
            cipher = Cipher.getInstance(CIPHER_TYPE + "/CBC/PKCS5Padding");
            cipher.init(mode, secret, paramSpec);
        } catch (Exception e) {
            e.printStackTrace(); //Todo implementovat
        }
        return cipher;
    }

    /**
     * Cipher setuped for encryption
     *
     * @return Cipher setuped for encryption
     */
    Cipher getEncryptCipher() {
        if (StringUtils.isNotBlank(password) && (encryptCipher == null)) {
            encryptCipher = getCipher(password, Cipher.ENCRYPT_MODE);
        }
        return encryptCipher;
    }

    /**
     * Cipher setuped for decryption
     *
     * @return Cipher setuped for decryption
     */
    Cipher getDecryptCipher() {
        if (StringUtils.isNotBlank(password) && (decryptCipher == null)) {
            decryptCipher = getCipher(password, Cipher.DECRYPT_MODE);
        }
        return decryptCipher;
    }

    String getPassword() {
        return password;
    }

    /**
     * Is encryption enabled?
     *
     * @return true if password is not empty
     */
    boolean isEncryptEnabled() {
        return StringUtils.isNotBlank(password);
    }

    /**
     * Set password and clear old encrypt and decrypt initialized engine.
     *
     * @param password new password, can by null or empty to disable
     */
    void setPassword(String password) {
        this.password = password;
        encryptCipher = null;
        decryptCipher = null;
    }
}