ECBUtil.java 2.74 KB
package com.yoho.unions.utils;

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

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

/**
 * Created by zhengwen.ge on 2017/9/19.
 */
public class ECBUtil {

    public static String SECRETKEY = "yoho9646abcdefgh";

    public static final String KEY_ALGORITHM = "AES";
    public static final String ECB_CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding";
    public static final String CBC_CIPHER_ALGORITHM = "AES/CBC/PKCS5Padding";
    public static final String PLAIN_TEXT = "MANUTD is the greatest club in the world";

    public static String encrypt(String key, String data)
            throws NoSuchAlgorithmException, NoSuchPaddingException,
            InvalidKeyException, InvalidAlgorithmParameterException,
            IllegalBlockSizeException, BadPaddingException, IOException {

        byte[] dataBytes = data.getBytes();
        byte[] keyBytes = key.getBytes();

        // 必须为 128bit或256bit,即 16字节或32字节
        if (keyBytes.length != 16 && keyBytes.length != 32) {
            return "";
        }

        Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
        SecretKeySpec k = new SecretKeySpec(keyBytes, KEY_ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, k);
        byte[] bytes = cipher.doFinal(dataBytes);

        return Base64.encodeBase64String(cipher.doFinal(dataBytes));

    }

    public static String decrypt(String key, String data) {

        data = data.replace(" ", "+");
//		System.out.println("字串1是:" + data);
        byte[] keyBytes = key.getBytes();
        byte[] dataBytes = Base64.decodeBase64(data);

        // 必须为 128bit或256bit,即 16字节或32字节
        if (keyBytes.length != 16 && keyBytes.length != 32) {
            return data;
        }
        try {
            Cipher cipher = Cipher.getInstance("AES");//
            SecretKeySpec k = new SecretKeySpec(keyBytes, "AES");
            cipher.init(Cipher.DECRYPT_MODE, k);

            return new String(cipher.doFinal(dataBytes)).trim();
        } catch (Exception e) {
            e.printStackTrace();

            try{
                Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding");//
                SecretKeySpec k = new SecretKeySpec(keyBytes, "AES");
                cipher.init(Cipher.DECRYPT_MODE, k);

                return new String(cipher.doFinal(dataBytes)).trim();
            }catch(Exception e1){
                return data;
            }
        }
    }
}