我在 Rails 应用程序中使用 Shrine 将文件上传到 Amazon S3。一些与 GDPR 合规性相关的用户文件,我需要实施客户端加密([Shrine 文档](https://github.com/shrinerb/shrine/blob/v2.16.0/doc/storage/s3.md#加密))。在 Shrine 文档中,您可以看到通过 AWS KMS 进行文件加密的信息,但没有关于解密的信息。
当我从 aws s3 下载文件时,如何解密文件?
这是我的代码:
config/initializers/shrine.rb - 在这个地方我为 Shrine 指定配置。
require 'shrine'
require 'shrine/storage/s3'
require 'shrine/storage/file_system'
class Shrine
plugin :activerecord
class << self
Aws::S3::Encryption::Client.extend Forwardable
Aws::S3::Encryption::Client.delegate(
[:head_object, :get_object, :config, :build_request] => :client
)
def s3_options_encrypted
{
prefix: 'encrypted',
region: ENV['AWS_REGION'],
bucket: ENV['AWS_BUCKET_NAME'] ,
endpoint: ENV['AWS_ENDPOINT'],
access_key_id: ENV['AWS_ACCESS_KEY_ID'],
secret_access_key: ENV['AWS_SECRET_ACCESS_KEY'],
upload_options: { acl: 'private' },
client: Aws::S3::Encryption::Client.new(kms_key_id: ENV['KMS_KEY_ID'])
}
end
def storages
{
cache: Shrine::Storage::FileSystem.new('public', prefix: 'cache_files'),
encrypted: Shrine::Storage::S3.new(**s3_options_encrypted)
}
end
end
end
模型/document.rb - 模型
class Document < ApplicationRecord
include DocumentsUploader::Attachment.new(:file, {store: :encrypted})
end
controllers/downloads_controller.rb - 在这个地方我正在下载文件并需要解密它。
class DownloadsController < ApplicationController
def documents
document = Document.find(id) if Document.exists?(id: params[:id])
if document.nil? || !document&.file
redirect_to root_path and return
end
temp_file = document.file.download
name = "#{document.name}.pdf"
type = 'application/pdf'
send_file temp_file, filename: name, type: type, disposition: 'attachment'
end
end