cipher只加密目录中的一个文件

yzuktlbb  于 2021-07-06  发布在  Java
关注(0)|答案(0)|浏览(177)

我正在编写一个程序,对文件目录进行加密和解密,并用加密文件替换它们。到目前为止,当目录中只有一个文件时,这个程序就可以工作了,但是超过这个值,它就不会加密任何其他文件了。该程序抱怨使用了相同的密钥或iv,但我们希望使用相同的密码对目录中的所有文件进行加密,根据文档,cipher.dofinal应该将密码重置回初始状态。还有其他与aes密钥的创建相关的代码,等等,但似乎工作正常。有人知道是什么导致了这个问题吗?

//Creates Cipher and encodes with the AES key
      Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
      cipher.init(Cipher.ENCRYPT_MODE, AESKey, spec);
      //write all files to directory
      File dir = new File(directory);
      if (dir.isDirectory()) {
        EncryptDirectory(dir, cipher);
      } else {
        System.out.println("Error: Directory Invalid");
        return;
      }
    }
  }
  static public void EncryptDirectory(File dir, Cipher cipher) throws Exception {
    String[] pathnames;
    pathnames = dir.list();
    for (String pathname : pathnames) {
      File dirFile = new File(dir.getAbsolutePath() + "/"+ pathname);
      if (dirFile.isDirectory()) {
        EncryptDirectory(dirFile, cipher);
      } else if (pathname.equals("keyfile") || pathname.equals("keyfile.sig")) {
        continue;
      } else {
        String newFile = dir.getAbsolutePath() + "/" + dirFile.getName() + ".ci"; // Not sure what this will be.
        // Error checking if file exists
        File newFileCreate = new File(newFile);
        if (!newFileCreate.createNewFile()) {
          newFileCreate.delete();
          newFileCreate.createNewFile();
        }
        FileOutputStream cipherFile = new FileOutputStream(newFileCreate);
        FileInputStream in = new FileInputStream(dir.getAbsolutePath() + "/"+ pathname);
        byte[] ibuf = new byte[1024];
        int len;
        while ((len = in.read(ibuf)) != -1) {
          byte[] obuf = cipher.update(ibuf, 0, len);
          if ( obuf != null ) {
            cipherFile.write(obuf);
          }
        }
        cipherFile.write(cipher.doFinal());
        cipherFile.close();
        in.close();
        if (!dirFile.delete()) {
          System.out.println("Error in deleting file.");
        }
      }
    }

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题