我有以下代码可以在Windows和Linux / Unix上运行,但不会解密在Linux / Unix上加密的加密文本,反之亦然。
我知道这也会每次生成相同的加密文本,但我删除了一些代码以达到最基本的。
我确信它与Charset编码无关,因为编码的String在两个操作系统上是相同的,即使SecretKey在两者上都是相同的。
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;
public class Encryptor {
private static final String password = "passwordKey";
private static final Charset UTF_8 = Charset.forName("UTF-8");
private static final byte [] salt = "test salt as string".getBytes(UTF_8);
public static String encrypt(String text) throws UnsupportedEncodingException {
IvParameterSpec ivSpec = new IvParameterSpec(password.getBytes(UTF_8));
PBEParameterSpec parameterSpec = new PBEParameterSpec(salt, 10000, ivSpec);
PBEKeySpec keySpec = new PBEKeySpec(password.toCharArray(), salt, 10000);
SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance("PBEWithSHA256AndAES_256");
SecretKey key = secretKeyFactory.generateSecret(keySpec);
Cipher cipher = Cipher.getInstance("PBEWithSHA256AndAES_256");
cipher.init(Cipher.ENCRYPT_MODE, key, parameterSpec);
byte [] encrypted = cipher.doFinal(text.getBytes(UTF_8));
return Base64.encodeBase64String(encrypted);
}
public static String decrypt(String encryptedText) throws UnsupportedEncodingException {
IvParameterSpec ivSpec = new IvParameterSpec(password.getBytes(UTF_8));
PBEParameterSpec parameterSpec = new PBEParameterSpec(salt, 10000, ivSpec);
PBEKeySpec keySpec = new PBEKeySpec(password.toCharArray(), salt, 10000);
SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance("PBEWithSHA256AndAES_256");
SecretKey key = secretKeyFactory.generateSecret(keySpec);
Cipher cipher = Cipher.getInstance("PBEWithSHA256AndAES_256");
cipher.init(Cipher.DECRYPT_MODE, key, parameterSpec);
byte [] decoded = Base64.decodeBase64String(encryptedText);
byte [] decrypted = cipher.doFinal(decoded);
return new String(decrypted, UTF_8);
}
public static void main(String args []) throws UnsupportedEncodingException {
String encryptedFromWindows = "eFRvTevgk/oslll+234r5tdsss==";
System.out.println(decrypt(encryptedFromWindows));
}
}
例外:
Exception in thread "main" javax.crypto.BadPaddingException: Given final block not properly padded
at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:811)
at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:676)
答案 0 :(得分:1)
问题是_64的JDK版本中的错误。升级到_121并成功运行。 IT不是已知的oracle错误,但他们在该版本中的另一个类似的加密问题中提到了该问题。