java aes 不填充_AES加密给定最终块未正确填充

我正在尝试创建一个允许我使用AES算法加密和解密字符串的类。 我正在使用来自http://aesencryption.net/#Java-aes-encryption-example的例外,但修改了代码以满足我的需要。

这是我的Main.java:public class Main {

public static void main(String[] args) {

AES256 aes = new AES256();

aes.setKey("Secret Key");

String enc = "";

enc = aes.encrypt("qwertyuiopasdfgh");

System.out.println(enc);

System.out.println(aes.decrypt(enc));

}

}

这是我的AES256.java:import java.io.UnsupportedEncodingException;

import java.security.InvalidKeyException;

import java.security.MessageDigest;

import java.security.NoSuchAlgorithmException;

import java.util.Arrays;

import java.util.Base64;

import javax.crypto.BadPaddingException;

import javax.crypto.Cipher;

import javax.crypto.IllegalBlockSizeException;

import javax.crypto.NoSuchPaddingException;

import javax.crypto.spec.SecretKeySpec;

public class AES256 {

private SecretKeySpec secretKey;

private byte[] key;

public void setKey(String key) {

MessageDigest sha = null;

try {

this.key = key.getBytes("UTF-8");

sha = MessageDigest.getInstance("SHA-1");

this.key = sha.digest(this.key);

this.key = Arrays.copyOf(this.key, 16);

secretKey = new SecretKeySpec(this.key, "AES");

} catch (UnsupportedEncodingException | NoSuchAlgorithmException e) {

e.printStackTrace();

}

}

public String getSecretKey() {

return secretKey.toString();

}

public String getKey() {

return new String(key);

}

public String encrypt(String string) {

try {

Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");

cipher.init(Cipher.ENCRYPT_MODE, secretKey);

return Base64.getMimeEncoder().encodeToString(string.getBytes());

} catch (InvalidKeyException | NoSuchAlgorithmException | NoSuchPaddingException e) {

e.printStackTrace();

}

return null;

}

public String decrypt(String string) {

try {

Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");

cipher.init(Cipher.DECRYPT_MODE, secretKey);

return new String(cipher.doFinal(Base64.getMimeDecoder().decode(string.getBytes())));

} catch (InvalidKeyException | NoSuchAlgorithmException | NoSuchPaddingException | IllegalBlockSizeException | BadPaddingException e) {

e.printStackTrace();

}

return null;

}

}

这是抛出的错误:javax.crypto.BadPaddingException: Given final block not properly padded

at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:966)

at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:824)

at com.sun.crypto.provider.AESCipher.engineDoFinal(AESCipher.java:436)

at javax.crypto.Cipher.doFinal(Cipher.java:2121)

at AES256.decrypt(AES256.java:55)

at Main.main(Main.java:13)

有人知道是什么导致了这个错误吗?

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值