我正在尝试通过 Ruby 中的密码“DES-EDE3-CBC”加密数据,然后在 Java 中解密加密数据。
这是我进行加密的Ruby代码:
require 'digest'
require 'openssl'
require 'base64'
ALG = "DES-EDE3-CBC"
key = "80f28a1ef4aa9df6ee2ee3210316b98f383eb344"
cipher = OpenSSL::Cipher::Cipher.new(ALG)
cipher.pkcs5_keyivgen(key, nil)
cipher.encrypt
data = "hello"
result = cipher.update(data)
result << cipher.final
# Write the data to file.
File.open("enc.txt", "wb"){|f| f.write result}
然后用Java解密:
import java.security.*;
import java.*;
import java.io.*;
import javax.crypto.*;
import javax.crypto.spec.*;
public class Test{
public static void main(String[] args) throws Exception {
String key = "80f28a1ef4aa9df6ee2ee3210316b98f383eb344";
// Init the key
DESKeySpec desKeySpec = new DESKeySpec(key.getBytes());
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
Key secretKey = keyFactory.generateSecret(desKeySpec);
Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] buf = new byte[1024];
InputStream input = new FileInputStream(new File("enc.txt"));
FileOutputStream output = new FileOutputStream(new File("dec.txt"));
int count = input.read(buf);
// Read and decrypt file content
while (count >= 0) {
output.write(cipher.update(buf, 0, count));
count = input.read(buf);
}
output.write(cipher.doFinal());
output.flush();
}
}
但是我在运行 Java 代码时总是遇到异常:
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.DESCipher.engineDoFinal(DESCipher.java:314)
at javax.crypto.Cipher.doFinal(Cipher.java:1969)
at Test.main(Test.java:29)
我认为问题在于 Ruby 中的“DES-EDE3-CBC”密码与 Java“DES/ECB/PKCS5Padding”不兼容。我该怎么做?