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

如何使用Rails credentials encryption加密生成可用加密凭证文件

在Ruby代码中调用Rails Credentials加密能力的实现方法

Rails内置的Credentials加密能力没有做CLI层面的调用限制,完全可以在自定义Ruby代码中直接调用,不需要依赖rails credentials系列命令行操作,具体实现方式如下:


核心依赖

Rails把凭证加密、解密、读写的完整逻辑封装在ActiveSupport::EncryptedConfiguration类中,只要加载了ActiveSupport(Rails项目默认已加载)就可以直接调用,不需要额外引入第三方gem。

可直接复用的加密方法

def encrypt_credential_file(plain_config_path, secret_key, output_enc_path)
  # 初始化加密配置实例
  encrypted_config = ActiveSupport::EncryptedConfiguration.new(
    config_path: output_enc_path,
    key: secret_key,
    env_key: "", # 传入空值跳过从环境变量读取密钥的逻辑
    raise_if_missing_key: true
  )

  # 读取明文凭证内容
  plain_content = File.read(plain_config_path)
  # 自动完成AES-256-GCM加密+签名写入文件
  encrypted_config.write(plain_content)

  # 写入后自动校验解密结果,确保生成的文件可用
  unless encrypted_config.read == plain_content
    raise "加密校验失败,生成的文件无法正常解密"
  end

  output_enc_path
end

调用示例

# 注意:secret_key必须为32字节长度,可通过SecureRandom.hex(16)生成符合规范的密钥
encrypt_credential_file(
  "/your/local/plain_credentials.yml",
  "your_32byte_length_encryption_key",
  Rails.root.join("config/credentials/custom.yml.enc").to_s
)

关键注意事项

  • 传入的密钥如果是Rails默认生成的16进制格式master key,直接传入即可,组件内部会自动完成解码适配,不需要手动转码
  • 该方法生成的加密文件和rails credentials:edit命令生成的文件格式完全兼容,后续可以直接通过Rails.application.encrypted(output_enc_path, key: secret_key)正常读取
  • 如果需要在非Rails项目中使用这套加密逻辑,可以直接依赖activesupport gem,用底层ActiveSupport::MessageEncryptor实现同规格加密,保证和Rails生态兼容:
    require "active_support"
    require "active_support/message_encryptor"
    
    encryptor = ActiveSupport::MessageEncryptor.new(
      [secret_key].pack("H*"),
      cipher: "aes-256-gcm"
    )
    encrypted_content = encryptor.encrypt_and_sign(File.read(plain_config_path))
    File.write(output_enc_path, encrypted_content)
    
  • 加密后的文件只要有任意字节改动,都会触发签名校验失败,无法正常解密,不要手动修改加密文件内容
  • 密钥需要单独存储,不要和加密后的凭证文件一同提交到代码仓库

内容的提问来源于stack exchange,提问作者Vedran Mijatović

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.03 10:42:51