簡體   English   中英

解密使用 openssl 和 aes-cbc-256 加密的文件

[英]Decrypt file encrypted using openssl with aes-cbc-256

我已經使用以下命令加密了一個文件

openssl rand 32 > test.key

openssl enc -aes-256-cbc -iter 10000 -pbkdf2 -salt -in test.txt -out test.txt.enc -pass file:test.key

現在我正在嘗試使用 java 對其進行解密。 從最近幾天開始嘗試,但沒有成功。

任何人都可以幫忙嗎?

我的代碼

package test;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.security.GeneralSecurityException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.io.IOUtils;

public class OpenSSlDecryptor {
    private static final Charset ASCII = Charset.forName("ASCII");
    private static final int INDEX_KEY = 0;
    private static final int INDEX_IV = 1;
    private static final int ITERATIONS = 10000;

    private static final int ARG_INDEX_FILENAME = 0;
    private static final int ARG_INDEX_PASSWORD = 1;

    private static final int SALT_OFFSET = 8;
    private static final int SALT_SIZE = 8;
    private static final int CIPHERTEXT_OFFSET = SALT_OFFSET + SALT_SIZE;

    private static final int KEY_SIZE_BITS = 256;

    /**
     * Thanks go to Ola Bini for releasing this source on his blog.
     * The source was obtained from <a href="http://olabini.com/blog/tag/evp_bytestokey/">here</a> .
     */
    public static byte[][] EVP_BytesToKey(final int key_len, final int iv_len, final MessageDigest md,
            final byte[] salt, final byte[] data, final int count) {
        final byte[][] both = new byte[2][];
        final byte[] key = new byte[key_len];
        int key_ix = 0;
        final byte[] iv = new byte[iv_len];
        int iv_ix = 0;
        both[0] = key;
        both[1] = iv;
        byte[] md_buf = null;
        int nkey = key_len;
        int niv = iv_len;
        int i = 0;
        if (data == null) {
            return both;
        }
        int addmd = 0;
        for (;;) {
            md.reset();
            if (addmd++ > 0) {
                md.update(md_buf);
            }
            md.update(data);
            if (null != salt) {
                md.update(salt, 0, 8);
            }
            md_buf = md.digest();
            for (i = 1; i < count; i++) {
                md.reset();
                md.update(md_buf);
                md_buf = md.digest();
            }
            i = 0;
            if (nkey > 0) {
                for (;;) {
                    if (nkey == 0) {
                      break;
                    }
                    if (i == md_buf.length) {
                      break;
                    }
                    key[key_ix++] = md_buf[i];
                    nkey--;
                    i++;
                }
            }
            if (niv > 0 && i != md_buf.length) {
                for (;;) {
                    if (niv == 0) {
                      break;
                    }
                    if (i == md_buf.length) {
                      break;
                    }
                    iv[iv_ix++] = md_buf[i];
                    niv--;
                    i++;
                }
            }
            if (nkey == 0 && niv == 0) {
                break;
            }
        }
        for (i = 0; i < md_buf.length; i++) {
            md_buf[i] = 0;
        }
        return both;
    }


