您的位置:首页 > 编程语言 > Java开发

java AES加密解密

2012-04-12 22:05 323 查看
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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: