如何使用 java 解码使用 openssl aes-128-cbc 编码的字符串?

How to decode a string encoded with openssl aes-128-cbc using java?

我正在使用 openssl 使用以下命令对 string 进行编码:

openssl enc -aes-128-cbc -a -salt -pass pass:mypassword <<< "Whosebug"

结果给我一个编码字符串:U2FsdGVkX187CGv6DbEpqh/L6XRKON7uBGluIU0nT3w=

到目前为止,我只需要使用 openssl 对其进行解码,因此以下命令 returns 之前编码的字符串:

 openssl enc -aes-128-cbc -a -salt -pass pass:mypassword -d <<< "U2FsdGVkX187CGv6DbEpqh/L6XRKON7uBGluIU0nT3w="

结果:Whosebug

现在,我需要在 java 应用程序.

中解码编码字符串

我的问题是:

有谁能给我提供一个简单的 java class 来解码用先前给出的 openssl 命令编码的字符串吗?

非常感谢。

openssl enc 默认使用(适度)非标准的基于密码的加密算法,以及自定义但简单的数据格式。

  1. 如果你真的不需要PBE,只有一些 openssl加密,the question linked by @Artjom有一个很好的答案:Use "raw" key and IV in openssl ,然后在 Java 中使用相同的密钥和 IV。并让它们都默认为 "PKCS5"(真正的 PKCS#7)填充。请注意,openssl enc 以十六进制表示 -K-iv,而 Java 加密将它们视为字节;根据需要进行转换。 Since/if 你对密文进行了 base64 编码,首先 de-base64;这在 java8 中提供,并且有许多库可用于早期 java 版本。

否则需要解压文件格式。 de-base64后,丢弃前8个字节,将后8个字节作为盐,其余字节作为密文。

  1. 如果您需要针对特定​​算法 AES128-CBC 或 192 或 256 的 PBE,您可以使用第三方加密库,即 http://www.BouncyCastle.org,它为这三种算法实现了 openssl PBE。为 PBEWITHMD5AND128BITAES-CBC-OPENSSL 实例化 SecretKeyFactory——或 192 或 256,但前提是安装了无限强度策略(更新:或 Oracle 版本 >= 8u161 或 OpenJDK)——并给它一个 PBEKeySpec键作为字符、盐和 1 的计数,并在相同算法的 Cipher 中使用结果。

  2. 否则你必须自己做PBE。幸运的是(?)这很简单。将以下方法放在方便的地方:

public static /*or as appropriate */ void opensslBytesToKey ( byte[] pass, byte[] salt /*or null*/, // inputs int iter, String hashname, // PBKDF1-ish byte[] key, byte[] iv /*or null*/ // outputs ) throws NoSuchAlgorithmException { MessageDigest md = MessageDigest.getInstance (hashname); byte[] temp = null, out = new byte[key.length+(iv!=null?iv.length:0)]; int outidx = 0; while(outidx < out.length){ if(temp!=null) md.update(temp); md.update(pass); if(salt!=null) md.update(salt); temp = md.digest(); for(int i=1; i<iter; i++) temp = md.digest (temp); int use = Math.min (out.length-outidx, temp.length); System.arraycopy (temp,0, out,outidx, use); outidx += use; } System.arraycopy (out,0, key,0, key.length); if(iv!=null) System.arraycopy (out,key.length, iv,0, iv.length); }

并使用字节形式的密码、salt、迭代计数 1、"MD5" 和大小适合您的 AES 密钥的输出数组(16、24 或 32 字节)和一个AES IV(始终为 16 字节)。在 SecretKeySpecIvParameterSpec 中分别使用 Cipher 用于(更正)AES/CBC/PKCS5Padding.

旁白:您不能像这样加密字符串,只能加密 字节 (或更确切地说 八位字节 )。 C 程序,包括 openssl,几乎在所有系统上都将 ASCII 中的 strings/characters 隐式转换为字节,但使用 ASCII 集之外的任何字符可能会产生不一致和无法使用的结果。 Java 将 strings/characters 视为 Unicode(或更确切地说是 UTF-16),并且 将它们与字节进行转换 主要是显式的;这种转换对于 ASCII 是可靠的(并且与 C 一致),但对于非 ASCII 字符可能会有所不同。

更新:OpenSSL 1.1.0 (2016-08) 将 enc PBE 的默认哈希从 MD5 更改为 SHA256。根据使用哪个版本的 OpenSSL 进行加密,或者是否使用了(以前未记录的)-md 选项,更改我的选项 3 中的调用。有关详细信息,请参阅(我的)https://crypto.stackexchange.com/questions/3298/is-there-a-standard-for-openssl-interoperable-aes-encryption/#35614

使用 Bouncy Castle 库解决了它。

代码如下:

package example;
import java.util.Arrays;

import org.apache.commons.codec.binary.Base64;
import org.bouncycastle.crypto.BufferedBlockCipher;
import org.bouncycastle.crypto.CipherParameters;
import org.bouncycastle.crypto.InvalidCipherTextException;
import org.bouncycastle.crypto.engines.AESEngine;
import org.bouncycastle.crypto.generators.OpenSSLPBEParametersGenerator;
import org.bouncycastle.crypto.modes.CBCBlockCipher;
import org.bouncycastle.crypto.paddings.BlockCipherPadding;
import org.bouncycastle.crypto.paddings.PKCS7Padding;
import org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher;

public class OpenSSLAesDecrypter
{
    private static final int AES_NIVBITS = 128; // CBC Initialization Vector (same as cipher block size) [16 bytes]

    private final int keyLenBits;

    public OpenSSLAesDecrypter(int nKeyBits)
    {
        this.keyLenBits = nKeyBits;
    }

    public byte[] decipher(byte[] pwd, byte[] src)
    {
        // openssl non-standard extension: salt embedded at start of encrypted file
        byte[] salt = Arrays.copyOfRange(src, 8, 16); // 0..7 is "SALTED__", 8..15 is the salt

        try
        {
            // Encryption algorithm. Note that the "strength" (bitsize) is controlled by the key object that is used.
            // Note that PKCS5 padding and PKCS7 padding are identical.
            BlockCipherPadding padding = new PKCS7Padding();
            BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine()), padding);

            CipherParameters params = getCipherParameters(pwd, salt);
            cipher.reset();
            cipher.init(false, params);

            int buflen = cipher.getOutputSize(src.length - 16);
            byte[] workingBuffer = new byte[buflen];
            int len = cipher.processBytes(src, 16, src.length - 16, workingBuffer, 0);
            len += cipher.doFinal(workingBuffer, len);

            // Note that getOutputSize returns a number which includes space for "padding" bytes to be stored in.
            // However we don't want these padding bytes; the "len" variable contains the length of the *real* data
            // (which is always less than the return value of getOutputSize.
            byte[] bytesDec = new byte[len];
            System.arraycopy(workingBuffer, 0, bytesDec, 0, len);
            return bytesDec;
        }
        catch (InvalidCipherTextException e)
        {
            System.err.println("Error: Decryption failed");
            return null;
        }
        catch (RuntimeException e)
        {
            System.err.println("Error: Decryption failed");
            return null;
        }
    }

    private CipherParameters getCipherParameters(byte[] pwd, byte[] salt)
    {
        // Use bouncycastle implementation of openssl non-standard (pwd,salt)->(key,iv) algorithm.
        // Note that if a "CBC" cipher is selected, then an IV is required as well as a key. When using a password,
        // Openssl
        // *derives* the IV from the (pwd,salt) pair at the same time as it derives the key.
        //
        // * PBE = Password Based Encryption
        // * CBC = Cipher Block Chaining (ie IV is needed)
        //
        // Note also that when the IV is derived from (pwd, salt) the salt **must** be different for each message; this is
        // the default for openssl - just make sure to NOT explicitly provide a salt, or encryption security is badly
        // affected.
        OpenSSLPBEParametersGenerator gen = new OpenSSLPBEParametersGenerator();
        gen.init(pwd, salt);
        CipherParameters cp = gen.generateDerivedParameters(keyLenBits, AES_NIVBITS);
        return cp;
    }

    public static void main(String[] args)
    {
        OpenSSLAesDecrypter d = new OpenSSLAesDecrypter(128);
        String r = new String(d.decipher("mypassword".getBytes(),
                Base64.decodeBase64("U2FsdGVkX187CGv6DbEpqh/L6XRKON7uBGluIU0nT3w=")));
        System.out.println(r);
    }
}

使用以下依赖项 compile/run 它: