几天来,我一直试图用java解密一条用openssl加密的消息。该消息是使用以下命令加密的:
openssl enc -e -aes-256-cbc -kfile $ file.key -in toto -out toto.enc.
文件file.key包含256位的对称密钥。命令中没有指定salt,但是文件以Salted__开头。下面是我编写的试图解密文件的类,但即使删除文件中的16个字符,即: Salted__ +加密的salt,也不可能得到任何信息。我知道默认情况下openssl是这样做的。当我试图解密时,会抛出与加密文本相关的异常。
有人能帮我吗?一条赛道?一个主意?
非常感谢。
守则:
public class Java {
private static SecretKey key = null;
private static Cipher cipher = null;
public static void main(String[] args) throws Exception
{
String filename = RESOURCES_DIR + "toto.enc";
byte[] key = Base64.decode("2AxIw+/AzDBj83OILV9GDpOs+izDFJEhD6pve/IPsN9=");
SecretKeySpec secretKey = new SecretKeySpec(key, "AES");
cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] test = Base64.decode(readFile(filename));
byte[] decryptedBytes = cipher.doFinal(test);
String decryptedText = new String(decryptedBytes, "UTF8");
System.out.println("After decryption: " + decryptedText);
}
public final static String RESOURCES_DIR = "C:/Users/toto/Desktop/";
static String readFile(String filename) throws FileNotFoundException, IOException {
FileReader fr;
BufferedReader br;
fr = new FileReader(new File(filename));
br = new BufferedReader(fr);
String str;
String res = "";
while ((str = br.readLine()) != null) {
res += str;
}
return res;
}
}错误:
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)
at com.sun.crypto.provider.AESCipher.engineDoFinal(AESCipher.java:313)
at javax.crypto.Cipher.doFinal(Cipher.java:2131)
at deciphertodeploytest6.Java.main(Java.java:52)发布于 2017-04-03 19:09:12
不,file.key不包含密钥。openssl enc -kfile读取的密码不是密钥,而是用于派生密钥和IV (如果适用的话,它就在这里);参见手册页。默认情况下,该密钥派生使用随机盐类,并且自2016-08年以来,默认散列依赖于您未声明的OpenSSL版本。而且,Java中的Cipher.getInstance("AES")默认为ECB,而不是您需要的CBC。(它也默认为“PKCS5”填充,这确实与OpenSSL匹配,尽管从技术上讲,它应该被称为PKCS7而不是PKCS5。)
要在Java中匹配openssl enc使用的PBKDF (因此是键和IV),可以使用BouncyCastle或编写相当于OpenSSL的EVP_BytesToKey的代码;请参见dupe或接近dupe:
Java equivalent of an OpenSSL AES CBC encryption
How to decode a string encoded with openssl aes-128-cbc using java?
How to decrypt AES encrypted file with '-nosalt' param
How to decrypt file in Java encrypted with openssl command using AES?
https://stackoverflow.com/questions/43189765
复制相似问题