AES本身通用算, 能Base64编码候字符串编码格式才导致相同(UTF-8, GBK)编码
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import javax.crypto.*;
import javax.crypto.spec.*;
/**
*
* @author wchun
*
* AES128 算加密模式ECB填充模式 pkcs7(实际pkcs5)
*
*
*/
public class AES {
static final String algorithmStr="AES/ECB/PKCS5Padding";
static private KeyGenerator keyGen;
static private Cipher cipher;
static boolean isInited=false;
//初始化
static private void init()
{
//初始化keyGen
try {
keyGen=KeyGenerator.getInstance("AES");
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
keyGen.init(128);
//初始化cipher
try {
cipher=Cipher.getInstance(algorithmStr);
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
isInited=true;
}
public static byte[] GenKey()
{
if(!isInited)//没初始化,则初始化
{
init();
}
return keyGen.generateKey().getEncoded();
}
public static byte[] Encrypt(byte[] content,byte[] keyBytes)
{
byte[] encryptedText=null;
if(!isInited)//初始化
{
init();
}
Key key=new SecretKeySpec(keyBytes,"AES");
try {
cipher.init(Cipher.ENCRYPT_MODE, key);
} catch (InvalidKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
encryptedText=cipher.doFinal(content);
} catch (IllegalBlockSizeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (BadPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return encryptedText;
}
//解密byte[]
public static byte[] DecryptToBytes(byte[] content,byte[] keyBytes)
{
byte[] originBytes=null;
if(!isInited)
{
init();
}
Key key=new SecretKeySpec(keyBytes,"AES");
try {
cipher.init(Cipher.DECRYPT_MODE, key);
} catch (InvalidKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//解密
try {
originBytes=cipher.doFinal(content);
} catch (IllegalBlockSizeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (BadPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return originBytes;
}
}