SECTION 1: LEARNING OBJECTIVES

By the end of this lesson, you will be able to:

  • Understand the importance of data protection in digital banking.

  • Identify the key data protection principles – confidentiality, integrity, availability.

  • Apply encryption techniques – symmetric, asymmetric, and hashing.

  • Implement data masking and tokenisation for sensitive data.

  • Understand data loss prevention (DLP) in banking.

  • Manage encryption keys securely.

  • Measure data protection effectiveness using key metrics.

  • Develop a data protection strategy for a digital bank.


SECTION 2: DATA PROTECTION PRINCIPLES

2.1 The Data Protection Lifecycle
text
┌─────────────────────────────────────────────────────────────────────────────┐
│                    DATA PROTECTION LIFECYCLE                              │
├─────────────────────────────────────────────────────────────────────────────┤
│                                                                             │
│  ┌──────────────────────────────────────────────────────────────────────┐   │
│  │                    DATA CREATION                                    │   │
│  │  (Collect, generate, acquire)                                      │   │
│  └──────────────────────────────────────────────────────────────────────┘   │
│                                    │                                        │
│                                    v                                        │
│  ┌──────────────────────────────────────────────────────────────────────┐   │
│  │                    DATA CLASSIFICATION                              │   │
│  │  (Sensitive, confidential, public)                                 │   │
│  └──────────────────────────────────────────────────────────────────────┘   │
│                                    │                                        │
│                                    v                                        │
│  ┌──────────────────────────────────────────────────────────────────────┐   │
│  │                    DATA STORAGE                                     │   │
│  │  (Encrypt at rest, secure storage)                                 │   │
│  └──────────────────────────────────────────────────────────────────────┘   │
│                                    │                                        │
│                                    v                                        │
│  ┌──────────────────────────────────────────────────────────────────────┐   │
│  │                    DATA USAGE                                       │   │
│  │  (Access control, masking, tokenisation)                           │   │
│  └──────────────────────────────────────────────────────────────────────┘   │
│                                    │                                        │
│                                    v                                        │
│  ┌──────────────────────────────────────────────────────────────────────┐   │
│  │                    DATA SHARING                                     │   │
│  │  (Encryption in transit, secure transfer)                          │   │
│  └──────────────────────────────────────────────────────────────────────┘   │
│                                    │                                        │
│                                    v                                        │
│  ┌──────────────────────────────────────────────────────────────────────┐   │
│  │                    DATA RETENTION & DISPOSAL                        │   │
│  │  (Retention policies, secure deletion)                              │   │
│  └──────────────────────────────────────────────────────────────────────┘   │
│                                                                             │
└─────────────────────────────────────────────────────────────────────────────┘
2.2 Data Classification in Banking
 
 
Classification Description Examples
Public Publicly available information. Annual reports, marketing materials.
Internal Internal use only. Policies, procedures, internal memos.
Confidential Sensitive business information. Financial data, strategy documents.
Highly Confidential Customer data, credentials. Customer PII, account details, credentials.
Restricted Regulatory-protected data. Payment card data, health records.

SECTION 3: ENCRYPTION TECHNOLOGIES

3.1 Types of Encryption
 
 
Type Description Banking Application
Symmetric Encryption Same key for encryption/decryption. AES-256 for data at rest.
Asymmetric Encryption Public/private key pair. Digital signatures, key exchange.
Hashing One-way encryption. Password storage, integrity checks.
Tokenisation Replace sensitive data with tokens. Card data, PII.
Format-Preserving Encryption Encrypt data while preserving format. Credit card numbers, IDs.
3.2 Symmetric Encryption – AES
text
┌─────────────────────────────────────────────────────────────────────────────┐
│                    SYMMETRIC ENCRYPTION FLOW                              │
├─────────────────────────────────────────────────────────────────────────────┤
│                                                                             │
│  ┌─────────────┐    ┌─────────────┐    ┌─────────────┐                    │
│  │  Plaintext  │ ─→ │  Encryption │ ─→ │  Ciphertext │                    │
│  │  (Data)     │    │  (AES-256)  │    │  (Encrypted)│                    │
│  └─────────────┘    └─────────────┘    └─────────────┘                    │
│                          │                                                  │
│                          v                                                  │
│                    ┌─────────────┐                                         │
│                    │  Secret Key │                                         │
│                    └─────────────┘                                         │
│                          │                                                  │
│                          v                                                  │
│  ┌─────────────┐    ┌─────────────┐    ┌─────────────┐                    │
│  │  Plaintext  │ ← │  Decryption │ ← │  Ciphertext │                    │
│  │  (Data)     │    │  (AES-256)  │    │  (Encrypted)│                    │
│  └─────────────┘    └─────────────┘    └─────────────┘                    │
│                                                                             │
└─────────────────────────────────────────────────────────────────────────────┘
3.3 Hashing for Data Integrity
 
 
Hash Algorithm Output Size Strength Banking Use
MD5 128 bits Weak (broken). Not recommended.
SHA-1 160 bits Weak (broken). Not recommended.
SHA-256 256 bits Strong. Password hashing, integrity checks.
SHA-512 512 bits Very strong. High-security applications.
bcrypt Variable Strong. Password hashing.
Argon2 Variable Strongest. Modern password hashing.

SECTION 4: DATA MASKING AND TOKENISATION

4.1 Data Masking
 
 
Type Description Banking Example
Static Masking Permanently mask data. Test environments.
Dynamic Masking Mask data at query time. User-specific data views.
Static Data Masking Replace sensitive data. Development data.
Format-Preserving Masking Mask while preserving format. Credit card numbers.
4.2 Tokenisation
 
 
Aspect Description Banking Application
Definition Replace sensitive data with tokens. Card payments, PII.
Benefits Reduces PCI DSS scope. Payment security.
Token Types One-time, reusable, vault-based. Different use cases.
Vault Storage Securely store original data. Token mapping.

SECTION 5: KEY MANAGEMENT

5.1 Key Management Principles
 
 
Principle Description Implementation
Secure Storage Protect keys from unauthorised access. HSM, Key Management Service.
Key Rotation Regularly rotate keys. Automated rotation.
Least Privilege Limit key access. IAM, RBAC.
Audit Track key usage. Logging, monitoring.
Backup Securely back up keys. Disaster recovery.
Lifecycle Management Manage keys from creation to destruction. Key lifecycle policies.
5.2 Key Management Options
 
 
Option Description Banking Use
HSM (Hardware Security Module) Physical device for key storage. Highest security.
KMS (Key Management Service) Cloud-based key management. AWS KMS, Azure Key Vault.
Software-Based Software key management. Lower security.
Hybrid Combination of HSM and KMS. Most banking environments.

SECTION 6: IMPLEMENTATION IN PYTHON – DATA PROTECTION TOOLS

python
# ===================================================================
# MODULE 5, LESSON 5: DATA PROTECTION AND ENCRYPTION
# ===================================================================

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import hashlib
import base64
import json
from cryptography.fernet import Fernet
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
import warnings
warnings.filterwarnings('ignore')

print("="*70)
print("DATA PROTECTION AND ENCRYPTION IN BANKING")
print("="*70)

# ----------------------------------------------------------------
# PART A: DATA CLASSIFICATION FRAMEWORK
# ----------------------------------------------------------------

print("\n" + "-"*60)
print("PART A: Data Classification Framework")
print("-"*60)

class DataClassification:
    """Simulate a data classification framework."""
    
    classifications = {
        'Public': {'color': 'green', 'description': 'Publicly available information'},
        'Internal': {'color': 'blue', 'description': 'Internal use only'},
        'Confidential': {'color': 'orange', 'description': 'Sensitive business information'},
        'Highly Confidential': {'color': 'red', 'description': 'Customer data, credentials'},
        'Restricted': {'color': 'darkred', 'description': 'Regulatory-protected data'}
    }
    
    @staticmethod
    def classify_data(data_type, context=''):
        """Classify data based on type and context."""
        # Simple classification rules
        if 'public' in data_type.lower():
            return 'Public'
        elif 'pii' in data_type.lower() or 'customer' in data_type.lower():
            return 'Highly Confidential'
        elif 'payment' in data_type.lower() or 'card' in data_type.lower():
            return 'Restricted'
        elif 'financial' in data_type.lower() or 'strategy' in data_type.lower():
            return 'Confidential'
        else:
            return 'Internal'

