Last active
May 15, 2023 13:54
-
-
Save rponte/2cf7d3637cc2a50e1069bcd41e57b14b to your computer and use it in GitHub Desktop.
PostgreSQL: encrypting and decrypting (and Rails examples)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| -- first, install the pgcrypto module | |
| CREATE EXTENSION pgcrypto; | |
| -- this is how to use its crypto-functions and encoding the value into base64 (by default postgresql uses bytea) | |
| with sensitive_info (email, encrypted_email) as ( | |
| values ('[email protected]', 'ww0EBwMC1V/tU6ZYV3Nq0kEBz8iqdRYE0A/zL3dQ+du9Ex+GkSDzz3Llq8g1yCoa9XpNbhKzK7U5 | |
| b1EtUYzUMer8XSaCwdFSPKmbSfJo1btoSQ==') | |
| ) | |
| select encode(pgp_sym_encrypt(s.email, 'mySecretKey'), 'base64') as encrypted_data | |
| ,pgp_sym_decrypt(decode(s.encrypted_email, 'base64'), 'mySecretKey') as decrypted_data | |
| from sensitive_info s | |
| ; |
Author
Author
- Twitter thread: The RubyOnRails has implemented a good approach - Active Record Encryption:
class Person < ApplicationRecord
encrypts :name
encrypts :email_address, deterministic: true
end
# Person.find_by(name: "jorge") # doesn't work
# Person.find_by(email_address: "[email protected]") # works- Here you can check the guide: Active Record Encryption
- LockBox: Another RubyOnRails library that follows the same approach:
- Works with database fields, files, and strings
- Maximizes compatibility with existing code and libraries
- Makes migrating existing data and key rotation easy
- Has zero dependencies and many integrations
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
There're other alternatives in the application-level, such as:
@PrePersist,@PreUpdateand@PostLoadJPA listeners (it's enough for simple use cases)@PrePersist,@PreUpdateand@PostLoad@ColumnTranformerannotation and the underlying database cryptor functions@ColumnTranformerannotation