DEV Community

丁久
丁久

Posted on • Originally published at dingjiu1989-hue.github.io

Database Encryption

This article was originally published on AI Study Room. For the full version with working code examples and related articles, visit the original post.

Database Encryption

Database Encryption

Database Encryption

Database Encryption

Database Encryption

Database Encryption

Database Encryption

Database Encryption

Database Encryption

Database Encryption Layers

Database encryption protects data at rest and in transit. Multiple layers provide defense in depth.

Transparent Data Encryption (TDE)

TDE encrypts the entire database at the storage layer:

\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\-- SQL Server TDE

CREATE DATABASE ENCRYPTION KEY

WITH ALGORITHM = AES_256

ENCRYPTION BY SERVER CERTIFICATE DatabaseCert;

ALTER DATABASE ProductionDB

SET ENCRYPTION ON;

\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\-- Check encryption status

SELECT DB_NAME(database_id) as DatabaseName,

encryption_state_desc,

percent_complete

FROM sys.dm_database_encryption_keys;

\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\-- PostgreSQL TDE (with pg_tde extension)

CREATE EXTENSION pg_tde;

SELECT pg_tde_add_database_key_provider(

'file-vault',

'{"type":"file","path":"/etc/postgresql/keys.json"}'

);

SELECT pg_tde_set_principal_key('production-db-key', 'file-vault');

Column-Level Encryption

Encrypt specific sensitive columns:

from cryptography.fernet import Fernet

import base64

class ColumnEncryptor:

def init(self, master_key):

self.fernet = Fernet(master_key)

def encrypt_column(self, value):

if value is None:

return None

return self.fernet.encrypt(value.encode()).decode()

def decrypt_column(self, encrypted_value):

if encrypted_value is None:

return None

return self.fernet.decrypt(encrypted_value.encode()).decode()

def searchable_encryption(self, value):

"""Deterministic encryption for searchable columns"""

from cryptography.hazmat.primitives import hashes

di


Read the full article on AI Study Room for complete code examples, comparison tables, and related resources.

Found this useful? Check out more developer guides and tool comparisons on AI Study Room.

Top comments (0)