package com.zving.booklib.resource.util;

import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
import org.bouncycastle.util.encoders.Base64;

/*
 * 加密工具类
 */
public class ASEUtil {

    private static final String PASS_NEED = "1qaz2wsx3edc4rfv";
    private static SecretKeySpec key;
    private static Cipher encCipher = null;
    private static Cipher decCipher = null;

    static {
        byte[] enCodeFormat = Arrays.copyOf(PASS_NEED.getBytes(), 16);
        key = new SecretKeySpec(enCodeFormat, "AES");
        try {
            encCipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            encCipher.init(Cipher.ENCRYPT_MODE, key);

            decCipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            decCipher.init(Cipher.DECRYPT_MODE, key);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        }
    }

    public static String encryData(String plaintData) throws IllegalBlockSizeException, BadPaddingException {
        byte result[] = encCipher.doFinal(plaintData.getBytes());
        return new String(Base64.encode(result));
    }

    public static String decryData(String encData) throws Exception {
        byte result[] = decCipher.doFinal(Base64.decode(encData.getBytes()));
        return new String(result);
    }

    public static byte[] encryData(byte[] plaintData) throws IllegalBlockSizeException, BadPaddingException {
        byte result[] = encCipher.doFinal(plaintData);
        return result;
    }

    public static byte[] decryData(byte[] encData) throws IllegalBlockSizeException, BadPaddingException {
        byte result[] = decCipher.doFinal(encData);
        return result;
    }

}

 

posted on 2018-08-02 11:09  四叶草的眼泪  阅读(213)  评论(0编辑  收藏  举报