AES加密:
最常见的对称加密算法。对称加密算法即加密和解密用相同的密钥
直接上代码:
工具类
import com.google.common.base.Charsets;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
public class SignUtils {
public static String aesEncrypt(String content, byte[] keyBytes) {
try {
SecretKey secretKey = new SecretKeySpec(keyBytes, "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] p = content.getBytes("UTF-8");
byte[] result = cipher.doFinal(p);
return Base64Util.encode(result);
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
public static String aesDecrypt(String content, byte[] keyBytes) {
try {
SecretKey secretKey = new SecretKeySpec(keyBytes, "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] p = Base64Util.decodeToBytes(content);
byte[] result = cipher.doFinal(p);
return new String(result, Charsets.UTF_8);
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
}
import java.io.UnsupportedEncodingException;
import java.util.Base64;
public class Base64Util {
public static String encode(byte[] data) {
try {
return new String(Base64.getEncoder().encode(data), "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return null;
}
}
public static final byte[] decodeToBytes(String text) {
try {
String[][] replaces= {{"_","/"},{"%2f","/"},{"%2F","/"},{"-","+"},{"%3d","="},{"%3D","="}};
for (String[] item: replaces){
text = text.replace(item[0], item[1]);
}
return Base64.getDecoder().decode(text.getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return null;
}
}
}
测试类
import java.nio.charset.StandardCharsets;
public class Test {
public static void main(String[] args) {
//密钥
String key="2019201820172016";
String string="{\"returnId\":\"JM00000000070\",\"isRelief\":\"SUCCESS\"}";
System.out.println("加密内容 : "+string);
String encryptAes = SignUtils.aesEncrypt(string, key.getBytes(StandardCharsets.UTF_8));
System.out.println("aes加密后的密文 : "+encryptAes);
String aesDecrypt=SignUtils.aesDecrypt(encryptAes, key.getBytes(StandardCharsets.UTF_8));
System.out.println("aes加密密文解密后的内容 : "+aesDecrypt);
}
}
测试结果:
加密内容 : {"returnId":"JM00000000070","isRelief":"SUCCESS"}
aes加密内容后的密文 : ePpedaL94oX+X3uCUTCa770tMKY4rqznChitE7K44IHqSNZStNsVgGnxKZDi/3qrQCd5ku4ybFh44Z7nt49/eg==
aes加密密文解密后的内容 : {"returnId":"JM00000000070","isRelief":"SUCCESS"}