# Test data classification
data_types = ['Customer Name', 'Credit Card Number', 'Annual Report', 'Financial Strategy', 'Internal Memo']
for data_type in data_types:
    classification = DataClassification.classify_data(data_type)
    print(f"  {data_type}: {classification}")

# ----------------------------------------------------------------
# PART B: ENCRYPTION IMPLEMENTATION
# ----------------------------------------------------------------

print("\n" + "-"*60)
print("PART B: Encryption Implementation")
print("-"*60)

class EncryptionService:
    """Simulate encryption services for banking."""
    
    def __init__(self, key=None):
        if key:
            self.key = key
        else:
            self.key = Fernet.generate_key()
        self.cipher = Fernet(self.key)
    
    def encrypt(self, data):
        """Encrypt data using AES-256 (Fernet)."""
        if isinstance(data, str):
            data = data.encode()
        return self.cipher.encrypt(data)
    
    def decrypt(self, encrypted_data):
        """Decrypt data."""
        return self.cipher.decrypt(encrypted_data)
    
    def hash_password(self, password):
        """Hash a password using SHA-256."""
        salt = b'salt_'  # In production, use a random salt
        kdf = PBKDF2HMAC(
            algorithm=hashes.SHA256(),
            length=32,
            salt=salt,
            iterations=100000,
        )
        key = base64.urlsafe_b64encode(kdf.derive(password.encode()))
        return key.decode()
    
    def verify_password(self, password, hashed_password):
        """Verify a password against its hash."""
        # In production, use proper verification
        return self.hash_password(password) == hashed_password

# Create encryption service
encryption_service = EncryptionService()

# Test encryption
original_data = "Customer Account Balance: $10,000.00"
encrypted = encryption_service.encrypt(original_data)
decrypted = encryption_service.decrypt(encrypted)

print("Encryption Test:")
print(f"  Original: {original_data}")
print(f"  Encrypted (base64): {base64.b64encode(encrypted).decode()[:50]}...")
print(f"  Decrypted: {decrypted.decode()}")

# Test password hashing
password = "SecurePassword123"
hashed_password = encryption_service.hash_password(password)
print(f"\nPassword Hashing Test:")
print(f"  Password: {password}")
print(f"  Hashed: {hashed_password[:30]}...")
print(f"  Verify: {encryption_service.verify_password(password, hashed_password)}")

# ----------------------------------------------------------------
# PART C: DATA MASKING SIMULATION
# ----------------------------------------------------------------

print("\n" + "-"*60)
print("PART C: Data Masking Simulation")
print("-"*60)

class DataMasking:
    """Simulate data masking for sensitive information."""
    
    @staticmethod
    def mask_credit_card(card_number):
        """Mask a credit card number."""
        if len(card_number) >= 16:
            return f"XXXX-XXXX-XXXX-{card_number[-4:]}"
        return "XXXX-XXXX-XXXX-XXXX"
    
    @staticmethod
    def mask_email(email):
        """Mask an email address."""
        parts = email.split('@')
        if len(parts) >= 2:
            return f"{parts[0][:2]}*****@{parts[1]}"
        return email
    
    @staticmethod
    def mask_phone(phone):
        """Mask a phone number."""
        if len(phone) >= 10:
            return f"XXX-XXX-{phone[-4:]}"
        return "XXX-XXX-XXXX"
    
    @staticmethod
    def mask_name(name):
        """Mask a name."""
        parts = name.split()
        if len(parts) >= 2:
            return f"{parts[0][0]}. {parts[-1]}"
        return f"{name[0]}. ****"

