Class OFDDecryptor

java.lang.Object
org.ofdrw.crypto.OFDDecryptor
All Implemented Interfaces:
Closeable, AutoCloseable

public class OFDDecryptor extends Object implements Closeable
OFD解密器 — OFDEncryptor 的逆操作

将加密的 OFD 文件解密为明文 OFD 文件。解密流程:

  1. 解压加密 OFD 到工作目录
  2. 读取 Encryptions.xml,获取所有加密信息(支持多重加密)
  3. 对每个加密信息:加载密钥描述文件 → 匹配解密器恢复 FEK → 解密密文映射表 → 逐一解密文件
  4. 清理所有加密元数据(Encryptions.xml、decryptseed.dat、entriesmap.dat)
  5. 重新打包为明文 OFD

使用示例 — 口令解密:

    Path src = Paths.get("encrypted.ofd");
    Path out = Paths.get("decrypted.ofd");
    try (OFDDecryptor d = new OFDDecryptor(src, out)) {
        d.addUser(new UserPasswordDecryptor("张三", "12345678"));
        d.decrypt();
    }

支持多重加密(Encryptions.xml 包含多个 CT_EncryptInfo), 需为每个加密层提供对应的解密器。

Since:
2.4.0
Author:
权观宇
  • Constructor Details

    • OFDDecryptor

      public OFDDecryptor(Path src, Path dest) throws IOException
      创建 OFD 解密器(自动创建临时工作目录)

      工作目录由系统自动创建在系统临时目录下,close 时自动删除。

      Parameters:
      src - 加密的 OFD 文件路径,不能为空
      dest - 解密后 OFD 文件输出路径,不能为空
      Throws:
      IOException - 解压或文件操作异常
      IllegalArgumentException - src 或 dest 为 null 或不存在
    • OFDDecryptor

      public OFDDecryptor(Path src, Path dest, Path workDir) throws IOException
      创建 OFD 解密器(使用用户指定的工作目录)

      工作目录由调用者提供和管理,close 时 不会 删除该目录。 适用于需要保留中间文件进行调试,或工作目录有特殊位置要求的场景。

      注意:若指定的工作目录已存在且非空,其内容可能被覆盖。

      Parameters:
      src - 加密的 OFD 文件路径,不能为空
      dest - 解密后 OFD 文件输出路径,不能为空
      workDir - 用户指定的工作目录(若不存在则自动创建)
      Throws:
      IOException - 解压或文件操作异常
      IllegalArgumentException - src 为 null 或不存在,dest 为 null
  • Method Details

    • addUser

      public OFDDecryptor addUser(UserFEKDecryptor decryptor)
      添加解密用户

      解密时会用每个添加的解密器尝试匹配密钥描述文件中的 UserInfo。 建议先添加匹配概率最高的解密器以提高效率。

      Parameters:
      decryptor - 用户 FEK 解密器,不能为 null
      Returns:
      this(Fluent API)
    • decrypt

      public void decrypt() throws IOException, org.bouncycastle.crypto.CryptoException
      执行解密

      完整解密流程:

      1. 检查 Encryptions.xml 是否存在,不存在则直接打包退出
      2. 读取 Encryptions.xml → CT_EncryptInfo 列表
      3. 对每个 CT_EncryptInfo(支持多重加密):
        1. 读取 decryptseed.dat → 解析 DecyptSeed
        2. 用 UserFEKDecryptor 匹配 UserInfo → 恢复 FEK + IV
        3. 读取 entriesmap.dat → SM4-CBC 解密 → 解析 EncryptEntries
        4. 对每个 EncryptEntry:SM4-CBC 解密密文 → 写回明文路径 → 删除密文
        5. 删除 decryptseed.dat 和 entriesmap.dat
      4. 删除 Encryptions.xml
      5. 重新打包为明文 OFD 输出到 dest
      Throws:
      IOException - 文件读写异常
      org.bouncycastle.crypto.CryptoException - 解密失败(无匹配的解密器、密钥错误或数据损坏)
    • close

      public void close() throws IOException
      关闭解密器,清理临时文件

      若工作目录为本类自动创建(双参构造器),则删除整个工作目录; 若为用户指定(三参构造器),则保留工作目录。

      Specified by:
      close in interface AutoCloseable
      Specified by:
      close in interface Closeable
      Throws:
      IOException - 删除工作目录异常