对称加密算法-AES

package com.wilson.EDecryption;

import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import junit.framework.Assert;

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

public class AESCoderTest {
	@Test
	public void test() throws Exception {
		String inputStr = "AES加密";
		byte[] inputData = inputStr.getBytes();
		System.out.println("原文: \t" + inputStr);

		// initial key
		byte[] key = AESCoder.initKey();
		System.out.println("密钥:\t" + Base64.encodeBase64String(key));

		//encryption
		inputData = AESCoder.encrypt(inputData, key);
		System.out.println("加密后:\t" + Base64.encodeBase64String(inputData));

		//decryption
		byte[] outputData = AESCoder.decrypt(inputData, key);
		String outputStr = new String(outputData);
		System.out.println("解密后:\t" + outputStr);

		Assert.assertEquals(inputStr, outputStr);
	}
}

class AESCoder {
	private static final String KEY_ALGORITHM = "AES";
	private static final String CHIPHER_ALGORITHM = "AES/ECB/PKCS5Padding";

	public static byte[] initKey() throws NoSuchAlgorithmException {
		KeyGenerator kg = KeyGenerator.getInstance(KEY_ALGORITHM);
		kg.init(128);
		SecretKey secretKey = kg.generateKey();
		return secretKey.getEncoded();
	}

	public static byte[] decrypt(byte[] data, byte[] key) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
		Key k = new SecretKeySpec(key, KEY_ALGORITHM);
		Cipher cipher = Cipher.getInstance(CHIPHER_ALGORITHM);
		cipher.init(Cipher.DECRYPT_MODE, k);
		return cipher.doFinal(data);
	}

	public static byte[] encrypt(byte[] data, byte[] key) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
		Key k = new SecretKeySpec(key, KEY_ALGORITHM);
		Cipher cipher = Cipher.getInstance(CHIPHER_ALGORITHM);
		cipher.init(Cipher.ENCRYPT_MODE, k);
		return cipher.doFinal(data);
	}

}

猜你喜欢

转载自caerun.iteye.com/blog/1299973