[英]AES encrypt with openssl decrypt using java
我必须使用 openssl 命令行或 C api 加密一个 xml 文件。 输出应为 Base64。
java程序将用于解密。 此程序由客户提供且无法更改(他们将此代码用于遗留应用程序)。 正如您在下面的代码中看到的那样,客户提供了一个密码短语,因此将使用 SecretKeySpec 方法生成密钥。
爪哇代码:
// Passphrase
private static final byte[] pass = new byte[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0','1', '2', '3', '4', '5' };
public static String encrypt(String Data) throws Exception {
Key key = generateKey();
Cipher c = Cipher.getInstance("AES/ECB/PKCS5Padding");
c.init(Cipher.ENCRYPT_MODE, key);
byte[] encVal = c.doFinal(Data.getBytes());
String encryptedValue = new BASE64Encoder().encode(encVal);
return encryptedValue;
}
public static String decrypt(String encryptedData) throws Exception {
Key key = generateKey();
Cipher c = Cipher.getInstance("AES/ECB/PKCS5Padding");
c.init(Cipher.DECRYPT_MODE, key);
byte[] decordedValue = new BASE64Decoder().decodeBuffer(encryptedData);
byte[] decValue = c.doFinal(decordedValue);
String decryptedValue = new String(decValue);
return decryptedValue;
}
private static Key generateKey() throws Exception {
Key key = new SecretKeySpec(pass, "AES");
return key;
}
我已经测试了几个命令,例如:
openssl enc -aes-128-ecb -a -salt -in file.xml -out file_enc.xml -pass pass:123456789012345
openssl enc -aes-128-ecb -a -nosalt -in file.xml -out file_enc.xml -pass pass:123456789012345
但是给定的输出中没有一个是使用 java 成功解密的。 出于测试目的,我使用给定的 java 代码进行加密,结果当然与来自 openssl 的结果不同。
有没有办法使用openssl C api或命令行来加密数据,以便使用给定的java代码成功解密?
要补充一点。 我正在努力解决同样的问题。 我能够使用以下设置从 Java 解密 AES-128 加密消息。
我使用openssl
来加密数据:
openssl enc -nosalt -aes-128-ecb -in data.txt -out crypted-aes.data -K 50645367566B59703373367639792442
正如@Daniel 所建议的那样,改变游戏规则的是使用-K
属性。 让我们解密生成文件的Java配置如下:
final byte[] aesKey = "PdSgVkYp3s6v9y$B".getBytes(StandardCharsets.UTF_8);
final SecretKeySpec aesKeySpec = new SecretKeySpec(aesKey, "AES");
Path path = Paths.get("src/test/resources/crypted-aes.data");
final byte[] cryptedData = Files.readAllBytes(path);
final Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, aesKeySpec);
final byte[] decryptedMsg = cipher.doFinal(cryptedData);
当十六进制密钥50645367566B59703373367639792442
、它的String
表示"PdSgVkYp3s6v9y$B"
和AES/ECB/PKCS5Padding
对齐时,魔法就会发生。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.