com.anteam.demo.codec.cipher.symmetric.DESedeCoder.java Source code

Java tutorial

Introduction

Here is the source code for com.anteam.demo.codec.cipher.symmetric.DESedeCoder.java

Source

/*
 * Project: root
 * 
 * File Created at 2014-05-22
 * 
 * Copyright 2012 Greenline.com Corporation Limited.
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of
 * Greenline Company. ("Confidential Information").  You shall not
 * disclose such Confidential Information and shall use it only in
 * accordance with the terms of the license agreement you entered into
 * with Greenline.com.
 */
package com.anteam.demo.codec.cipher.symmetric;

import com.anteam.demo.codec.common.StringUtil;
import com.anteam.demo.codec.core.BasicCoder;
import com.anteam.demo.codec.core.EncryptAlgorithm;

import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.EncoderException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import javax.crypto.spec.IvParameterSpec;
import java.security.InvalidKeyException;

/**
 * @author bash
 * @version V1.0
 * @type DESedeCoder
 * @desc
 * @date 2014-05-22
 */
public class DESedeCoder implements BasicCoder {

    /**
     * Logger
     */
    private static final Logger LOG = LoggerFactory.getLogger(DESedeCoder.class);

    /**
     * 
     */
    public static final EncryptAlgorithm ALGORITHM = EncryptAlgorithm.DESEDE;

    /**
     * ??
     */
    public static final String ALGORITHM_NAME = ALGORITHM.algorithmName();

    /**
     * cipher??
     */
    public static final String CIPHER_NAME = ALGORITHM.cipherName();

    /**
     * IvParameterSpec
     */
    private static final IvParameterSpec IvParameters = new IvParameterSpec(
            new byte[] { 0x01, 0x02, 0x03, 0x04, 0x0F, 0x0E, 0x0D, 0x0C });

    /**
     * key
     */
    private byte[] key = "anteam.good.luck.1234567890\t\r\n~!@#$%^&*()_+".getBytes();

    private DESedeKeySpec keySpec;

    /**
     * 
     */
    public DESedeCoder() {
        super();
        try {
            keySpec = new DESedeKeySpec(key);
        } catch (InvalidKeyException e) {
            LOG.error("DESedeKeySpec:" + key, e);
        }
    }

    /**
     * ?
     */
    public DESedeCoder(byte[] key) {
        super();
        this.setKey(key);
    }

    /**
     * Encodes a byte array and return the encoded data as a byte array.
     *
     * @param source Data to be encoded
     * @return ?byte.source, null
     * @throws org.apache.commons.codec.EncoderException thrown if the Encoder encounters a failure condition during the encoding process.
     */
    @Override
    public byte[] encode(byte[] source) throws EncoderException {
        if (source == null) {
            return null;
        }
        try {

            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM_NAME);
            SecretKey secretKey = keyFactory.generateSecret(keySpec);
            Cipher cipher = Cipher.getInstance(CIPHER_NAME);
            cipher.init(Cipher.ENCRYPT_MODE, secretKey, IvParameters);
            return cipher.doFinal(source);

        } catch (Exception e) {
            LOG.error(":" + key + ":" + source, e);
            throw new EncoderException(":" + key + ":" + source, e);
        }
    }

    /**
     * Decodes a byte array and returns the results as a byte array.
     *
     * @param source A byte array which has been encoded with the appropriate encoder
     * @return ?byte.source, null
     * @throws org.apache.commons.codec.DecoderException A decoder exception is thrown if a Decoder encounters a failure condition during the decode process.
     */
    @Override
    public byte[] decode(byte[] source) throws DecoderException {
        if (source == null) {
            return null;
        }
        try {
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM_NAME);
            SecretKey secretKey = keyFactory.generateSecret(keySpec);
            Cipher cipher = Cipher.getInstance(CIPHER_NAME);
            cipher.init(Cipher.DECRYPT_MODE, secretKey, IvParameters);
            return cipher.doFinal(source);
        } catch (Exception e) {
            LOG.error(":" + key + ":" + source, e);
            throw new DecoderException(":" + key + ":" + source, e);
        }
    }

    /**
     * Encodes a String and returns a String.
     *
     * @param source the String to encode
     * @return ?String.source, null.?StringUtil.bytesToString{@link StringUtil}?String.
     * @throws org.apache.commons.codec.EncoderException thrown if there is an error condition during the encoding process.
     */
    @Override
    public String encode(String source) throws EncoderException {
        if (source == null) {
            return null;
        }
        byte[] encryptedByte = this.encode(source.getBytes());
        if (encryptedByte != null) {
            return StringUtil.bytesToString(encryptedByte);
        }
        return null;
    }

    /**
     * Decodes a String and returns a String.
     *
     * @param source the String to decode
     * @return ?String.source, null.??String.
     * @throws org.apache.commons.codec.DecoderException thrown if there is an error condition during the Encoding process.
     */
    @Override
    public String decode(String source) throws DecoderException {
        if (source == null) {
            return null;
        }
        //?StringUtilToByte.
        byte[] plainBytes = StringUtil.stringToBytes(source);
        byte[] encryptedByte = this.decode(plainBytes);
        if (encryptedByte != null) {
            return new String(encryptedByte);
        }
        return null;
    }

    /**
     * ?.Encodes an "Object" and returns the encoded content as an Object. The Objects here may just be
     * <code>byte[]</code> or <code>String</code>s depending on the implementation used.
     *
     * @param source An object to encode
     * @return An "encoded" Object
     * @throws org.apache.commons.codec.EncoderException An encoder exception is thrown if the encoder experiences a failure condition during the encoding
     *                                                   process.
     */
    @Override
    @SuppressWarnings("NotImpl")
    public Object encode(Object source) throws EncoderException {
        if (source == null) {
            return null;
        }
        if (source instanceof byte[]) {
            return this.encode((byte[]) source);
        } else if (source instanceof String) {
            return this.encode((String) source);
        }
        return null;
    }

    /**
     * ?.Decodes an "encoded" Object and returns a "decoded" Object. Note that the implementation of this interface will
     * try to cast the Object parameter to the specific type expected by a particular Decoder implementation. If a
     * {@link ClassCastException} occurs this decode method will throw a DecoderException.
     *
     * @param source the object to decode
     * @return a 'decoded" object
     * @throws org.apache.commons.codec.DecoderException a decoder exception can be thrown for any number of reasons. Some good candidates are that the
     *                                                   parameter passed to this method is null, a param cannot be cast to the appropriate type for a
     *                                                   specific encoder.
     */
    @Override
    @SuppressWarnings("NotImpl")
    public Object decode(Object source) throws DecoderException {
        if (source == null) {
            return null;
        }
        if (source instanceof byte[]) {
            return this.decode((byte[]) source);
        } else if (source instanceof String) {
            return this.decode((String) source);
        }
        return null;
    }

    public byte[] getKey() {
        return key;
    }

    /**
     * DESkey
     *
     * @param key
     */
    public void setKey(byte[] key) {
        if (key != null && key.length >= BasicCoder.MIN_KEY_LENGTH) {
            this.key = key;
        }
        try {
            keySpec = new DESedeKeySpec(this.key);
        } catch (InvalidKeyException e) {
            LOG.error("DESedeKeySpec:" + this.key, e);
        }
    }
}