gpt4 book ai didi

java - java中的AES解密错误

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:00:42 24 4
gpt4 key购买 nike

我正在研究 AES 算法,我得到了这个异常:

javax.crypto.BadPaddingException: Given final block not properly padded
at com.sun.crypto.provider.SunJCE_f.b(DashoA13*..)
at com.sun.crypto.provider.SunJCE_f.b(DashoA13*..)
at com.sun.crypto.provider.AESCipher.engineDoFinal(DashoA13*..)
at javax.crypto.Cipher.doFinal(DashoA13*..)
at org.enterprisepower.io.MyEncryptTools.decrypt(MyEncryptTools.java:41)
at org.enterprisepower.io.IOUtils.copyStream(IOUtils.java:132)
at org.enterprisepower.net.portforward.Processor$Copier.run(Processor.java:99)
at java.lang.Thread.run(Unknown Source)

异常发生在解密部分。我在 myClient 程序中加密消息并将 cipherMessage 发送到 myServer 程序。在服务器收到 cipherMessage 后它抛出上述异常,但在客户端我可以解密完全相同的 cipherMessage。(我检查这与在两侧打印字节......)

这些是我的代码:

//It's decrypt method for both client and server
public byte[] decrypt(byte[] encryptedData, int length) throws Exception {
Key key = generateKey();
Cipher c = Cipher.getInstance(ALGO);
c.init(Cipher.DECRYPT_MODE, key);
byte[] enc = new byte[length];
for (int i = 0; i < length; i++) {
enc[i] = encryptedData[i];
}
byte[] decordedValue= Base64.decodeBase64(enc);//org.apache.commons.codec.binary.*;
byte[] decValue = c.doFinal(decordedValue);
return decValue;
}


//Client side
public static void copyStream(InputStream in, OutputStream out,
boolean closeOnFinish, boolean encrypt, String password) throws Exception {
MyEncryptTools mit;
try {
mit = new MyEncryptTools(password);
byte[] buf = new byte[BUF_SIZE];
byte[] enbuf ;
int count;
try {
if (encrypt) {
while (((count = in.read(buf)) != -1) && alive) {
enbuf = mit.encrypt(buf,count);
out.write(enbuf, 0, enbuf.length);
}
} else {
buf = new byte[172];
while (((count = in.read(buf)) != -1) && alive) {
enbuf = mit.decrypt(buf, count);
out.write(enbuf, 0, enbuf.length);
}
}
} finally {
if (closeOnFinish)
close(in);
if (closeOnFinish)
close(out);
}

} catch (Exception e) {
e.printStackTrace();
}
}



//Server side
public static void copyStream(InputStream in, OutputStream out,
boolean closeOnFinish, boolean encrypt, String user, String password) throws Exception {
MyEncryptTools mit;
try {
mit = new MyEncryptTools(password);

byte[] buf = new byte[BUF_SIZE];
byte[] enbuf ;
int count;
try {
if (encrypt) {
System.out.println("Encrypt;");
while (((count = in.read(buf)) != -1)) {
enbuf = mit.encrypt(buf,count);
out.write(enbuf, 0, enbuf.length);
}
} else {
buf = new byte[172];
while (((count = in.read(buf)) != -1)) {
enbuf = mit.decrypt(buf, count);
out.write(enbuf, 0, enbuf.length);
}
}
} finally {
if (closeOnFinish)
close(in);
if (closeOnFinish)
close(out);
}

} catch (Exception e) {
e.printStackTrace();
}
}

我应该提一下,我使用一个 117 字节的数组进行加密,并使用一个 172 字节的数组进行解密。

最佳答案

使用美妙的 CipherInputStream 并忘记缓冲区长度。

关于java - java中的AES解密错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7281619/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com