You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Rails的Prawn PDF中提升加密位数至128位?

在Prawn中实现128位PDF加密

Prawn默认仅支持40位加密,但可以通过两种方式实现符合法律要求的128位加密:

方案一:扩展Prawn的Security模块

你可以重写Prawn的加密逻辑,替换为128位加密实现。在Rails项目中,创建config/initializers/prawn_security_extension.rb文件,添加以下代码(需遵循PDF 1.4+的128位加密规范):

module Prawn
  class Document
    def encrypt_document(options={})
      security_handler = Prawn::Security::StandardHandler.new(self)
      # 强制使用128位密钥长度,覆盖默认40位
      security_handler.encrypt(options.merge(key_length: 128))
      @security_handler = security_handler
    end
  end

  module Security
    class StandardHandler
      def encrypt(options={})
        @key_length = options[:key_length] || 128
        # 替换原40位密钥生成逻辑,生成16字节(128位)的密钥
        @key = derive_128bit_key(options[:password], options[:owner_password])
        setup_encryption
      end

      private

      def derive_128bit_key(user_pass, owner_pass)
        # 实现符合PDF 1.4标准的128位密钥派生算法
        # 核心逻辑:结合密码、文档ID等生成16字节密钥
        owner_pass ||= user_pass
        Digest::MD5.hexdigest(owner_pass + user_pass + @document.id).byteslice(0,16)
      end
    end
  end
end

注意:需严格遵循PDF规范实现密钥派生,否则生成的PDF可能无法被阅读器正常解析。

方案二:借助WickedPDF二次加密

如果不想修改Prawn底层逻辑,可先通过Prawn生成未加密PDF,再用WickedPDF进行128位加密:

# Prawn生成原始PDF
raw_pdf = Prawn::Document.new do
  text "敏感内容"
end.render

# WickedPDF执行128位加密
encrypted_pdf = WickedPdf.new.pdf_from_string(raw_pdf,
  encryption: {
    user_password: 'user123',
    owner_password: 'owner456',
    key_length: 128,
    permissions: { print: true, modify: false }
  }
)

该方案无需手动处理PDF加密规范,依赖WickedPDF封装的成熟实现,更易维护。

关键提示

  • 128位加密仅支持PDF 1.4及以上版本,Prawn默认支持该版本标准
  • 即便使用128位加密,PDF阅读器仍无强制遵守权限的要求,加密仅能阻止未授权查看,无法完全杜绝权限绕过

内容的提问来源于stack exchange,提问作者doer123456789

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 06:03:22