如何使用从密码派生的密钥正确加密和解​​密文件

CHO*_*OCK 4 java encryption jce salt

我正在尝试使用“PBEWithHmacSHA256AndAES_256”标准制定正确的过程来加密和解密文件。

从我从 Oracle 的这个示例代码中了解到。

我收集到需要一个盐,以及一个迭代计数和哈希标准。

所以我有我的主要方法,传入加密方法:

  1. 用户定义的密码new String(key).toCharArray()作为字节数组(使用此方法进行其他加密运行)
  2. initVector作为字节数组的安全随机 IV
  3. 纯文本文件inputFile作为字符串
  4. 要创建的密文文件的名称outputFile作为字符串

我已经按照代码示例编写了我认为对加密方法正确的内容。我通过将它们附加到密文来存储用于解密的盐和 IV。

private static void encrypt(byte[] key, byte[] initVector, String inputFile, String outputFile) //exceptions for throws... {
    //Initalisation for encryption
    Cipher cipher;

    byte[] salt = new byte[16];

        SecureRandom rand = new SecureRandom();

        // Salt randomly generated with base64
        rand.nextBytes(salt);
        System.out.println("my salt should be" + Base64.getEncoder().encodeToString(salt));
        salt = Base64.getEncoder().encode(salt);

        // Iteration count
        int count = 1000;

        IvParameterSpec iv = new IvParameterSpec(initVector);
        
        // Create PBE parameter set
        PBEParameterSpec pbeParamSpec = new PBEParameterSpec(Base64.getDecoder().decode(salt), count, iv);                
        // Convert pass into SecretKey object
        PBEKeySpec pbeKeySpec = new PBEKeySpec(new String(key).toCharArray());
        SecretKeyFactory keyFac = SecretKeyFactory.getInstance("PBEWithHmacSHA256AndAES_256");
        SecretKey pbeKey;
        try {
            pbeKey = keyFac.generateSecret(pbeKeySpec);
        } catch (InvalidKeySpecException e) {
            System.out.println("Sorry, the password specified cannot be used as a secret key");
            System.out.println("Please check that your password uses valid characters");
            return;
        }

        // Create PBE Cipher
        cipher = Cipher.getInstance("PBEWithHmacSHA256AndAES_256");

        // Initialize PBE Cipher with key and parameters
        cipher.init(Cipher.ENCRYPT_MODE, pbeKey, pbeParamSpec);
    }

    //File error checking and file handling (i.e. generating file paths)...

    System.out.println("Secret key is " + Base64.getEncoder().encodeToString(key));
    System.out.println("IV is " + Base64.getEncoder().encodeToString(initVector));

    //Special file reading and writing with 'Cipher Stream'
    try (InputStream fin = FileEncryptor.class.getResourceAsStream(loadFile.getName());
            OutputStream fout = Files.newOutputStream(saveFile);

            CipherOutputStream cipherOut = new CipherOutputStream(fout, cipher) {
            }) {
        final byte[] bytes = new byte[1024];
        for(int length=fin.read(bytes); length!=-1; length = fin.read(bytes)){

                fout.write(initVector);
                fout.write(salt);

            cipherOut.write(bytes, 0, length);

        }
    } catch (IOException e) {
        System.out.println("Something went wrong with reading and writing these files!");
        System.out.println("Please check you have the latest version of this program");
        System.out.println("Contact your IT admin to make sure you have sufficient privileges");
    }
    System.out.println("SUCCESS! Encryption finished, saved at specified location");
}
Run Code Online (Sandbox Code Playgroud)

