importjava.io.UnsupportedEncodingException;importjava.security.InvalidAlgorithmParameterException;importjava.security.InvalidKeyException;importjava.security.NoSuchAlgorithmException;importjavax.crypto.BadPaddingException;importjavax.crypto.Cipher;importjavax.crypto.IllegalBlockSizeException;importjavax.crypto.NoSuchPaddingException;importjavax.crypto.spec.IvParameterSpec;importjavax.crypto.spec.SecretKeySpec;public classEncrypt_Decrypt_AES {/*** AES加密算法,调用Java自有类库,采用CFB模式密文反馈无填充模式,可以保证数据长度在加密前后是相同的
*@paramcontent 待加密内容
*@paramkey 密钥
*@returnbyte[] 加密结果用byte数组表示
**/
public static byte[] encrypt_AES(String content, String key) {try{
Cipher aesECB= Cipher.getInstance("AES/CFB/NoPadding");
SecretKeySpec keySpec= new SecretKeySpec(key.getBytes(), "AES");
IvParameterSpec ivSpec= newIvParameterSpec(key.getBytes());
aesECB.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);byte[] result =aesECB.doFinal(content.getBytes());returnresult;
}catch(NoSuchAlgorithmException e) {
e.printStackTrace();
}catch(NoSuchPaddingException e) {
e.printStackTrace();
}catch(InvalidKeyException e) {
e.printStackTrace();
}catch(IllegalBlockSizeException e) {
e.printStackTrace();
}catch(BadPaddingException e) {
e.printStackTrace();
}catch(InvalidAlgorithmParameterException e) {//TODO 自动生成的 catch 块
e.printStackTrace();
}return null;
}/***
*@paramcontent 待解密内容,字符串形式
*@paramkey 解密用的密钥
*@return使用字符串形式返回解密内容
*@throwsUnsupportedEncodingException*/
public static String decrypt_AES(byte[] content, String key) throwsUnsupportedEncodingException {try{
Cipher aesECB= Cipher.getInstance("AES/CFB/NoPadding");
SecretKeySpec keySpec= new SecretKeySpec(key.getBytes(), "AES");
IvParameterSpec ivSpec= newIvParameterSpec(key.getBytes());
aesECB.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);byte[] result =aesECB.doFinal(content);
String AES_decode=new String(result,"utf-8");/************************************/
//System.out.println("解密结果:"+AES_decode);
returnAES_decode;
}catch(NoSuchAlgorithmException e) {
e.printStackTrace();
}catch(NoSuchPaddingException e) {
e.printStackTrace();
}catch(InvalidKeyException e) {
e.printStackTrace();
}catch(IllegalBlockSizeException e) {
e.printStackTrace();
}catch(BadPaddingException e) {
e.printStackTrace();
}catch(InvalidAlgorithmParameterException e) {//TODO 自动生成的 catch 块
e.printStackTrace();
}return null;
}public static void main(String[] str) throwsInvalidKeyException,
InvalidAlgorithmParameterException, IllegalBlockSizeException,
BadPaddingException, UnsupportedEncodingException {
String s= "fire fox 22";byte[] r = encrypt_AES(s, "@93456781234567A");for (bytei : r){
String l= Integer.toBinaryString((i & 0xFF) + 0x100).substring(1);
System.out.print(l+" ");
}
System.out.println();
decrypt_AES(r,"@93456781234567A");
}
}