我的應用程序在Windows中工作,但在Linux中出現故障,出現Given final block not properly padded
異常。例外:在Linux中「給定最終塊未正確填充」,但它在Windows中工作
配置:
- JDK版本:1.6
- 的Windows:版本7
- 的Linux:CentOS的5.8 64位
我的代碼如下:
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
public class SecurityKey {
private static Key key = null;
private static String encode = "UTF-8";
private static String cipherKey = "DES/ECB/PKCS5Padding";
static {
try {
KeyGenerator generator = KeyGenerator.getInstance("DES");
String seedStr = "test";
generator.init(new SecureRandom(seedStr.getBytes()));
key = generator.generateKey();
} catch(Exception e) {
}
}
// SecurityKey.decodeKey("password")
public static String decodeKey(String str) throws Exception {
if(str == null)
return str;
Cipher cipher = null;
byte[] raw = null;
BASE64Decoder decoder = new BASE64Decoder();
String result = null;
cipher = Cipher.getInstance(cipherKey);
cipher.init(Cipher.DECRYPT_MODE, key);
raw = decoder.decodeBuffer(str);
byte[] stringBytes = null;
stringBytes = cipher.doFinal(raw); // Exception!!!!
result = new String(stringBytes, encode);
return result;
}
}
在該行:
ciper.doFilnal(raw);
以下異常被拋出:
javax.crypto.BadPaddingException: Given final block not properly padded
我怎樣才能解決這個問題?
我希望你不要在乎安全。 DES和ECB都是一個可疑的選擇。 – CodesInChaos
您假定'SecureRandom'在所有平臺上的行爲方式都是相同的。 Java保證嗎?使用KDF來派生密鑰,而不是PRNG。 – CodesInChaos
你確定'raw'在兩個平臺上都包含相同的數據嗎?在將數據傳遞給'decodeKey()'之前,我會懷疑一些錯誤的編碼蓋度,儘管使用base64的可能性不大。 – axtavt