我已经尝试了几天,用java解密使用openssl加密的消息。该消息已使用以下命令加密:
openssl enc -e -aes-256-cbc -kfile $ file.key -in toto -out toto.enc。
文件file.key包含256位对称密钥。在命令中未指定盐,但文件以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)
最佳答案
否,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
等效的代码。看到重复或接近重复的Qs:
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://crypto.stackexchange.com/questions/3298/is-there-a-standard-for-openssl-interoperable-aes-encryption/#35614