首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >基于Java代码的AES加密和OpenSSL解密(终端)

基于Java代码的AES加密和OpenSSL解密(终端)
EN

Stack Overflow用户
提问于 2019-03-26 20:12:02
回答 2查看 291关注 0票数 0

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

我试过这个命令

代码语言:javascript
复制
openssl enc -aes-256-cbc -d -in file_05.encrypt.txt -out file_05.decrypt.txt

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

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

代码语言:javascript
复制
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;
    }
EN

回答 2

Stack Overflow用户

发布于 2019-03-26 23:47:41

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

然后在终端中显示一个“坏的幻数”错误信息

默认情况下,Openssl使用其内部EVP_BytesToKey函数从提供的密码和盐生成密钥和IV。如果需要,只需在internet上搜索以查找Java实现。

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

我尝试从命令行使用OpenSSL对加密的文件进行解密,但我无法这样做

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

票数 1
EN

Stack Overflow用户

发布于 2019-03-26 22:37:38

看起来你遗漏了openssl期望的报头--字符串Salted__,后面是8字节的盐,然后是密文。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55356861

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档