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

时间:2015-08-11 16:33:07

标签: java encryption openssl aes decode

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

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

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

到现在为止,我只需要使用openssl解码它,所以以下命令返回先前编码的字符串:

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

结果:stackoverflow

现在,我需要解码 java应用程序中的编码字符串。

我的问题是:

有人能为我提供一个简单的java类来解码用先前给定的openssl命令编码的字符串吗?

非常感谢。

2 个答案:

答案 0 :(得分:4)

使用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);
    }
}

使用以下依赖项来编译/运行它:

答案 1 :(得分:0)

默认情况下,

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

  1. 如果你真的不需要PBE,只有一些 openssl加密,the question linked by @Artjom有一个很好的答案:使用&#34; raw&#34; openssl中的key和IV,然后在Java中使用相同的密钥和IV。让他们都默认为&#34; PKCS5&#34; (真的是PKCS#7)填充。请注意,openssl enc以十六进制表示-K-iv,而Java加密表将它们作为字节;必要时转换。既然/如果您使用64-ed的密文,则首先取消de base64;这是在java8中提供的,并且有许多库可用于早期的Java版本。
  2. 否则您需要解压缩文件格式。在de-base64之后,丢弃前8个字节,将接下来的8个字节作为salt,将剩余的字节作为密文。

    1. 如果您需要特定算法AES128-CBC或192或256 的PBE,您可以使用第三方加密库http://www.BouncyCastle.org,它为这三个实现openssl PBE算法。为SecretKeyFactory实例化PBEWITHMD5AND128BITAES-CBC-OPENSSL - 或192或256,但仅在安装了无限强度策略(更新:或Oracle版本&gt; = 8u161或OpenJDK)时 - 并为其指定PBEKeySpec将键作为chars,salt和count为1,并将结果用于同一算法的Cipher

    2. 否则你必须自己做PBE。幸运的是(?)它非常简单。无论如何,请使用以下方法:

    3. 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); }

      并使用密码作为字节,盐,迭代计数1,&#34; MD5&#34;以及输出数组(AES密钥的正确大小(16,24或32字节))和AES IV(总是16字节)。分别在SecretKeySpecIvParameterSpec中使用Cipher进行(更正)AES/CBC/PKCS5Padding

      除此之外:您无法对字符串进行加密,只能字节(或更准确地说八位字节)。几乎所有系统上的C程序(包括openssl)都隐式地将字符串/字符以ASCII 方式转换为字节,但是使用ASCII集之外的任何字符可能会产生不一致和不可用的结果。 Java将字符串/字符视为 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