AES 解密 报 Base-64 字符数组的无效长度

理论不说了,主要说怎么解决。

该类问题 主要存在于 编码解码的问题。

 

由于 在传输过程中,将字符串中的 “+”,编码为 空格,而在解码时,并没有将 空格 解码为 +,故而应该在传输前,手动将 “+”进行编码

 

方法如下:  string.replace("+","%2B");

 

如图所示

知乎: https://zhuanlan.zhihu.com/albertwang

微信公众号:AI-Research-Studio

https://i-blog.csdnimg.cn/blog_migrate/5509f60f875d387159a310532cc257dd.png ​​

下面是赞赏码

 

好的,我可以帮你解答这个问题。 在 Java 中,我们可以使用 javax.crypto 库中的 Cipher 类进行 AES 加密和解密操作。具体步骤如下: 1. 创建 Cipher 对象 ```java Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); ``` 2. 创建密钥 ```java SecretKeySpec secretKey = new SecretKeySpec(keyBytes, "AES"); ``` 其中,keyBytes 是一个 byte 数组,表示密钥的内容。 3. 初始化 Cipher 对象 ```java cipher.init(Cipher.ENCRYPT_MODE, secretKey, new IvParameterSpec(ivBytes)); ``` 其中,ivBytes 是一个 byte 数组,表示初始化向量。 4. 加密或解密数据 ```java byte[] result = cipher.doFinal(dataBytes); ``` 其中,dataBytes 是一个 byte 数组,表示要加密或解密的数据。 5. 将加密或解密后的结果转换成字符串或字节数组 如果需要将加密或解密后的结果转换成字符串,可以使用 Base64 编码。具体代码如下: ```java String resultStr = Base64.getEncoder().encodeToString(result); ``` 如果需要将加密或解密后的结果转换成字节数组,可以直接使用得到的 result 数组。 完整的示例代码如下: ```java import java.util.Base64; import javax.crypto.Cipher; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; public class AesUtils { public static byte[] encrypt(byte[] keyBytes, byte[] ivBytes, byte[] dataBytes) throws Exception { Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); SecretKeySpec secretKey = new SecretKeySpec(keyBytes, "AES"); cipher.init(Cipher.ENCRYPT_MODE, secretKey, new IvParameterSpec(ivBytes)); return cipher.doFinal(dataBytes); } public static byte[] decrypt(byte[] keyBytes, byte[] ivBytes, byte[] dataBytes) throws Exception { Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); SecretKeySpec secretKey = new SecretKeySpec(keyBytes, "AES"); cipher.init(Cipher.DECRYPT_MODE, secretKey, new IvParameterSpec(ivBytes)); return cipher.doFinal(dataBytes); } public static void main(String[] args) throws Exception { String dataStr = "hello, world!"; byte[] keyBytes = "0123456789abcdef".getBytes(); byte[] ivBytes = "0123456789abcdef".getBytes(); byte[] dataBytes = dataStr.getBytes(); // 加密 byte[] encryptedBytes = encrypt(keyBytes, ivBytes, dataBytes); String encryptedStr = Base64.getEncoder().encodeToString(encryptedBytes); System.out.println(encryptedStr); // 解密 byte[] decryptedBytes = decrypt(keyBytes, ivBytes, encryptedBytes); String decryptedStr = new String(decryptedBytes); System.out.println(decryptedStr); } } ``` 希望这个答案能够帮助到你!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值