【发布时间】:2014-05-29 01:08:02
【问题描述】:
我有一个用 DES/ECB/PKCS5Padding 加密的私钥文件(由秘密短语生成的 56 位 DES 密钥),我想解密它。 我不知道为什么,但每次我尝试解密时,我的密码类的方法 doFinal 都会抛出这个错误:
javax.crypto.BadPaddingException:给定的最终块不正确 在 com.sun.crypto.provider.SunJCE_f.b(DashoA13*..) 处填充 com.sun.crypto.provider.SunJCE_f.b(DashoA13*..) 在 com.sun.crypto.provider.DESCipher.engineDoFinal(DashoA13*..) 在 javax.crypto.Cipher.doFinal(DashoA13*..) at...
这是我的代码:
public static PrivateKey readPrivateKeyFromFile(File file, String chaveSecreta) {
try {
SecureRandom r = new SecureRandom(chaveSecreta.getBytes());
KeyGenerator keyGen = KeyGenerator.getInstance("DES");
keyGen.init(56, r);
Key key = keyGen.generateKey();
byte[] privateKeyBytes = decryptPKFile(file, key);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(privateKeyBytes);
PrivateKey privateKey = null;
try {
privateKey = keyFactory.generatePrivate(privateKeySpec);
} catch (InvalidKeySpecException e) {
JOptionPane.showMessageDialog(null, "Erro 01, tente mais tarde");
}
return privateKey;
} catch (NoSuchAlgorithmException e) {
JOptionPane.showMessageDialog(null, "Erro 02, tente mais tarde");
}
return null;
}
public static byte[] decryptPKFile(File file, Key key){
try{
Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
byte[] cipherText = readBytes(file);
cipher.init(Cipher.DECRYPT_MODE, key);
System.out.println(cipher);
System.out.println(cipherText);
byte[] text = cipher.doFinal(cipherText);
return text;
}catch(Exception e){
e.printStackTrace();
return null;
}
}
public static byte[] readBytes(File file) {
try {
FileInputStream fs = new FileInputStream(file);
byte content[] = new byte[(int) file.length()];
fs.read(content);
return content;
} catch (FileNotFoundException e) {
System.out.println("Arquivo não encontrado!");
e.printStackTrace();
} catch (IOException ioe) {
System.out.println("Erro ao ler arquivo!");
ioe.printStackTrace();
}
return null;
}
有什么建议吗?
【问题讨论】:
-
我猜您从文件中读取的输入不是有效的加密文本。使用 DES 是块算法,你应该检查文件长度是否是 64 的乘积。如果不是,则意味着该文件已损坏。
-
你的意思是8的倍数?是的,文件没有损坏,我已经检查过了。
-
@markubik 这是一个随机密钥:P
标签: java encryption