    public static void main(final String[] args) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException {
     final String fileName = "test.txt.enc";

      final File f = new File(fileName );
      try {
            // --- read base 64 encoded file ---

            List<String> lines = new ArrayList<>();

            try (BufferedReader br = new BufferedReader(new FileReader(f))) {
              //br returns as stream and convert it into a List
              lines = br.lines().collect(Collectors.toList());

          } catch (final IOException e) {
              e.printStackTrace();
          }

            final StringBuilder sb = new StringBuilder();
            for (final String line : lines) {
                sb.append(line.trim());
            }


            final String random_bin_key = "test.key";
            final byte[] passwordKey = IOUtils.toByteArray(new FileInputStream(random_bin_key));

            // --- extract salt & encrypted ---
            final byte[] headerSaltAndCipherText = sb.toString().getBytes();
            // header is "Salted__", ASCII encoded, if salt is being used (the default)
            final byte[] salt = Arrays.copyOfRange(
                    headerSaltAndCipherText, SALT_OFFSET, SALT_OFFSET + SALT_SIZE);
            final byte[] encrypted = Arrays.copyOfRange(
                    headerSaltAndCipherText, CIPHERTEXT_OFFSET, headerSaltAndCipherText.length);

            // --- specify cipher and digest for EVP_BytesToKey method ---

            final Cipher aesCBC = Cipher.getInstance("AES/CBC/PKCS5Padding");
            final MessageDigest md5 = MessageDigest.getInstance("MD5");

            // --- create key and IV  ---

            // the IV is useless, OpenSSL might as well have use zero's
            final byte[][] keyAndIV = EVP_BytesToKey(
                    KEY_SIZE_BITS / Byte.SIZE,
                    aesCBC.getBlockSize(),
                    md5,
                    salt,
                    passwordKey,
                    ITERATIONS);
            final SecretKeySpec key = new SecretKeySpec(keyAndIV[INDEX_KEY], "AES");
            final IvParameterSpec iv = new IvParameterSpec(keyAndIV[INDEX_IV]);

            // --- initialize cipher instance and decrypt ---

            aesCBC.init(Cipher.DECRYPT_MODE, key, iv);
            final byte[] decrypted = aesCBC.doFinal(encrypted);
            final String answer = new String(decrypted);
            System.out.println(answer);
        } catch (final BadPaddingException e) {
           System.out.println(e.getMessage());
        } catch (final IllegalBlockSizeException e) {
          System.out.println(e.getMessage());
        } catch (final GeneralSecurityException e) {
          System.out.println(e.getMessage());
        } catch (final IOException e) {
          System.out.println(e.getMessage());
        }
}

我得到的錯誤

Given final block not properly padded. Such issues can arise if a bad key is used during decryption.

我參考了以下鏈接

https://raymii.org/s/tutorials/Encrypt_and_decrypt_files_to_public_keys_via_the_OpenSSL_Command_Line.html

https://community.cloudera.com/t5/Support-Questions/How-do-I-decrypt-AES-256-CBC-data-in-HDF-if-it-was-encrypted/td-p/97961#

試過

` final Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
    // strip off the salt and iv
    final ByteBuffer buffer = ByteBuffer.wrap(encryptedText);
    byte[] saltBytes = new byte[16];
    buffer.get(saltBytes, 0, saltBytes.length);
    saltBytes =  Arrays.copyOfRange(saltBytes, 8, 16);
    final byte[] ivBytes1 = new byte[cipher.getBlockSize()];
    buffer.get(ivBytes1, 0, ivBytes1.length);
    final int length = buffer.capacity() - 16 - ivBytes1.length;
    // length = length+ 16 -(length%16);
    final byte[] encryptedTextBytes = new byte[length];

    buffer.get(encryptedTextBytes);
    // Deriving the key
     final SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
     final PBEKeySpec spec = new PBEKeySpec(new String(password).toCharArray(), saltBytes, 10000,
    256);
     final SecretKey secretKey = factory.generateSecret(spec);
     final SecretKeySpec secret = new SecretKeySpec(secretKey.getEncoded(), "AES");
    cipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(ivBytes1));
    byte[] decryptedTextBytes = null;
    try {
      decryptedTextBytes = cipher.doFinal(encryptedTextBytes);
    } catch (final IllegalBlockSizeException e) {
      e.printStackTrace();
    } catch (final BadPaddingException e) {
      e.printStackTrace();
    }

獲取 badpadding 異常

嘗試使用PBKDF2WithHmacSHA256仍然收到錯誤

你有幾個問題。 最明顯的是您正在嘗試從文件中讀取 IV,但openssl enc在其默認的基於密碼的模式下從密碼和鹽中派生密鑰和 IV - 即使使用 PBKDF2。 但是,Java 中的標准(Sun/Oracle/OpenJDK)和 BouncyCastle 提供程序都實現了 PBKDF2 以僅派生一個密鑰——它在PBES2中的使用方式。

即使沒有這個,您將“密碼”生成為隨機字節的方法也不起作用。 PKCS5 標准實際上定義了 PBKDF2 來取密碼為

一個任意長度的八位組字符串,其作為文本字符串的解釋是未指定的。 然而,為了互操作性,建議應用程序遵循一些常見的文本編碼規則。 ASCII 和 UTF-8 [RFC3629] 是兩種可能性。 (ASCII 是 UTF-8 的子集。)

Many systems take interoperable encoding more seriously, and Java in particular (which was designed from its inception to be worldwide) defines PBEKeySpec to contain characters -- char[] in Java is UTF-16 -- which are encoded as UTF-8 when doing PBKDF2. 相比之下openssl是一個 C 程序,可以追溯到世紀之交之前,當時 C 開始承認除了美國以外的國家存在字節,因此它只知道其他字節EBCDIC,但可能根本不是字符,當然也不是那些不適合一個字節的奇怪外來字符。 32 個隨機字節序列有效 UTF-8 的概率非常低; 對我來說,分析計算的工作量太大,但我對 1 億個隨機值進行了測試,結果只有一個可以與你的方案配合使用。 (我打算測試十億,但厭倦了等待。)

另外,由於密碼應該是文本, openssl讀取 -pass -pass file:作為文本文件並將其視為字符串。 這意味着如果任何隨機字節是 null 字節或對應於換行符的字節,則文件中的其余數據將被丟棄並忽略密鑰和 IV 派生。 對於隨機的 32 字節值,這將平均大約 4 次出現,大約 20 次中的 1 次會在文件中發生得足夠早,以使結果在密碼學上很弱且易破解。

這就提出了一點:你為什么要使用基於密碼的加密? 如果您的“密鑰”是來自一個體面的安全 RNG 的 32 個字節openssl rand是——你不需要加強它,它已經作為一個有效的密鑰。 您可以使用openssl enc進行基於密鑰的加密,而不是基於密碼的加密,並且在 Java 中更高效、更安全、更容易——這是一個巨大的勝利。 如果您為每個加密使用一個新的隨機密鑰,您甚至不必使用真正的 IV,您可以像我在下面所做的那樣使用零 IV。 但是,如果您要重用/任何密鑰,則需要為每次加密使用唯一且不可預測的(通常是隨機的)IV,並將其與數據一起傳送,也許只需將其放在前面即可。

因此,無論如何,這是一個相當簡單的ZD52387880EE1EA22817A72D3759213819Z程序,可以處理任何一種情況:Z50955D4B2031271F8FDDA1764C1A6666ACIBIE的exey eimny ins of ze emem pdbkf2 eque ness of'passect and password99666666Acibile Inspect ofers'password99 expassion'passpers和密碼。 IV 為零的演示):

//nopackage
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.security.*;
import java.util.*;
import javax.crypto.*;
import javax.crypto.spec.*;

public class SO61613286 {
    static public void main (String[] args) throws Exception /* let JVM give error */{
        // arguments: P/K, filename output from openssl enc, filename of text pw or binary key
        byte[] file = Files.readAllBytes(Paths.get(args[1])); 
        byte[] fil2 = Files.readAllBytes(Paths.get(args[2])); 
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");

        if( args[0].startsWith("P") ){
            // possibly truncate 'password' in fil2
            int n = 0; for( ; n < fil2.length; n++ ) if( fil2[n]==0 || fil2[n]=='\n' ) break;
            if( n < fil2.length ) fil2 = Arrays.copyOf(fil2, n);
            // extract salt and derive ...
            byte[] salt = Arrays.copyOfRange(file, 8, 16);
            byte[] derive = PBKDF2 ("HmacSHA256", fil2, salt, 10000, 48);
            // ... key is first 32, IV is last 16
            cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(derive,0,32,"AES"), new IvParameterSpec(derive,32,16));
            // remainder of file is ciphertext
            System.out.write( cipher.doFinal(file,16,file.length-16) );
        }else{
            // just use fil2 as key and zeros for IV ...
            cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(fil2,"AES"), new IvParameterSpec(new byte[16]));
            // ... all of file is ciphertext
            System.out.write( cipher.doFinal(file,0,file.length) );
            // !!!if key will be reused, must use better IVs and transmit with the data!!!
        }
    }
    public static byte[] PBKDF2 (String prf, byte[] pass, byte[] salt, int iter, int len)
            throws NoSuchProviderException, NoSuchAlgorithmException, InvalidKeyException {
        byte[] result = new byte[len];
        Mac mac = Mac.getInstance(prf);
        mac.init (new SecretKeySpec (pass,prf));
        byte[] saltcnt = Arrays.copyOf (salt, salt.length+4);
        while( /*remaining*/len>0 ){
            for( int o = saltcnt.length; --o>=saltcnt.length-4; ) if( ++saltcnt[o] != 0 ) break; 
            byte[] u = saltcnt, x = new byte[mac.getMacLength()];
            for( int i = 1; i <= iter; i++ ){
                u = mac.doFinal (u); 
                for( int o = 0; o < x.length; o++ ) x[o] ^= u[o];
            }
            int len2 = Math.min (len, x.length);
            System.arraycopy (x,0, result,result.length-len, len2);
            len -= len2;
        }
        return result;
    }
    public static void testutf8 (){
        Random r = new Random();
        byte[] t = new byte[32];
        for( int i = 0; i < 1000000000; i++ ){
            r.nextBytes(t); 
            if( Arrays.equals(new String (t, StandardCharsets.UTF_8).getBytes(StandardCharsets.UTF_8), t) ) 
                System.out.println(i+" "+Arrays.toString(t));
            if( i % 1000000 == 999999 ) System.out.println (i);
        }
    }
}

和一個演示:

$ openssl rand 32 >SO61613286.rnd   # repeated several times until I got this:
$ xxd SO61613286.rnd   # notice the null byte
0000000: ab1a 1384 9238 0900 c947 6b9a c23d 5ee0  .....8...Gk..=^.
0000010: 32f0 6b2f 91ec 2dd9 a69d eb7d e00e 37ff  2.k/..-....}..7.
$
$ echo the name of the cat >SO61613286.in
$
$ openssl aes-256-cbc -in SO61613286.in -out SO61613286.enc1 -pass file:SO61613286.rnd -pbkdf2 -iter 10000
$ java8 -cp . SO61613286 P SO61613286.enc1 SO61613286.rnd
the name of the cat
$
$ openssl aes-256-cbc -in SO61613286.in -out SO61613286.enc2 -K $(xxd -p -c32 SO61613286.rnd) -iv 00
hex string is too short, padding with zero bytes to length
$ # that's a warning and can be ignored, as long as we don't need real IVs (see above)
$ java8 -cp . SO61613286 K SO61613286.enc2 SO61613286.rnd      
the name of the cat
$

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM