12月 082015
 

DES使用越来越少,原因就在于其使用56位密钥,比较容易被破解,近些年来逐渐被AES替代,AES已经变成目前对称加密中最流行算法之一;AES可以使用128、192、和256位密钥,并且用128位分组加密和解密数据(目前默认java仅支持128位密钥,需下载扩展包支持256位,见java扩展算法与辅助工具)。本文就简单介绍如何通过JAVA实现AES加密。

网上很多java 实现AES的代码都有这样那样问题,现摘录《java加密与解密的艺术》中关于AES的代码, 简单明了,关键是有效!!!

JAVA实现

package test.rsa;

import java.security.Key;
import java.util.Arrays;

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

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

public class AESCoder {
public static final String KEY_ALGORITHM = “AES”;

public static final String CIPHER_ALGORITHM = “AES/ECB/PKCS5Padding”;

private static Key toKey(byte[] key) throws Exception {
SecretKey secretKey = new SecretKeySpec(key, KEY_ALGORITHM);
return secretKey;
}

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);
}

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(128);
SecretKey secretKey = kg.generateKey();
return secretKey.getEncoded();

}

public static void main(String[] args) throws Exception {
String inputStr=”测试 AES 密钥密钥密钥密钥”;
byte[] inputData = inputStr.getBytes();
System.out.println(“原文[arrays]:\t” + Arrays.toString(inputData));
System.out.println(“原文:\t” + inputStr);

byte[] key = initKey();
System.out.println(“密钥[arrays]:\t” + Arrays.toString(key));
System.out.println(“密钥[base64]:\t” + Base64.encodeBase64String(key));

inputData = encrypt(inputData, key);
System.out.println(“加密后[arrays]:\t” + Arrays.toString(inputData));
System.out.println(“加密后[base64]:\t” + Base64.encodeBase64String(inputData));

byte[] outputData= decrypt(inputData, key);
System.out.println(“解密后[arrays]:\t” + Arrays.toString(outputData));
System.out.println(“解密后[base64]:\t” + new String(outputData));

}

}

密钥的合成及base64转码方式,给我们保存及传输提供了想象空间。