然后我还有我的main方法,传入解密方法:

  1. 用户定义的密码String inputKEY作为字符串(也将此方法用于其他 dencryption 运行)

  2. , 的字符串inputIV已作为 null 传入,因为未用于 PBE。

  3. 密文文件inputFile作为字符串

  4. 将要创建的显示纯文本文件的名称outputFile作为字符串

    私有静态无效解密(字符串输入密钥,字符串输入IV,字符串输入文件,字符串输出文件){密码密码=空;

     //File error checking and file handling (i.e. generating file paths)...
    
     InputStream encryptedData = Files.newInputStream(loadFilePath);
    
    
         PBEKeySpec pbeKeySpec = new PBEKeySpec(inputKEY.toCharArray());
         SecretKeyFactory keyFac = SecretKeyFactory.getInstance("PBEWithHmacSHA256AndAES_256");
         SecretKey pbeKey = null;
         try {
             pbeKey = keyFac.generateSecret(pbeKeySpec);
         } catch (InvalidKeySpecException e) {
             // TODO Auto-generated catch block
             e.printStackTrace();
         }
         byte[] initVect = new byte[16];
         encryptedData.read(initVect);
    
         IvParameterSpec iv = new IvParameterSpec(Base64.getDecoder().decode(initVect);
    
         byte[] salt = new byte[16];
         encryptedData.read(salt);
    
         PBEParameterSpec pbeParamSpec = new PBEParameterSpec(Base64.getDecoder().decode(salt), 1000, iv);  
         cipher = Cipher.getInstance("PBEWithHmacSHA256AndAES_256");
    
         System.out.println("my salt should be" + Base64.getEncoder().encodeToString(Base64.getDecoder().decode(salt)));
    
         cipher.init(Cipher.DECRYPT_MODE, pbeKey, pbeParamSpec); 
    
     try (CipherInputStream decryptStream = new CipherInputStream(encryptedData, cipher);    
             OutputStream decryptedOut = Files.newOutputStream(saveFile)){
         final byte[] bytes = new byte[1024];
         for(int length=decryptStream.read(bytes); length!=-1; length = decryptStream.read(bytes)){
             decryptedOut.write(bytes, 0, length);
         }
     } catch (IOException e) { //This is caught when decryption is run
         System.out.println("Something went wrong with reading and writing these files!");
         System.out.println("Please check you have the latest version of this program");
         System.out.println("Contact your IT admin to make sure you have sufficient privileges");
     }
    
     System.out.println("SUCESS! Decryption finished, saved at specified location");
    
    Run Code Online (Sandbox Code Playgroud)

    }

我相信我对 PBE 的理解有些不对,因此我实现它的方式可能是错误的。谁能指出似乎有什么问题?

Top*_*aco 8

主要问题是:

  • IV 和 Salt 不得写入for循环内。
  • IVencrypt不是用 Base64 编码存储的,而是用 Base64 解码的decrypt.
  • 16 个字节的盐存储在encrypt(不必要的)Base64 编码中,即存储了 24 个字节。在decrypt但是只有16字节加载。

还:

  • 在编码/解码时,有时不指定编码,因此使用默认编码。
  • encryptdecrypt为 key 和 IV 使用不同的参数类型。
  • 代码中有很多复制/粘贴错误。

注意:与您的代码相反,链接代码除了密钥之外还确定密码和盐的 IV。在您的代码中,IV 已通过。因此,您必须确保密钥/IV 对只能使用一次。通常为每个加密生成一个随机 IV。

在以下代码(基于您的代码,但为了简单起见,没有异常处理)中,这些问题已修复/优化。此外,代码适用FileInputStreamFileOutputStream而不是您的类(但这不是必需的):

private static void encrypt(String key, byte[] initVector, String inputFile, String outputFile) throws Exception {

    // Key
    PBEKeySpec pbeKeySpec = new PBEKeySpec(key.toCharArray());
    SecretKeyFactory keyFac = SecretKeyFactory.getInstance("PBEWithHmacSHA256AndAES_256");
    SecretKey pbeKey = keyFac.generateSecret(pbeKeySpec);

    // IV
    IvParameterSpec iv = new IvParameterSpec(initVector);

    // Salt
    SecureRandom rand = new SecureRandom();
    byte[] salt = new byte[16];
    rand.nextBytes(salt);

    // ParameterSpec
    int count = 1000; // should be larger, see Michael Fehr's comment
    PBEParameterSpec pbeParamSpec = new PBEParameterSpec(salt, count, iv);

    // Cipher
    Cipher cipher = Cipher.getInstance("PBEWithHmacSHA256AndAES_256");
    cipher.init(Cipher.ENCRYPT_MODE, pbeKey, pbeParamSpec);

    try (FileInputStream fin = new FileInputStream(inputFile);
         FileOutputStream fout = new FileOutputStream(outputFile);
         CipherOutputStream cipherOut = new CipherOutputStream(fout, cipher)) {
    
        // Write IV, Salt
        fout.write(initVector);
        fout.write(salt);
    
        // Encrypt
        final byte[] bytes = new byte[1024];
        for (int length = fin.read(bytes); length != -1; length = fin.read(bytes)) {
            cipherOut.write(bytes, 0, length);
        }
    } 
}
Run Code Online (Sandbox Code Playgroud)
private static void decrypt(String key, byte[] initVect, String inputFile, String outputFile) throws Exception {

    try (FileInputStream encryptedData = new FileInputStream(inputFile);
         FileOutputStream decryptedOut = new FileOutputStream(outputFile)) {

        // Key
        PBEKeySpec pbeKeySpec = new PBEKeySpec(key.toCharArray());
        SecretKeyFactory keyFac = SecretKeyFactory.getInstance("PBEWithHmacSHA256AndAES_256");
        SecretKey pbeKey = keyFac.generateSecret(pbeKeySpec);

        // Read IV
        if (initVect == null) {
            initVect = encryptedData.readNBytes(16);
        }
        IvParameterSpec iv = new IvParameterSpec(initVect);

        // Read salt
        byte[] salt = encryptedData.readNBytes(16);

        // ParameterSpec
        int count = 1000;
        PBEParameterSpec pbeParamSpec = new PBEParameterSpec(salt, count, iv);

        // Cipher
        Cipher cipher = Cipher.getInstance("PBEWithHmacSHA256AndAES_256");
        cipher.init(Cipher.DECRYPT_MODE, pbeKey, pbeParamSpec);

        try (CipherInputStream decryptStream = new CipherInputStream(encryptedData, cipher)) {
        
            // Decrypt
            final byte[] bytes = new byte[1024];
            for (int length = decryptStream.read(bytes); length != -1; length = decryptStream.read(bytes)) {
                decryptedOut.write(bytes, 0, length);
            }
        } 
    }
}
Run Code Online (Sandbox Code Playgroud)

编辑- 关于盐和 IV 的读取decrypt
正如GPI在他们的评论中指出的那样,FileInputStream.read(byte[] b)通常读取b.length字节,但这不能保证。更健壮的是确定读取数据的长度并在循环中调用该方法,直到数据完整。另一种选择是使用InputStream.readNBytes?(int len),它保证读取len字节(除非遇到流结束或抛出异常),正如Zabuzard所建议的那样。在代码中,现在使用了后者,read即被替换为readNBytes?.

  • +1。我不是加密专家,所以我不会判断它的安全性,但在 Java 级别,这对我来说看起来不错。一个小窍门是,我知道在我使用过的任何 JVM 实现中调用“read(buffer)”时,“FileInputStream”将“总是”(如果文件足够长)读取“buffer.length”字节。但事实并非*必须*如此。因此,在您的解密方法中,在读取 IV 和盐时,我肯定会编写样板以确保已读取实际的字节数。从安全角度来看,这也很棒,因为如果未达到预期的字节数,就会发生一些可疑的事情。 (3认同)
  • 或者使用“readNBytes”,那么您也将返回“N”字节。 (2认同)