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

我正在使用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命令编码的字符串吗?

非常感谢。

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

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

  • apache通用编解码器
  • 充气城堡

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

  1. 如果你真的不需要PBE,只需要一些 openssl加密, @ Artjom链接的问题有一个很好的答案:在openssl中使用“raw”密钥和IV,然后在Java中使用相同的密钥和IV。 让它们都默认为“PKCS5”(真正的PKCS#7)填充。 请注意, openssl enc以hexforms获取-K-iv ,而Java crypto将它们视为字节; 必要时转换。 从/如果您使用64-ed的密文,首先是de-base64; 这是在java8中提供的,并且有许多库可用于早期的Java版本。

否则,您需要解压缩文件格式。 在de-base64之后,丢弃前8个字节,将接下来的8个字节作为salt,将剩余的字节作为密文。

  1. 如果你需要特定算法AES128-CBC或192或256的PBE 你可以使用第三方加密库,即http://www.BouncyCastle.org ,它为这三种算法实现openssl PBE。 为PBEWITHMD5AND128BITAES-CBC-OPENSSL或192或256实例化SecretKeyFactory (但仅在安装了无限强度策略时)并为其指定PBEKeySpec ,其密钥为chars,salt和count为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

并使用密码作为字节,盐,迭代计数1,“MD5”以及输出数组(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