Skip to content

Instantly share code, notes, and snippets.

@rponte
Last active May 15, 2023 13:54
Show Gist options
  • Select an option

  • Save rponte/2cf7d3637cc2a50e1069bcd41e57b14b to your computer and use it in GitHub Desktop.

Select an option

Save rponte/2cf7d3637cc2a50e1069bcd41e57b14b to your computer and use it in GitHub Desktop.
PostgreSQL: encrypting and decrypting (and Rails examples)
-- 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
;
@rponte
Copy link
Author

rponte commented Sep 2, 2020

@rponte
Copy link
Author

rponte commented Mar 11, 2021

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

@rponte
Copy link
Author

rponte commented Mar 11, 2021

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment