AES加密Demo
aes对称加密,一个密码,加密解密全完成。加密没有长度限制
``
package com.autoyong.common.utils;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
public class AESUtil {
private static final String defaultCKey = "hello@world";
/**
* 使用默认字符进行加密
*
* @param msg
* @return
*/
public static String EncryptByDefaultKey(String msg) {
try {
return Encrypt(msg, defaultCKey);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 使用默认密码进行解密
*
* @param msg
* @return
*/
public static String DecryptByDefaultKey(String msg) {
try {
return Decrypt(msg, defaultCKey);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
// 加密
public static String Encrypt(String sSrc, String sKey) throws Exception {
if (sKey == null) {
System.out.print("Key为空null");
return null;
}
// 判断Key是否为16位
if (sKey.length() != 16) {
System.out.print("Key长度不是16位");
return null;
}
byte[] raw = sKey.getBytes("utf-8");
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");//"算法/模式/补码方式"
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] encrypted = cipher.doFinal(sSrc.getBytes("utf-8"));
String result = new BASE64Encoder().encode(encrypted);
result = result.replaceAll("\r|\n", "");
return result;//此处使用BASE64做转码功能,同时能起到2次加密的作用。
}
// 解密
public static String Decrypt(String sSrc, String sKey) throws Exception {
try {
// 判断Key是否正确
if (sKey == null) {
System.out.print("Key为空null");
return null;
}
// 判断Key是否为16位
if (sKey.length() != 16) {
System.out.print("Key长度不是16位");
return null;
}
byte[] raw = sKey.getBytes("utf-8");
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
byte[] encrypted1 = new BASE64Decoder().decodeBuffer(sSrc);//先用base64解密
try {
byte[] original = cipher.doFinal(encrypted1);
String originalString = new String(original, "utf-8");
return originalString;
} catch (Exception e) {
System.out.println(e.toString());
return null;
}
} catch (Exception ex) {
System.out.println(ex.toString());
return null;
}
}
public static void main(String[] args) throws Exception {
/*
* 此处使用AES-128-ECB加密模式,key需要为16位。
*/
String cKey = "jkl;POIU1234++==";
// 需要加密的字串
String cSrc = "{\"userId\":\"myUserId\",\"orderId\":\"ORDER000001\",\"amount\":0,\"num\":10,\"mobileNo\":\"13266668888\",\"orderItemDtos\":[{\"productId\":\"000001\",\"productCode\":\"productCode-001x\",\"productName\":\"天马牌活塞\",\"count\":5,\"price\":10},{\"productId\":\"000002\",\"productCode\":\"productCode-002x\",\"productName\":\"天马牌缸套\",\"count\":6,\"price\":10}]}";
System.out.println(cSrc);
// 加密
String enString = AESUtil.EncryptByDefaultKey(cSrc);
System.out.println("加密后的字串是:");
System.out.println(enString);
// 解密
String DeString = AESUtil.DecryptByDefaultKey(enString);
System.out.println("解密后的字串是:" + DeString);
}
}