我需要使用 OpenSSL 和 Java 加密一个字符串,并让它们最终完全相同。
OpenSSL
openssl enc -aes-256-cbc -S THISISASECRETKEY -k ALSOISASECRETKEY -in $txtName -out $aesName -a
爪哇
import java.security.*;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import sun.misc.*;
public class Protector {
    private static final String ALGORITHM = "AES";
    private static final int ITERATIONS = 1;
    private static final byte[] keyValue = "ALSOISASECRETKEY".getBytes();
    public static String encrypt(String value, String salt) throws Exception {
        Key key = generateKey();
        Cipher c = Cipher.getInstance(ALGORITHM);
        c.init(Cipher.ENCRYPT_MODE, key);
        String valueToEnc = null;
        String eValue = value;
        for (int i = 0; i < ITERATIONS; i++) {
            valueToEnc = salt + eValue;
            byte[] encValue = c.doFinal(valueToEnc.getBytes());
            eValue = new BASE64Encoder().encode(encValue);
        }
        return eValue;
    }
    public static String decrypt(String value, String salt) throws Exception {
        Key key = generateKey();
        Cipher c = Cipher.getInstance(ALGORITHM);
        c.init(Cipher.DECRYPT_MODE, key);
        String dValue = null;
        String valueToDecrypt = value;
        for (int i = 0; i < ITERATIONS; i++) {
            byte[] decordedValue = new BASE64Decoder().decodeBuffer(valueToDecrypt);
            byte[] decValue = c.doFinal(decordedValue);
            dValue = new String(decValue).substring(salt.length());
            valueToDecrypt = dValue;
        }
        return dValue;
    }
    private static Key generateKey() throws Exception {
        Key key = new SecretKeySpec(keyValue, ALGORITHM);
        // SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM);
        // key = keyFactory.generateSecret(new DESKeySpec(keyValue));
        return key;
    }
}
和 Java 主要
public class main {
    public static void main(String[] args) throws Exception {
        String password = "This is a test!";
        String salt = "THISISASECRETKEY";
        String passwordEnc = Protector.encrypt(password, salt);
        String passwordDec = Protector.decrypt(passwordEnc, salt);
        System.out.println("Salt Text : " + salt);
        System.out.println("Plain Text : " + password);
        System.out.println("Encrypted : " + passwordEnc);
        System.out.println("Decrypted : " + passwordDec);
    }
} 
Java 代码产生一个结果,但它不匹配。我需要将我的 Java 代码与确实必须保持不变的 OpenSSL 相匹配(与已经设置了很多后端的其他人一起工作)。我在某处读到 OpenSSL 和 Java 生成密钥的方式有所不同,如果这有帮助的话。
非常感谢您!