通过Java代码进行AES加密并使用OpenSSL(终端)进行解密

问题描述 投票:0回答:2

我可以使用下面提到的Java代码加密文件中的数据。但是当我尝试从命令行使用OpenSSL解密加密文件时,我无法做到这一点。

我试过这个命令

openssl enc -aes-256-cbc -d -in file_05.encrypt.txt -out file_05.decrypt.txt

它要求输入密码 - 输入aes-256-cbc解密密码:我输入密码为“helloworld”,

然后在终端中显示“错误的幻数”错误消息。

String pwd  = "helloworld";
String SALT_VALUE  = "12345@salt";
private String algorithm = "PBEWITHSHA256AND256BITAES-CBC-BC";


String finalTxt  = "Hi, Goof After noon All.";

char[] pwd = Crypt.password.toCharArray();

SecretKey originalKey = Crypt.generateSK(pwd);

byte[] cipherText = Crypt.encrypt(finalTxt.getBytes(),SALT_VALUE.getBytes(), originalKey);

public static SecretKey generateSK(char[] passPhrase) throws NoSuchAlgorithmException,
                                                             InvalidKeySpecException,
                                                             NoSuchPaddingException,
                                                             InvalidAlgorithmParameterException,
                                                             InvalidKeyException {

    PBEKeySpec pbeKeySpec = new PBEKeySpec(passPhrase);
    SecretKeyFactory secretKeyFactory;
    secretKeyFactory = SecretKeyFactory.getInstance(algorithm);
    return secretKeyFactory.generateSecret(pbeKeySpec);
}



public static byte[] encrypt(byte[] image, byte[] salt, SecretKey sKey) throws InvalidKeyException,
            IllegalBlockSizeException,
            BadPaddingException,
            InvalidKeySpecException,
            UnsupportedEncodingException,
            InvalidAlgorithmParameterException {
        Cipher cipher;
        try {
            cipher = getCipher(Cipher.ENCRYPT_MODE, salt, sKey);
            return cipher.doFinal(image);
        } catch (Exception e) {
            e.printStackTrace();

        }

        return null;
    }

private static Cipher getCipher(int mode, @NonNull byte[] salt, @NonNull SecretKey secretKey) throws Exception {
        PBEParameterSpec pbeParamSpecKey = new PBEParameterSpec(salt, 1000);
            Cipher cipher = Cipher.getInstance(algorithm);
            cipher.init(mode, secretKey, pbeParamSpecKey);
            return cipher;
    }
java android linux encryption command-line
2个回答
1
投票

它要求输入密码 - 输入aes-256-cbc解密密码:我输入密码为“helloworld”, 然后在终端中显示“错误的幻数”错误消息

Openssl默认使用其内部EVP_BytesToKey函数从提供的密码和salt生成密钥和IV。如果需要,只需在互联网上搜索即可找到Java实现。

默认情况下,如果您不直接提供密钥和IV,Openssl期望格式为Salted__<8bit_salt><ciphertext>

我尝试从命令行使用OpenSSL解密加密文件,然后我无法做到这一点

我不确定你的Crypt类是什么实现的,你可以尝试打印十六进制编码的密钥和iv。使用带参数-iv <hex_IV> -K <hex_key>的openssl可以直接提供IV和Key值来解密密文


0
投票

看起来你缺少openssl预期的标题 - 字符串Salted__,后跟8字节盐,然后是密文。

© www.soinside.com 2019 - 2024. All rights reserved.