首先需要导入一个第三方jsr包,commons-codec.jar
下面是一个写好的工具类,调用该类的方法,实现使用指定密钥对明文进行加解密:
package util;
import java.io.UnsupportedEncodingException;
import java.util.Random;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
public class AesUtil {
//byte数组转字符串
public static String byteToString(byte[] byte1)
throws UnsupportedEncodingException {
return new String(byte1);
}
//加密时调用方法,三个参数分别是:明文,密钥,向量,注意向量的长度只能是16byte,而且加密解密时必须使用一致的向量。
public static byte[] AES_CBC_Encrypt(byte[] content, byte[] keyBytes,
byte[] iv) {
try {
SecretKeySpec key = new SecretKeySpec(keyBytes, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(iv));
byte[] result = ci