[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"project-8070":3},{"id":4,"name":5,"fullName":6,"owner":7,"repo":5,"description":8,"homepage":9,"htmlUrl":10,"language":11,"languages":10,"totalLinesOfCode":10,"stars":12,"forks":13,"watchers":14,"openIssues":15,"contributorsCount":16,"subscribersCount":16,"size":16,"stars1d":16,"stars7d":16,"stars30d":16,"stars90d":16,"forks30d":16,"starsTrendScore":16,"compositeScore":17,"rankGlobal":10,"rankLanguage":10,"license":18,"archived":19,"fork":19,"defaultBranch":20,"hasWiki":21,"hasPages":19,"topics":22,"createdAt":10,"pushedAt":10,"updatedAt":23,"readmeContent":24,"aiSummary":25,"trendingCount":16,"starSnapshotCount":16,"syncStatus":26,"lastSyncTime":27,"discoverSource":28},8070,"attr_encrypted","attr-encrypted\u002Fattr_encrypted","attr-encrypted","Generates attr_accessors that encrypt and decrypt attributes","",null,"Ruby",2017,421,38,70,0,29.88,"MIT License",false,"master",true,[],"2026-06-12 02:01:48","# attr_encrypted\n\n![workflow](https:\u002F\u002Fgithub.com\u002Fattr-encrypted\u002Fattr_encrypted\u002Factions\u002Fworkflows\u002FCI.yml\u002Fbadge.svg) [![Gem Version](https:\u002F\u002Fbadge.fury.io\u002Frb\u002Fattr_encrypted.svg)](https:\u002F\u002Fbadge.fury.io\u002Frb\u002Fattr_encrypted)\n\nGenerates attr_accessors that transparently encrypt and decrypt attributes.\n\nIt works with ANY class, however, you get a few extra features when you're using it with `ActiveRecord` or `Sequel`.\n\n## Installation\n\nAdd attr_encrypted to your gemfile:\n\n```ruby\n  gem \"attr_encrypted\"\n```\n\nThen install the gem:\n\n```bash\n  bundle install\n```\n\n## Usage\n\nIf you're using an ORM like `ActiveRecord` or `Sequel`, using attr_encrypted is easy:\n\n```ruby\n  class User\n    attr_encrypted :ssn, key: 'This is a key that is 256 bits!!'\n  end\n```\n\nIf you're using a PORO, you have to do a little bit more work by extending the class:\n\n```ruby\n  class User\n    extend AttrEncrypted\n    attr_accessor :name\n    attr_encrypted :ssn, key: 'This is a key that is 256 bits!!'\n\n    def load\n      # loads the stored data\n    end\n\n    def save\n      # saves the :name and :encrypted_ssn attributes somewhere (e.g. filesystem, database, etc)\n    end\n  end\n\n  user = User.new\n  user.ssn = '123-45-6789'\n  user.ssn # returns the unencrypted object ie. '123-45-6789'\n  user.encrypted_ssn # returns the encrypted version of :ssn\n  user.save\n\n  user = User.load\n  user.ssn # decrypts :encrypted_ssn and returns '123-45-6789'\n```\n\n### Encrypt\u002Fdecrypt attribute class methods\n\nTwo class methods are available for each attribute: `User.encrypt_email` and `User.decrypt_email`. They accept as arguments the same options that the `attr_encrypted` class method accepts. For example:\n\n```ruby\n  key = SecureRandom.random_bytes(32)\n  iv = SecureRandom.random_bytes(12)\n  encrypted_email = User.encrypt_email('test@test.com', iv: iv, key: key)\n  email = User.decrypt_email(encrypted_email, iv: iv, key: key)\n```\n\nThe `attr_encrypted` class method is also aliased as `attr_encryptor` to conform to Ruby's `attr_` naming conventions. I should have called this project `attr_encryptor` but it was too late when I realized it ='(.\n\n### attr_encrypted with database persistence\n\nBy default, `attr_encrypted` uses the `:per_attribute_iv` encryption mode. This mode requires a column to store your cipher text and a column to store your IV (initialization vector).\n\nCreate or modify the table that your model uses to add a column with the `encrypted_` prefix (which can be modified, see below), e.g. `encrypted_ssn` via a migration like the following:\n\n```ruby\n  create_table :users do |t|\n    t.string :name\n    t.string :encrypted_ssn\n    t.string :encrypted_ssn_iv\n    t.timestamps\n  end\n```\n\nYou can use a string or binary column type. (See the encode option section below for more info)\n\nIf you use the same key for each record, add a unique index on the IV. Repeated IVs with AES-GCM (the default algorithm) allow an attacker to recover the key.\n\n```ruby\n  add_index :users, :encrypted_ssn_iv, unique: true\n```\n\n### Specifying the encrypted attribute name\n\nBy default, the encrypted attribute name is `encrypted_#{attribute}` (e.g. `attr_encrypted :email` would create an attribute named `encrypted_email`). So, if you're storing the encrypted attribute in the database, you need to make sure the `encrypted_#{attribute}` field exists in your table. You have a couple of options if you want to name your attribute or db column something else, see below for more details.\n\n\n## attr_encrypted options\n\n#### Options are evaluated\nAll options will be evaluated at the instance level. If you pass in a symbol it will be passed as a message to the instance of your class. If you pass a proc or any object that responds to `:call` it will be called. You can pass in the instance of your class as an argument to the proc. Anything else will be returned. For example:\n\n##### Symbols representing instance methods\n\nHere is an example class that uses an instance method to determines the encryption key to use.\n\n```ruby\n  class User\n    attr_encrypted :email, key: :encryption_key\n\n    def encryption_key\n      # does some fancy logic and returns an encryption key\n    end\n  end\n```\n\n\n##### Procs\n\nHere is an example of passing a proc\u002Flambda object as the `:key` option as well:\n\n```ruby\n  class User\n    attr_encrypted :email, key: proc { |user| user.key }\n  end\n```\n\n\n### Default options\n\nThe following are the default options used by `attr_encrypted`:\n\n```ruby\n  prefix:            'encrypted_',\n  suffix:            '',\n  if:                true,\n  unless:            false,\n  encode:            false,\n  encode_iv:         true,\n  encode_salt:       true,\n  default_encoding:  'm',\n  marshal:           false,\n  marshaler:         Marshal,\n  dump_method:       'dump',\n  load_method:       'load',\n  encryptor:         Encryptor,\n  encrypt_method:    'encrypt',\n  decrypt_method:    'decrypt',\n  mode:              :per_attribute_iv,\n  algorithm:         'aes-256-gcm',\n  allow_empty_value: false\n```\n\nAll of the aforementioned options are explained in depth below.\n\nAdditionally, you can specify default options for all encrypted attributes in your class. Instead of having to define your class like this:\n\n```ruby\n  class User\n    attr_encrypted :email, key: 'This is a key that is 256 bits!!', prefix: '', suffix: '_crypted'\n    attr_encrypted :ssn, key: 'a different secret key', prefix: '', suffix: '_crypted'\n    attr_encrypted :credit_card, key: 'another secret key', prefix: '', suffix: '_crypted'\n  end\n```\n\nYou can simply define some default options like so:\n\n```ruby\n  class User\n    attr_encrypted_options.merge!(prefix: '', :suffix => '_crypted')\n    attr_encrypted :email, key: 'This is a key that is 256 bits!!'\n    attr_encrypted :ssn, key: 'a different secret key'\n    attr_encrypted :credit_card, key: 'another secret key'\n  end\n```\n\nThis should help keep your classes clean and DRY.\n\n### The `:attribute` option\n\nYou can simply pass the name of the encrypted attribute as the `:attribute` option:\n\n```ruby\n  class User\n    attr_encrypted :email, key: 'This is a key that is 256 bits!!', attribute: 'email_encrypted'\n  end\n```\n\nThis would generate an attribute named `email_encrypted`\n\n\n### The `:prefix` and `:suffix` options\n\nIf you don't like the `encrypted_#{attribute}` naming convention then you can specify your own:\n\n```ruby\n  class User\n    attr_encrypted :email, key: 'This is a key that is 256 bits!!', prefix: 'secret_', suffix: '_crypted'\n  end\n```\n\nThis would generate the following attribute: `secret_email_crypted`.\n\n\n### The `:key` option\n\nThe `:key` option is used to pass in a data encryption key to be used with whatever encryption class you use. If you're using `Encryptor`, the key must meet minimum length requirements respective to the algorithm that you use; aes-256 requires a 256 bit key, etc. The `:key` option is not required (see custom encryptor below).\n\n\n##### Unique keys for each attribute\n\nYou can specify unique keys for each attribute if you'd like:\n\n```ruby\n  class User\n    attr_encrypted :email, key: 'This is a key that is 256 bits!!'\n    attr_encrypted :ssn, key: 'a different secret key'\n  end\n```\n\nIt is recommended to use a symbol or a proc for the key and to store information regarding what key was used to encrypt your data. (See below for more details.)\n\n\n### The `:if` and `:unless` options\n\nThere may be times that you want to only encrypt when certain conditions are met. For example maybe you're using rails and you don't want to encrypt attributes when you're in development mode. You can specify conditions like this:\n\n```ruby\n  class User \u003C ActiveRecord::Base\n    attr_encrypted :email, key: 'This is a key that is 256 bits!!', unless: Rails.env.development?\n    attr_encrypted :ssn, key: 'This is a key that is 256 bits!!', if: Rails.env.development?\n  end\n```\n\nYou can specify both `:if` and `:unless` options.\n\n\n### The `:encryptor`, `:encrypt_method`, and `:decrypt_method` options\n\nThe `Encryptor` class is used by default. You may use your own custom encryptor by specifying the `:encryptor`, `:encrypt_method`, and `:decrypt_method` options.\n\nLets suppose you'd like to use this custom encryptor class:\n\n```ruby\n  class SillyEncryptor\n    def self.silly_encrypt(options)\n      (options[:value] + options[:secret_key]).reverse\n    end\n\n    def self.silly_decrypt(options)\n      options[:value].reverse.gsub(\u002F#{options[:secret_key]}$\u002F, '')\n    end\n  end\n```\n\nSimply set up your class like so:\n\n```ruby\n  class User\n    attr_encrypted :email, secret_key: 'This is a key that is 256 bits!!', encryptor: SillyEncryptor, encrypt_method: :silly_encrypt, decrypt_method: :silly_decrypt\n  end\n```\n\nAny options that you pass to `attr_encrypted` will be passed to the encryptor class along with the `:value` option which contains the string to encrypt\u002Fdecrypt. Notice that the above example uses `:secret_key` instead of `:key`. See [encryptor](https:\u002F\u002Fgithub.com\u002Fattr-encrypted\u002Fencryptor) for more info regarding the default encryptor class.\n\n\n### The `:mode` option\n\nThe mode options allows you to specify in what mode your data will be encrypted. There are currently three modes: `:per_attribute_iv`, `:per_attribute_iv_and_salt`, and `:single_iv_and_salt`.\n\n__NOTE: `:per_attribute_iv_and_salt` and `:single_iv_and_salt` modes are deprecated and will be removed in the next major release.__\n\n\n### The `:algorithm` option\n\nThe default `Encryptor` class uses the standard ruby OpenSSL library. Its default algorithm is `aes-256-gcm`. You can modify this by passing the `:algorithm` option to the `attr_encrypted` call like so:\n\n```ruby\n  class User\n    attr_encrypted :email, key: 'This is a key that is 256 bits!!', algorithm: 'aes-256-cbc'\n  end\n```\n\nTo view a list of all cipher algorithms that are supported on your platform, run the following code in your favorite Ruby REPL:\n\n```ruby\n  require 'openssl'\n  puts OpenSSL::Cipher.ciphers\n```\nSee [Encryptor](https:\u002F\u002Fgithub.com\u002Fattr-encrypted\u002Fencryptor#algorithms) for more information.\n\n\n### The `:encode`, `:encode_iv`, `:encode_salt`, and `:default_encoding` options\n\nYou're probably going to be storing your encrypted attributes somehow (e.g. filesystem, database, etc). You can simply pass the `:encode` option to automatically encode\u002Fdecode when encrypting\u002Fdecrypting. The default behavior assumes that you're using a string column type and will base64 encode your cipher text. If you choose to use the binary column type then encoding is not required, but be sure to pass in `false` with the `:encode` option.\n\n```ruby\n  class User\n    attr_encrypted :email, key: 'some secret key', encode: true, encode_iv: true, encode_salt: true\n  end\n```\n\nThe default encoding is `m` (base64). You can change this by setting `encode: 'some encoding'`. See [`Array#pack`](http:\u002F\u002Fruby-doc.org\u002Fcore-2.3.0\u002FArray.html#method-i-pack) for more encoding options.\n\n\n### The `:marshal`, `:dump_method`, and `:load_method` options\n\nYou may want to encrypt objects other than strings (e.g. hashes, arrays, etc). If this is the case, simply pass the `:marshal` option to automatically marshal when encrypting\u002Fdecrypting.\n\n```ruby\n  class User\n    attr_encrypted :credentials, key: 'some secret key', marshal: true\n  end\n```\n\nYou may also optionally specify `:marshaler`, `:dump_method`, and `:load_method` if you want to use something other than the default `Marshal` object.\n\n### The `:allow_empty_value` option\n\nYou may want to encrypt empty strings or nil so as to not reveal which records are populated and which records are not.\n\n```ruby\n  class User\n    attr_encrypted :credentials, key: 'some secret key', marshal: true, allow_empty_value: true\n  end\n```\n\n\n## ORMs\n\n### ActiveRecord\n\nIf you're using this gem with `ActiveRecord`, you get a few extra features:\n\n#### Default options\n\nThe `:encode` option is set to true by default.\n\n#### Dynamic `find_by_` and `scoped_by_` methods\n\nLet's say you'd like to encrypt your user's email addresses, but you also need a way for them to login. Simply set up your class like so:\n\n```ruby\n  class User \u003C ActiveRecord::Base\n    attr_encrypted :email, key: 'This is a key that is 256 bits!!'\n    attr_encrypted :password, key: 'some other secret key'\n  end\n```\n\nYou can now lookup and login users like so:\n\n```ruby\n  User.find_by_email_and_password('test@example.com', 'testing')\n```\n\nThe call to `find_by_email_and_password` is intercepted and modified to `find_by_encrypted_email_and_encrypted_password('ENCRYPTED EMAIL', 'ENCRYPTED PASSWORD')`. The dynamic scope methods like `scoped_by_email_and_password` work the same way.\n\nNOTE: This only works if all records are encrypted with the same encryption key (per attribute).\n\n__NOTE: This feature is deprecated and will be removed in the next major release.__\n\n\n### Sequel\n\n#### Default options\n\nThe `:encode` option is set to true by default.\n\n\n## Deprecations\n\nattr_encrypted v2.0.0 now depends on encryptor v2.0.0. As part of both major releases many insecure defaults and behaviors have been deprecated. The new default behavior is as follows:\n\n* Default `:mode` is now `:per_attribute_iv`, the default `:mode` in attr_encrypted v1.x was `:single_iv_and_salt`.\n* Default `:algorithm` is now 'aes-256-gcm', the default `:algorithm` in attr_encrypted v1.x was 'aes-256-cbc'.\n* The encryption key provided must be of appropriate length respective to the algorithm used. Previously, encryptor did not verify minimum key length.\n* The dynamic finders available in ActiveRecord will only work with `:single_iv_and_salt` mode. It is strongly advised that you do not use this mode. If you can search the encrypted data, it wasn't encrypted securely. This functionality will be deprecated in the next major release.\n* `:per_attribute_iv_and_salt` and `:single_iv_and_salt` modes are deprecated and will be removed in the next major release.\n\nBackwards compatibility is supported by providing a special option that is passed to encryptor, namely, `:insecure_mode`:\n\n```ruby\n  class User\n    attr_encrypted :email, key: 'a secret key', algorithm: 'aes-256-cbc', mode: :single_iv_and_salt, insecure_mode: true\n  end\n```\n\nThe `:insecure_mode` option will allow encryptor to ignore the new security requirements. It is strongly advised that if you use this older insecure behavior that you migrate to the newer more secure behavior.\n\n\n## Upgrading from attr_encrypted v1.x to v3.x\n\nModify your gemfile to include the new version of attr_encrypted:\n\n```ruby\n  gem attr_encrypted, \"~> 3.0.0\"\n```\n\nThe update attr_encrypted:\n\n```bash\n  bundle update attr_encrypted\n```\n\nThen modify your models using attr\\_encrypted to account for the changes in default options. Specifically, pass in the `:mode` and `:algorithm` options that you were using if you had not previously done so. If your key is insufficient length relative to the algorithm that you use, you should also pass in `insecure_mode: true`; this will prevent Encryptor from raising an exception regarding insufficient key length. Please see the Deprecations sections for more details including an example of how to specify your model with default options from attr_encrypted v1.x.\n\n## Upgrading from attr_encrypted v2.x to v3.x\n\nA bug was discovered in Encryptor v2.0.0 that incorrectly set the IV when using an AES-\\*-GCM algorithm. Unfornately fixing this major security issue results in the inability to decrypt records encrypted using an AES-*-GCM algorithm from Encryptor v2.0.0. Please see [Upgrading to Encryptor v3.0.0](https:\u002F\u002Fgithub.com\u002Fattr-encrypted\u002Fencryptor#upgrading-from-v200-to-v300) for more info.\n\nIt is strongly advised that you re-encrypt your data encrypted with Encryptor v2.0.0. However, you'll have to take special care to re-encrypt. To decrypt data encrypted with Encryptor v2.0.0 using an AES-\\*-GCM algorithm you can use the `:v2_gcm_iv` option.\n\nIt is recommended that you implement a strategy to insure that you do not mix the encryption implementations of Encryptor. One way to do this is to re-encrypt everything while your application is offline.Another way is to add a column that keeps track of what implementation was used. The path that you choose will depend on your situtation. Below is an example of how you might go about re-encrypting your data.\n\n```ruby\n  class User\n    attr_encrypted :ssn, key: :encryption_key, v2_gcm_iv: is_decrypting?(:ssn)\n\n    def is_decrypting?(attribute)\n      attr_encrypted_encrypted_attributes[attribute][:operation] == :decrypting\n    end\n  end\n\n  User.all.each do |user|\n    old_ssn = user.ssn\n    user.ssn= old_ssn\n    user.save\n  end\n```\n\n## Things to consider before using attr_encrypted\n\n#### Searching, joining, etc\nWhile choosing to encrypt at the attribute level is the most secure solution, it is not without drawbacks. Namely, you cannot search the encrypted data, and because you can't search it, you can't index it either. You also can't use joins on the encrypted data. Data that is securely encrypted is effectively noise. So any operations that rely on the data not being noise will not work. If you need to do any of the aforementioned operations, please consider using database and file system encryption along with transport encryption as it moves through your stack.\n\n#### Data leaks\nPlease also consider where your data leaks. If you're using attr_encrypted with Rails, it's highly likely that this data will enter your app as a request parameter. You'll want to be sure that you're filtering your request params from your logs or else your data is sitting in the clear in your logs. [Parameter Filtering in Rails](http:\u002F\u002Fapidock.com\u002Frails\u002FActionDispatch\u002FHttp\u002FFilterParameters) Please also consider other possible leak points.\n\n#### Storage requirements\nWhen storing your encrypted data, please consider the length requirements of the db column that you're storing the cipher text in. Older versions of Mysql attempt to 'help' you by truncating strings that are too large for the column. When this happens, you will not be able to decrypt your data. [MySQL Strict Trans](http:\u002F\u002Fwww.davidpashley.com\u002F2009\u002F02\u002F15\u002Fsilently-truncated\u002F)\n\n#### Metadata regarding your crypto implementation\nIt is advisable to also store metadata regarding the circumstances of your encrypted data. Namely, you should store information about the key used to encrypt your data, as well as the algorithm. Having this metadata with every record will make key rotation and migrating to a new algorithm signficantly easier. It will allow you to continue to decrypt old data using the information provided in the metadata and new data can be encrypted using your new key and algorithm of choice.\n\n#### Enforcing the IV as a nonce\nOn a related note, most algorithms require that your IV be unique for every record and key combination. You can enforce this using composite unique indexes on your IV and encryption key name\u002Fid column. [RFC 5084](https:\u002F\u002Ftools.ietf.org\u002Fhtml\u002Frfc5084#section-1.5)\n\n#### Unique key per record\nLastly, while the `:per_attribute_iv_and_salt` mode is more secure than `:per_attribute_iv` mode because it uses a unique key per record, it uses a PBKDF function which introduces a huge performance hit (175x slower by my benchmarks). There are other ways of deriving a unique key per record that would be much faster.\n\n## Note on Patches\u002FPull Requests\n\n* Fork the project.\n* Make your feature addition or bug fix.\n* Add tests for it. This is important so I don't break it in a\n  future version unintentionally.\n* Commit, do not mess with rakefile, version, changelog, or history.\n* Send me a pull request. Bonus points for topic branches.\n","attr_encrypted 是一个 Ruby 宝石，用于生成能够透明地加密和解密属性的 attr_accessors。其核心功能是为任意类提供加密解密支持，特别在与 ActiveRecord 或 Sequel 结合使用时，提供了额外的功能如数据库持久化支持。该库支持多种加密模式，默认采用 per_attribute_iv 模式，需要为每个加密属性存储密文及初始化向量（IV）。它非常适合需要对敏感数据进行保护的应用场景，例如用户信息中的社保号、电子邮件等字段的加密处理。通过简单的配置即可实现数据的安全存储与访问，同时保持代码的简洁性。",2,"2026-06-11 03:15:55","top_language"]