直接上代码.
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
public class AesEncrypt {
private final static String ORIGIN_KEY = "12jgUQFppppuwkkj";
private final static SecretKey SECRET_KEY = initSecretKey();
private static SecretKey initSecretKey() {
SecretKeySpec aes = new SecretKeySpec(ORIGINKEY.getBytes(), "AES");
return aes;
}
/**
* 加密
* @param source 一般字符串
* @return base64Str base64字符串
* @throws Exception
*/
public static String encryptAES(String source) throws Exception {
if (source==null){
return null;
}
byte[] bytes1 = base642Byte(Base64Encode.encode(source));
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, SECRETKEY);
byte[] bytes2 = cipher.doFinal(bytes1);
return byte2Base64(bytes2);
}
/**
* 解密
* @param base64Code 一般字符串base64
* @return base64Str
* @throws Exception
*/
public static String decryptAES(String base64Code) throws Exception {
if (base64Code==null){
return null;
}
byte[] bytes1 = base642Byte(base64Code);
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, SECRETKEY);
byte[] bytes2 = cipher.doFinal(bytes1);
return Base64Encode.decode(byte2Base64(bytes2));
}
/**
* 字节数组转Base64编码
*/
public static String byte2Base64(byte[] bytes) {
BASE64Encoder encoder = new BASE64Encoder();
return encoder.encode(bytes);
}
/**
* Base64编码转字节数组
*/
public static byte[] base642Byte(String base64Key) throws IOException {
BASE64Decoder decoder = new BASE64Decoder();
return decoder.decodeBuffer(base64Key);
}
}
下面是配合使用的base64工具类,可以完成一般字符串和base64字符串之间的转换。
下面这个类是我从csdn获取的,所以没有做代码合并。
这个类使用的base64依赖包(org.apache.commons.codec.binary.Base64),和我的aes加密工具类使用的不同,更推荐这个包
import java.io.UnsupportedEncodingException;
import org.apache.commons.codec.binary.Base64;
public class Base64Encode {
private static final String charset = "utf-8";
/**
* 解码成一般字符串
*/
public static String decode(String data) {
try {
if (null == data) {
return null;
}
return new String(Base64.decodeBase64(data.getBytes(charset)), charset);
} catch (UnsupportedEncodingException e) {
System.err.println(e);
}
return null;
}
/**
* 编码成base64字符串
*/
public static String encode(String data) {
try {
if (null == data) {
return null;
}
return new String(Base64.encodeBase64(data.getBytes(charset)), charset);
} catch (UnsupportedEncodingException e) {
System.err.println(e);
}
return null;
}
}
需要注意的几点:
1,AesEncrypt类中的ORIGIN_KEY是用于生成128位AES秘钥的源字符串,长度必须是16(128/8)个字符,是解密的关键。用于生产环境时,这个字符串需要客户端和服务器约定好,且一定要对这个常量做安全处理。
2,加密后返回的是base64字符串,解密前不要试图把密文转成一般字符串,否则再回溯成byte[]数组时会有位数丢失导致解密失败
3,使用这个加解密逻辑时,配合使用时间戳加密验证字段,可以提高通话验证的可操作性
4,这个工具类应对一般加解密需求足够了,若有更高的安全需求,推荐一篇讲aes+rsa双向加密的分享帖: https://blog.csdn.net/qq_32523587/article/details/79146977