# Test data masking
sensitive_data = {
    'Credit Card': '4111-1111-1111-1111',
    'Email': 'john.doe@email.com',
    'Phone': '555-123-4567',
    'Name': 'John Smith'
}

print("Data Masking Examples:")
for label, value in sensitive_data.items():
    masked = {
        'Credit Card': DataMasking.mask_credit_card,
        'Email': DataMasking.mask_email,
        'Phone': DataMasking.mask_phone,
        'Name': DataMasking.mask_name
    }[label](value)
    print(f"  {label}: {value} -> {masked}")

# ----------------------------------------------------------------
# PART D: TOKENISATION SIMULATION
# ----------------------------------------------------------------

print("\n" + "-"*60)
print("PART D: Tokenisation Simulation")
print("-"*60)

class TokenisationService:
    """Simulate a tokenisation service."""
    
    def __init__(self):
        self.vault = {}
        self.token_counter = 0
    
    def tokenize(self, sensitive_data):
        """Tokenize sensitive data."""
        self.token_counter += 1
        token = f"TOK_{self.token_counter:08d}"
        self.vault[token] = sensitive_data
        return token
    
    def detokenize(self, token):
        """Retrieve original data from token."""
        return self.vault.get(token, None)

# Test tokenisation
token_service = TokenisationService()

card_data = "4111-1111-1111-1111"
token = token_service.tokenize(card_data)
retrieved = token_service.detokenize(token)

print("Tokenisation Test:")
print(f"  Original Card: {card_data}")
print(f"  Token: {token}")
print(f"  Retrieved: {retrieved}")

# ----------------------------------------------------------------
# PART E: DATA PROTECTION METRICS
# ----------------------------------------------------------------

print("\n" + "-"*60)
print("PART E: Data Protection Metrics")
print("-"*60)

protection_metrics = pd.DataFrame({
    'Metric': [
        'Data Classification Coverage',
        'Encryption (Data at Rest)',
        'Encryption (Data in Transit)',
        'Data Masking Coverage',
        'Tokenisation Coverage',
        'Key Management Compliance',
        'DLP Coverage',
        'Data Breach Incidents'
    ],
    'Current Value': [
        '65%',
        '82%',
        '95%',
        '45%',
        '55%',
        '72%',
        '40%',
        '3/month'
    ],
    'Target Value': [
        '> 95%',
        '> 99%',
        '> 99%',
        '> 80%',
        '> 80%',
        '> 95%',
        '> 80%',
        '0/month'
    ],
    'Status': ['🔴', '🟡', '🟡', '🔴', '🔴', '🟡', '🔴', '🟡']
})

print("Data Protection Metrics:")
print(protection_metrics.to_string(index=False))

# ----------------------------------------------------------------
# PART F: DATA PROTECTION ROADMAP
# ----------------------------------------------------------------

print("\n" + "-"*60)
print("PART F: Data Protection Roadmap")
print("-"*60)

roadmap = {
    "Phase 1 (0-6 months) – Foundation": {
        "Focus": "Establish data protection foundation.",
        "Activities": [
            "Implement data classification framework.",
            "Encrypt sensitive data at rest.",
            "Establish encryption key management.",
            "Implement DLP for sensitive data."
        ],
        "Success Metrics": ["Data classification coverage > 80%", "Encryption coverage > 90%"]
    },
    "Phase 2 (6-12 months) – Scale": {
        "Focus": "Scale data protection capabilities.",
        "Activities": [
            "Implement data masking for production and test.",
            "Implement tokenisation for payment data.",
            "Automate key rotation.",
            "Implement data loss prevention."
        ],
        "Success Metrics": ["Masking coverage > 70%", "Tokenisation coverage > 70%"]
    },
    "Phase 3 (12-24 months) – Advanced": {
        "Focus": "Advanced data protection.",
        "Activities": [
            "Implement format-preserving encryption.",
            "Deploy real-time data monitoring.",
            "Implement data privacy automation.",
            "Build data protection analytics."
        ],
        "Success Metrics": ["Full data protection coverage", "Zero data breaches"]
    },
    "Phase 4 (24+ months) – Leadership": {
        "Focus": "Industry-leading data protection.",
        "Activities": [
            "Implement AI-powered data protection.",
            "Build predictive data security.",
            "Achieve industry-leading maturity.",
            "Establish data protection culture."
        ],
        "Success Metrics": ["Industry-leading data protection", "Continuous improvement"]
    }
}

