Шифрование данных в базе данных PostgreSQL

В этом видео покажу как можно шифровать данные в базе данных --1) Создаем новую базу данных --2) Создаем таблички CREATE TABLE entity3 ( id serial PRIMARY KEY, encoded_data bytea ); CREATE TABLE entity2 ( id serial PRIMARY KEY, encoded_data bytea, reference_to_entity3 int REFERENCES entity3(id) ); CREATE TABLE entity1 ( id serial PRIMARY KEY, name varchar(255) NOT NULL, reference_to_entity2 int REFERENCES entity2(id) ); --3) Устанавливаем метод встроеной кодировки CREATE EXTENSION IF NOT EXISTS pgcrypto; --4) Заполняем таблички INSERT INTO entity3 (encoded_data) VALUES (pgp_sym_encrypt('Bob', 'secret')), (pgp_sym_encrypt('John', 'secret')), (pgp_sym_encrypt('Vasya', 'secret')), (pgp_sym_encrypt('Ronny', 'secret')), (pgp_sym_encrypt('Jina', 'secret')), (pgp_sym_encrypt('Sayat', 'secret')), (pgp_sym_encrypt('Oleg', 'secret')), (pgp_sym_encrypt('Max', 'secret')), (pgp_sym_encrypt('Sean', 'secret')), (pgp_sym_encrypt('Дмитрий', 'secret')); INSERT INTO entity2 (encoded_data, reference_to_entity3) VALUES (pgp_sym_encrypt('test1', 'secret'), 1), (pgp_sym_encrypt('test2', 'secret'), 2), (pgp_sym_encrypt('test3', 'secret'), 3), (pgp_sym_encrypt('test4', 'secret'), 4), (pgp_sym_encrypt('test5', 'secret'), 5), (pgp_sym_encrypt('test6', 'secret'), 6), (pgp_sym_encrypt('test7', 'secret'), 7), (pgp_sym_encrypt('test8', 'secret'), 8), (pgp_sym_encrypt('test9', 'secret'), 9), (pgp_sym_encrypt('test10', 'secret'), 10); INSERT INTO entity1 (name, reference_to_entity2) VALUES ('1', 1), ('2', 2), ('3', 3), ('4', 4), ('5', 5), ('6', 6), ('7', 7), ('8', 8), ('9', 9), ('10', 10); --5) Делаем запрос с базы данных и сразу же дишефруем закодированные данные SELECT e1.id, e1.name, pgp_sym_decrypt(e2.encoded_data, 'secret') AS decrypted_data_entity2, pgp_sym_decrypt(e3.encoded_data, 'secret') AS decrypted_data_entity3 FROM entity1 e1 JOIN entity2 e2 ON e1.reference_to_entity2 = e2.id JOIN entity3 e3 ON e2.reference_to_entity3 = e3.id WHERE e1.name = '1'; --Если убрать WHERE e1.name = '1'; то получим все данные с таблички 1 склеенной с данными 2 - 3 таблиц

Смотрите также