com.aqnote.shared.cryptology.symmetric.Blowfish.java Source code

Java tutorial

Introduction

Here is the source code for com.aqnote.shared.cryptology.symmetric.Blowfish.java

Source

/*
 * Copyright 2013-2023 "Peng Li"<aqnote@qq.com> Licensed under the AQNote License, Version 1.0 (the "License");
 * you may not use this file except in compliance with the License. You may obtain a copy of the License at
 * http://www.aqnote.com/licenses/LICENSE-1.0 Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
 * either express or implied. See the License for the specific language governing permissions and limitations under the
 * License.
 */
package com.aqnote.shared.cryptology.symmetric;

import static com.aqnote.shared.cryptology.cert.constant.BCConstant.JCE_PROVIDER;

import java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.spec.AlgorithmParameterSpec;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang.StringUtils;

import com.aqnote.shared.cryptology.AQProviderUtil;

/**
 * Blowfish.java??
 * 
 * <pre>
 * Blowfish? Bruce Schneier ? 
 * ? 32 ? 448 ? 8 ????
 * (Blowfish/CBC/PKCS5Padding)Blowfish?CBC?PKCS5Padding??8 ?
 * </pre>
 * 
 * @author "Peng Li"<aqnote@qq.com> May 8, 2012 2:08:19 PM
 */
public class Blowfish {

    private static final String PROVIDER_NAME = JCE_PROVIDER;
    private static final String DEFAULT_CHARSET = "UTF-8";
    private static final String CIPHER_NAME = "Blowfish/CBC/PKCS5Padding";
    private static final String ALGORITHM = "Blowfish";

    private Key keySpec = null;
    private AlgorithmParameterSpec paramSpec = null;
    private Cipher encryptCipher = null;
    private Cipher decryptCipher = null;

    static {
        AQProviderUtil.addBCProvider();
    }

    public Blowfish(String keySpec, byte[] paramSpec) {
        this.keySpec = new SecretKeySpec(keySpec.getBytes(), ALGORITHM);
        this.paramSpec = new IvParameterSpec(paramSpec);
        initBlowfish();
    }

    private void initBlowfish() {
        encryptCipher = getCipher(CIPHER_NAME, PROVIDER_NAME);
        decryptCipher = getCipher(CIPHER_NAME, PROVIDER_NAME);
        initCipher(encryptCipher, Cipher.ENCRYPT_MODE, keySpec, paramSpec);
        initCipher(decryptCipher, Cipher.DECRYPT_MODE, keySpec, paramSpec);
    }

    /**
     * 
     * 
     * @param name cipher name
     * @param provider provider name
     * @return Cipher
     */
    private Cipher getCipher(String name, String provider) {
        Cipher cipher = null;
        try {
            cipher = Cipher.getInstance(name, provider);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchProviderException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        }
        return cipher;
    }

    /**
     * ?
     * 
     * @param cipher Cipher
     * @param opmode operation mode (ENCRYPT_MODE?DECRYPT_MODE?WRAP_MODE  UNWRAP_MODE)
     * @param key Key
     * @param iv AlgorithmParameterSpec
     */
    private void initCipher(Cipher cipher, int opmode, Key key, AlgorithmParameterSpec paramSpec) {
        try {
            cipher.init(opmode, key, paramSpec);
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (InvalidAlgorithmParameterException e) {
            e.printStackTrace();
        }
    }

    /**
     * ?CipherdoFinal?reset ???
     * 
     * @param b ?
     * @return ?
     * @throws IllegalBlockSizeException
     * @throws BadPaddingException
     */
    public synchronized byte[] encrypt(byte[] b) throws IllegalBlockSizeException, BadPaddingException {
        byte[] buffer = null;
        initCipher(encryptCipher, Cipher.ENCRYPT_MODE, keySpec, paramSpec);
        buffer = encryptCipher.doFinal(b);
        return buffer;
    }

    /**
     * ?CipherdoFinal?reset ???
     * 
     * @param b ?
     * @return ?
     * @throws IllegalBlockSizeException
     * @throws BadPaddingException
     */
    public synchronized byte[] decrypt(byte[] b) throws IllegalBlockSizeException, BadPaddingException {
        byte[] buffer = null;
        initCipher(decryptCipher, Cipher.DECRYPT_MODE, keySpec, paramSpec);
        buffer = decryptCipher.doFinal(b);
        return buffer;
    }

    /**
     * @param str ?
     * @return String ?
     */
    public String encrypt(String str) {
        String result = null;

        if (!StringUtils.isEmpty(str)) {
            try {
                byte[] src = str.getBytes(DEFAULT_CHARSET);
                byte[] enc = encrypt(src);
                result = Base64.encodeBase64String(enc);
            } catch (IllegalBlockSizeException e) {
                throw new RuntimeException(e);
            } catch (BadPaddingException e) {
                throw new RuntimeException(e);
            } catch (UnsupportedEncodingException e) {
                throw new RuntimeException(e);
            }
        }
        return result;
    }

    /**
     * @param str ?
     * @return String ?
     */
    public String decrypt(String str) {
        String result = null;

        if (!StringUtils.isEmpty(str)) {
            try {
                byte[] src = Base64.decodeBase64(str);
                byte[] dec = decrypt(src);
                result = new String(dec, DEFAULT_CHARSET);
            } catch (IllegalBlockSizeException e) {
                throw new RuntimeException(e);
            } catch (BadPaddingException e) {
                throw new RuntimeException(e);
            } catch (UnsupportedEncodingException e) {
                throw new RuntimeException(e);
            }
        }
        return result;
    }

}