for phase, details in roadmap.items():
    print(f"\n{phase}:")
    print(f"  Focus: {details['Focus']}")
    print("  Activities:")
    for activity in details['Activities']:
        print(f"    • {activity}")
    print("  Success Metrics:")
    for metric in details['Success Metrics']:
        print(f"    • {metric}")

# ----------------------------------------------------------------
# PART G: REGULATORY COMPLIANCE
# ----------------------------------------------------------------

print("\n" + "-"*60)
print("PART G: Regulatory Compliance for Data Protection")
print("-"*60)

regulations = pd.DataFrame({
    'Regulation': ['GDPR', 'PCI DSS', 'CCPA', 'NYDFS', 'BCBS 239'],
    'Key Requirements': [
        'Data protection, breach notification, right to erasure',
        'Cardholder data protection, encryption, access control',
        'Data privacy, consumer rights, opt-out',
        'Cybersecurity program, incident reporting, MFA',
        'Data quality, data lineage, risk data aggregation'
    ],
    'Implementation Status': ['✅', '✅', '🟡', '✅', '🟡'],
    'Audit Frequency': ['Annual', 'Annual', 'Annual', 'Annual', 'Annual']
})

print("Regulatory Compliance:")
print(regulations.to_string(index=False))

# ----------------------------------------------------------------
# PART H: SUMMARY AND RECOMMENDATIONS
# ----------------------------------------------------------------

print("\n" + "="*70)
print("PART H: Summary and Recommendations")
print("="*70)

print("""
Data Protection and Encryption – Key Takeaways:

1. Data protection ensures confidentiality, integrity, and availability of data.
2. Data classification: public, internal, confidential, highly confidential, restricted.
3. Encryption: symmetric (AES-256), asymmetric (RSA), hashing (SHA-256, bcrypt).
4. Data masking and tokenisation protect sensitive data.
5. Key management: HSM, KMS, secure storage, rotation, lifecycle management.
6. Key metrics: classification coverage, encryption coverage, DLP coverage.
7. Regulatory compliance: GDPR, PCI DSS, CCPA, NYDFS, BCBS 239.

Recommendations:
  - Implement data classification framework.
  - Encrypt sensitive data at rest and in transit.
  - Use data masking for test environments.
  - Tokenise payment and PII data.
  - Implement key management with HSM/KMS.
  - Conduct regular data protection audits.
""")

print("="*70)
print("END OF LESSON 5 – MODULE 5")
print("="*70)

SECTION 7: SUMMARY FOR THE DATA PRACTITIONER

  • Data protection ensures the confidentiality, integrity, and availability of sensitive data.

  • Data classification categorises data into public, internal, confidential, highly confidential, and restricted.

  • Encryption includes symmetric (AES-256), asymmetric (RSA), and hashing (SHA-256, bcrypt, Argon2).

  • Data masking protects sensitive data in test and development environments.

  • Tokenisation replaces sensitive data with tokens, reducing PCI DSS scope.

  • Key management requires secure storage (HSM, KMS), key rotation, and lifecycle management.

  • Key metrics include classification coverage, encryption coverage, DLP coverage, and data breach incidents.


SECTION 8: RECOMMENDED NEXT STEPS

  1. Implement data classification framework.

  2. Encrypt sensitive data at rest and in transit.

  3. Use data masking for test environments.

  4. Tokenise payment and PII data.

  5. Implement key management with HSM/KMS.

  6. Conduct regular data protection audits.

  7. Prepare for Lesson 6: Incident Response and Business Continuity.


[END OF LESSON 5 – MODULE 5]