Lockbox 开源项目教程
lockbox Modern encryption for Ruby and Rails 项目地址: https://gitcode.com/gh_mirrors/lo/lockbox
1. 项目介绍
Lockbox 是一个现代化的 Ruby 和 Rails 加密库,旨在为数据库字段、文件和字符串提供安全的加密功能。Lockbox 的设计目标是最大化与现有代码和库的兼容性,同时简化现有数据的迁移和密钥轮换过程。Lockbox 没有任何外部依赖,并且提供了多种集成选项,适用于不同的应用场景。
2. 项目快速启动
安装
首先,将 Lockbox 添加到你的 Rails 应用的 Gemfile 中:
gem "lockbox"
然后运行 bundle install
来安装 Lockbox。
密钥生成
生成一个密钥并将其存储在你的 Rails 应用的凭证中:
Lockbox.generate_key
将生成的密钥添加到你的 Rails 凭证中:
rails credentials:edit --environment <env>
在凭证文件中添加以下内容:
lockbox:
master_key: "0000000000000000000000000000000000000000000000000000000000000000"
加密数据库字段
创建一个迁移来添加加密字段:
class AddEmailCiphertextToUsers < ActiveRecord::Migration[7.2]
def change
add_column :users, :email_ciphertext, :text
end
end
在模型中添加加密字段:
class User < ApplicationRecord
has_encrypted :email
end
现在你可以像使用普通字段一样使用 email
字段:
User.create(email: "hi@example.org")
3. 应用案例和最佳实践
加密多个字段
你可以在一个模型中加密多个字段:
class User < ApplicationRecord
has_encrypted :email, :phone, :city
end
加密不同类型的字段
Lockbox 支持多种数据类型的加密:
class User < ApplicationRecord
has_encrypted :birthday, type: :date
has_encrypted :signed_at, type: :datetime
has_encrypted :active, type: :boolean
has_encrypted :salary, type: :integer
has_encrypted :latitude, type: :float
has_encrypted :longitude, type: :decimal
has_encrypted :video, type: :binary
has_encrypted :properties, type: :json
has_encrypted :settings, type: :hash
has_encrypted :messages, type: :array
has_encrypted :ip, type: :inet
end
迁移现有数据
Lockbox 可以轻松地加密现有数据:
class User < ApplicationRecord
has_encrypted :email, migrating: true
end
在 Rails 控制台中迁移数据:
Lockbox.migrate(User)
4. 典型生态项目
Active Storage
Lockbox 可以与 Active Storage 集成,加密上传的文件:
class User < ApplicationRecord
has_one_attached :license
encrypts_attached :license
end
CarrierWave
Lockbox 也可以与 CarrierWave 集成,加密上传的文件:
class LicenseUploader < CarrierWave::Uploader::Base
encrypt
end
通过这些集成,Lockbox 可以为你的 Rails 应用提供全面的加密解决方案,保护敏感数据的安全。
lockbox Modern encryption for Ruby and Rails 项目地址: https://gitcode.com/gh_mirrors/lo/lockbox
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考