java - 代码适用于 Windows JDK 7 但不适用于 Linux JDK 7

标签 java linux windows encryption java-7

以下代码在 Windows 上的 Oracle JDK 7 中运行良好,但在 Linux 上失败并出现以下错误:javax.crypto.IllegalBlockSizeException:使用填充密码解密时输入长度必须是 8 的倍数 line Cipher.doFinal(ciphertextArray) 这是使用完全相同的 Jar 文件和完全相同的命令行等。虽然文本和密码的值来自命令行我怀疑问题出在这里,我只是不知道在哪里...

String saltD = text.substring(0,12);
String ciphertext = text.substring(12,text.length());

// BASE64Decode the bytes for the salt and the ciphertext
Base64 decoder = new Base64();
byte[] saltArray = decoder.decode(saltD);
byte[] ciphertextArray = decoder.decode(ciphertext);

// Create the PBEKeySpec with the given password
PBEKeySpec keySpec = new PBEKeySpec(password.trim().toCharArray());

// Get a SecretKeyFactory for PBEWithSHAAndTwofish
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(encryptionMethod);

// Create our key
SecretKey key = keyFactory.generateSecret(keySpec);

// Now create a parameter spec for our salt and iterations
PBEParameterSpec paramSpec = new PBEParameterSpec(saltArray, ITERATIONS);

// Create a cipher and initialize it for encrypting
Cipher cipher = Cipher.getInstance(encryptionMethod);
cipher.init(Cipher.DECRYPT_MODE, key, paramSpec);

// Perform the actual decryption
byte[] plaintextArray = cipher.doFinal(ciphertextArray);
return new String(plaintextArray);

最佳答案

观察结果似乎是由于两个平台上的默认字符集不同所致。

您需要确保 Stringbyte[] 的转换(反之亦然)是使用指定的字符集执行的,而不是依赖于平台默认值。

关于java - 代码适用于 Windows JDK 7 但不适用于 Linux JDK 7,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16032002/

相关文章:

java - 为什么克隆阵列这么慢?

sql-server - Linux Open Suse "pyodbc.Error: (' 0100 0', "[01000] [unixODBC] [Driver Manager]无法打开 lib 'SQL Server' : file not found (0) (SQLDriverConnect )")"

php - MySQL PHP DELETE 不适用于此实例?

windows - 检测操作系统批处理

windows - 最小化应用程序时隐藏表单

ruby - 在 bash : no such file or directory 中安装 rvm 结果

java - 如何使用 Java(Apache HTTP 客户端)模拟浏览器 HTTPS POST 请求?

java - Eclipse 在启动时崩溃(eclipse.exe 已停止工作),任何解决方案?

linux - 如果任何查询失败则停止 shell 脚本

java - 具有泛型参数的 Java 方法 - 为什么我不能传递具有作为方法参数子类的泛型参数的对象?