一.简介

    AES是一种分组密码,用以取代DES的商业应用,其分组长度为128位,秘钥长度为128位、192位或256位。

    AES采用Feistel结构,每轮由四个单独的运算组成:字节代替、置换、有限域上的算术运算以及与秘钥的异或运算。

    

二.下面给出AES的实现

1.工程结构:

java new AES方法 java aes算法_ci


 2.下面是java实现AES对称加密并进行测试的全部代码:

AES.java

package aes;

import java.security.Key;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

public class AES {
    /**
     * 秘钥算法
     */
	public static final String KEY_ALGORITHM = "AES";
    
	/**
	 * 加密/解密算法    工作模式    填充方式
	 */
	public static final String CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding";
	
	/**
	 * 转换秘钥
	 * @param key
	 * @return
	 * @throws Exception
	 */
	public static Key toKey(byte[] key) throws Exception{
		//实例化AES秘钥材料
		SecretKey secretKey = new SecretKeySpec(key, KEY_ALGORITHM);
		return secretKey;
	}
	
	/**
	 * 解密操作
	 * @param data
	 * @param key
	 * @return
	 * @throws Exception
	 */
	public static byte[] decrypt(byte[] data, byte[] key) throws Exception{
		//还原秘钥
		Key k = toKey(key);
		Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
		cipher.init(Cipher.DECRYPT_MODE, k);
		return cipher.doFinal(data);
	}
	
	/**
	 * 加密操作
	 * @param data
	 * @param key
	 * @return
	 * @throws Exception
	 */
	public static byte[] encrypt(byte[] data, byte[] key) throws Exception{
		//还原秘钥
		Key k = toKey(key);
		Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
		cipher.init(Cipher.ENCRYPT_MODE, k);
		return cipher.doFinal(data);
	}
	
	
	public static byte[] initKey() throws Exception{
		//实例化
		KeyGenerator kg = KeyGenerator.getInstance(KEY_ALGORITHM);
		kg.init(256);
		SecretKey secretKey = kg.generateKey();
		return secretKey.getEncoded();
	}
}

AESTest.java

package aes;

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

public class AESTest {

	public static void main(String[] args) throws Exception {
		// TODO Auto-generated method stub
        String inputMessage = "好好学习,天天向上!";
        System.out.println("明文:\n" + inputMessage);
        byte[] inputData = inputMessage.getBytes();
        //初始化秘钥
        byte[] key = AES.initKey();
        System.out.println("秘钥:\n" + Base64.encodeBase64String(key));
        //加密
        inputData = AES.encrypt(inputData, key);
        System.out.println("加密得到的密文:\n" + Base64.encodeBase64String(inputData));
        //解密
        byte[] outputData = AES.decrypt(inputData, key);
        String outputMessage = new String(outputData);
        System.out.println("解密得到的明文:\n" + outputMessage);
	}

}

三.运行结果:

java new AES方法 java aes算法_System_02