Java 实现 AES 加解密

时间:2023-02-20 12:53:50

  毕业课题中需要使用加解密算法,要求加解密前后的数据长度不会变化,查了一些资料,发现可以采用AES加密的CFB跟OFB模式是无填充的模式,可以保持加解密前后数据的长度相等。下面上代码:

import java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException; import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec; public class Encrypt_Decrypt_AES { /**
* AES加密算法,调用Java自有类库,采用CFB模式密文反馈无填充模式,可以保证数据长度在加密前后是相同的
* @param content 待加密内容
* @param key 密钥
* @return byte[] 加密结果用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 = new IvParameterSpec(key.getBytes());
aesECB.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);
byte[] result = aesECB.doFinal(content.getBytes());
return result;
} 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;
} /**
*
* @param content 待解密内容,字符串形式
* @param key 解密用的密钥
* @return 使用字符串形式返回解密内容
* @throws UnsupportedEncodingException
*/ public static String decrypt_AES(byte[] content, String key) throws UnsupportedEncodingException {
try {
Cipher aesECB = Cipher.getInstance("AES/CFB/NoPadding");
SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(), "AES");
IvParameterSpec ivSpec = new IvParameterSpec(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);
return AES_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) throws InvalidKeyException,
InvalidAlgorithmParameterException, IllegalBlockSizeException,
BadPaddingException, UnsupportedEncodingException { String s = "fire fox 22";
byte[] r = encrypt_AES(s, "@93456781234567A");
for (byte i : r){
String l = Integer.toBinaryString((i & 0xFF) + 0x100).substring(1);
System.out.print(l+" ");
}
System.out.println();
decrypt_AES(r, "@93456781234567A");
} }