1. 程式人生 > >java AES128加密壓縮 模擬傳輸資料

java AES128加密壓縮 模擬傳輸資料

package test;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.zip.Deflater;
import java.util.zip.Inflater;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

/**
 * 
 * @author andy.wang
 * @時間 2016-4-21
 */
public class AES128 {
	private static final Logger log = LogManager
			.getLogger(AES128.class);
	/**
	 * 祕鑰長度
	 */
	private static final int SECURE_KEY_LENGTH = 16;
	/**
	 * 採用AES128解密
	 * 
	 * @param data
	 * @param secureKey
	 * @return
	 * @throws Exception
	 *             ,Exception
	 * @throws Exception
	 */
	public static byte[] decrypt(byte[] data, String secureKey)
			throws Exception {
		if (data == null || data.length == 0) {
			return data;
		}

		// 獲得密匙資料
		byte[] rawKeyData = getAESKey(secureKey); // secureKey.getBytes();
		// 從原始密匙資料建立一個KeySpec物件
		SecretKeySpec key = new SecretKeySpec(rawKeyData, "AES");
		// Cipher物件實際完成解密操作
		Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
		byte[] iv = new byte[SECURE_KEY_LENGTH];
		// 用密匙初始化Cipher物件
		cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(iv));
		try {
			return cipher.doFinal(data);
		} catch (Exception e) {
//			log.error(e.getMessage());
//			throw new Exception("ILLEGAL_SIGNATURE");
			e.printStackTrace();
			throw new Exception(e);
		}

	}

	public static byte[] getAESKey(String key)
			throws UnsupportedEncodingException {
		byte[] keyBytes;
		keyBytes = key.getBytes("UTF-8");
		// Use the first 16 bytes (or even less if key is shorter)
		byte[] keyBytes16 = new byte[SECURE_KEY_LENGTH];
		System.arraycopy(keyBytes, 0, keyBytes16, 0,
				Math.min(keyBytes.length, SECURE_KEY_LENGTH));
		return keyBytes16;
	}

	/**
	 * 採用AES128加密
	 * 
	 * @param text
	 * @param k
	 * @return
	 */
	public static byte[] encrypt(byte[] data, String secureKey)
			throws Exception {
		if (data == null || data.length == 0) {
			return data;
		}

		// 獲得密匙資料
		byte[] rawKeyData = getAESKey(secureKey);
		// 從原始密匙資料建立KeySpec物件
		SecretKeySpec key = new SecretKeySpec(rawKeyData, "AES");
		// Cipher物件實際完成加密操作
		Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
		byte[] iv = new byte[SECURE_KEY_LENGTH];
		// 用密匙初始化Cipher物件
		cipher.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(iv));
		// 正式執行加密操作

		return cipher.doFinal(data);
	}

	/**
	 * zlib解壓
	 * 
	 * @param input
	 * @return
	 */
	public static byte[] unzip(byte[] input) throws Exception {
		if (input == null || input.length == 0) {
			return input;
		}

		byte[] out = null;
		ByteArrayOutputStream bao = null;
		Inflater decompresser = new Inflater();
		try {
			bao = new ByteArrayOutputStream(input.length);
			decompresser.setInput(input);
			byte[] buf = new byte[1024];
			int len = 0;
			while (!(decompresser.finished() || decompresser.needsInput())) {
				len = decompresser.inflate(buf);
				if (len == 0) {
					break;
				}
				bao.write(buf, 0, len);
			}
			out = bao.toByteArray();
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception("ILLEGAL_COMPRESSION");
		} finally {
			try {
				if (null != bao) {
					bao.close();
				}
				decompresser.end();
			} catch (IOException e) {
				log.error("close unzip stream error:" + e.getMessage());
			}
		}
		return out;

	}

	/**
	 * zlib壓縮
	 * 
	 * @param input
	 * @return
	 */
	public static byte[] zip(byte[] input) throws Exception {
		if (input == null || input.length == 0) {
			return input;
		}

		byte[] out = null;
		ByteArrayOutputStream bao = null;
		Deflater compresser = new Deflater();
		try {
			compresser.setInput(input);
			compresser.finish();
			bao = new ByteArrayOutputStream(input.length);
			byte[] buf = new byte[1024];
			int len;
			while (!compresser.finished()) {
				len = compresser.deflate(buf);
				bao.write(buf, 0, len);
			}
			out = bao.toByteArray();
		} finally {
			try {
				if (null != bao) {
					bao.close();
				}
				compresser.end();
			} catch (IOException e) {
				log.error("close zip stream error:" + e.getMessage());
			}
		}
		return out;
	}
	
	public static void main(String[] args) throws Exception {
		String test = "hello 佬油條!";
		String key ="3jd92j28ahl9.W2_1";
		byte[] data = encrypt(test.getBytes(), key);
		data = zip(data);
		System.out.println(new String(data));
		/*******************網路傳輸*************************/
		String key1 ="3jd92j28ahl9.W2_";//祕鑰長度只需要16位 可以不到16位 超過16將會無視
		byte[] data1 = unzip(data);
		data1 = decrypt(data1, key1);
		System.out.println(new String(data1));
	}

}