AES加密解密

public class AesTest {

//加密
public static byte[] encrypt(String content,String password){

try {
KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
keyGenerator.init(128,new SecureRandom(password.getBytes()));
SecretKey secretKey = keyGenerator.generateKey();
byte[] keyEncoded = secretKey.getEncoded();
SecretKeySpec secretKeySpec = new SecretKeySpec(keyEncoded, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
byte[] contentBytes = content.getBytes("utf-8");
byte[] result = cipher.doFinal(contentBytes);
return result;
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (BadPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
//解密
public static  byte[] decrypt(byte[] content,String password){
try {
KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
keyGenerator.init(128,new SecureRandom(password.getBytes()));
SecretKey secretKey = keyGenerator.generateKey();
byte[] keyEncoded = secretKey.getEncoded();
SecretKeySpec secretKeySpec = new SecretKeySpec(keyEncoded, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
byte [] result = cipher.doFinal(content);
return result;
} catch (InvalidKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (BadPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;

}

public static void main(String[] args) {
String content = "aestest";
String password = "123456";
byte[] encrypt = encrypt(content, password);
System.out.println(encrypt);
byte[] decrypt = decrypt(encrypt, password);
System.out.println(new String(decrypt));
}

}


//加密后的byte数组是不能强制转换成字符串的,换言之:字符串和byte数组在这种情况下不是互逆的

要避免这种情况:

byte[] encryptResult = encrypt(content, password); 

String encryptResultStr = new String(encryptResult,"utf-8"); 

javax.crypto.IllegalBlockSizeException: Input length must be multiple of 16 when decrypting with padded cipher

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值