DEV Community

Cover image for Chapter 69 — Secure AI Cryptography & Data Protection
Black Shadow Team ©
Black Shadow Team ©

Posted on

Chapter 69 — Secure AI Cryptography & Data Protection

#ai

69.1 Introduction

Cryptography is one of the foundational security mechanisms of an AI platform.

It protects:

  • data in transit
  • data at rest
  • authentication tokens
  • database fields
  • object-storage files
  • backups
  • API communication
  • digital signatures
  • passwords
  • sensitive workflow information

However, cryptography is not simply a matter of selecting an algorithm.

A secure cryptographic architecture must answer:

  1. What needs protection?
  2. From whom?
  3. Where is the data?
  4. Which algorithm is appropriate?
  5. Where are the keys stored?
  6. Who can use the keys?
  7. How are keys rotated?
  8. How is integrity verified?
  9. What happens when cryptographic verification fails?
  10. How are old encrypted records migrated?

The most important principle is:

Strong cryptography cannot compensate for weak key management, incorrect implementation, or broken authorization.


69.2 Three Security Properties

Cryptographic systems commonly provide three major properties.

Confidentiality

Prevents unauthorized parties from reading data.

Integrity

Detects unauthorized modification.

Authenticity

Provides evidence that data originated from an expected party.

A secure AI application often needs all three.


69.3 Data States

Data should be considered in three states:

```text id="h3m8r5"
DATA

┌──────────┼──────────┐
▼ ▼ ▼
Transit Rest Use




### Data in transit

Moving across networks.

### Data at rest

Stored in databases, object storage, backups or disks.

### Data in use

Currently being processed by applications, workers or AI systems.

Encryption is particularly straightforward for transit and rest.

Data-in-use protection can require additional architectural techniques and careful isolation.

---

# 69.4 Encryption in Transit

Network encryption typically uses TLS.

Example:



```text id="r0t5k9"
Client
   │
   │ encrypted connection
   ▼
API
   │
   │ encrypted connection
   ▼
Database / Provider
Enter fullscreen mode Exit fullscreen mode

TLS protects against many forms of network interception and tampering.

But TLS does not eliminate application-level authorization problems.


69.5 Encryption at Rest

Stored data may be encrypted at several layers.

```text id="2b7s4f"
Application

Database encryption

Storage encryption

Disk encryption




Different layers protect against different threat scenarios.

For highly sensitive applications, defense in depth is valuable.

---

# 69.6 Symmetric Encryption

Symmetric encryption uses the same secret key for encryption and decryption.

Conceptually:



```text id="z4j7wq"
Plaintext
   ↓
Secret Key
   ↓
Encryption
   ↓
Ciphertext
   ↓
Secret Key
   ↓
Decryption
   ↓
Plaintext
Enter fullscreen mode Exit fullscreen mode

It is efficient and commonly used for bulk data encryption.


69.7 AES

AES is a widely used symmetric encryption standard.

Common configurations include AES with 128-, 192-, or 256-bit keys.

For modern applications, authenticated encryption should generally be preferred over encryption that provides confidentiality without integrity protection.


69.8 Authenticated Encryption

Authenticated encryption protects both:

  • confidentiality
  • integrity/authenticity

A common modern pattern is AES-GCM.

Conceptually:

```text id="4n8f9v"
Plaintext
+
Additional Authenticated Data
+
Key

AES-GCM

Ciphertext + Authentication Tag




The authentication tag allows the receiver to detect tampering.

---

# 69.9 Why Integrity Matters

Consider encrypted data:



```text id="m6h8f3"
ciphertext
Enter fullscreen mode Exit fullscreen mode

If an attacker modifies it and the system cannot detect the modification, the application may process corrupted information.

Authenticated encryption instead produces:

```text id="x9w5q1"
ciphertext
+
authentication tag




Tampering causes verification failure.

---

# 69.10 Nonces and IVs

Authenticated encryption modes use nonces/initialization vectors.

A critical rule for AES-GCM is:

> **Never reuse a nonce with the same key.**

Nonce management must therefore be deliberate.

Applications should use well-tested cryptographic libraries rather than implementing nonce generation manually.

---

# 69.11 Additional Authenticated Data

Some metadata does not need encryption but still needs integrity protection.

For example:



```text id="0e8h2v"
tenant_id
object_id
version
algorithm
Enter fullscreen mode Exit fullscreen mode

Such metadata can be authenticated as associated data.

Conceptually:

```text id="5v6n9m"
Encrypted Content
+
Authenticated Metadata

Integrity protected




This can prevent an attacker from moving valid ciphertext into an unauthorized context.

---

# 69.12 Avoid Custom Cryptography

A major security principle is:

> **Do not invent your own cryptographic algorithm.**

Avoid custom:

* encryption formats
* random-number generators
* signature schemes
* password hashing algorithms
* key exchange mechanisms

Use mature, reviewed cryptographic libraries and established standards.

---

# 69.13 Hashing

Hashing transforms input into a fixed-length digest.

Conceptually:



```text id="4v1r9x"
Input
  ↓
Hash Function
  ↓
Digest
Enter fullscreen mode Exit fullscreen mode

Hashing is not the same as encryption.

Encryption is intended to be reversible with the appropriate key.

A cryptographic hash is designed to be computationally difficult to reverse.


69.14 Hash Use Cases

Cryptographic hashes can be useful for:

  • integrity checks
  • content addressing
  • fingerprints
  • deduplication
  • signatures
  • cache validation
  • tamper detection

They should not automatically be used for password storage.


69.15 SHA-256

SHA-256 is a widely used cryptographic hash function.

A conceptual representation is:

```text id="19ly7v"
data

SHA-256

256-bit digest




The digest can help detect whether content changed.

---

# 69.16 Password Hashing

Passwords require a specialized password-hashing algorithm.

Do not store:



```text id="v2y7ce"
password
Enter fullscreen mode Exit fullscreen mode

or simply:

```text id="2e3m4k"
SHA256(password)




Password storage should use a dedicated password-hashing function designed to resist brute-force attacks.

Common choices include:

* Argon2id
* bcrypt
* scrypt

The exact choice depends on the environment and operational requirements.

---

# 69.17 Password Salts

Password hashes should use unique salts.

Conceptually:



```text id="y8c4b6"
Password
   +
Unique Salt
   ↓
Password Hash Function
   ↓
Stored Hash
Enter fullscreen mode Exit fullscreen mode

Two users with the same password should not normally have identical stored password hashes.


69.18 Password Hashing Parameters

Password-hashing algorithms have cost parameters.

Higher cost can increase attacker workload but also increases legitimate server workload.

The system should choose parameters appropriate to:

  • hardware
  • expected login volume
  • security requirements
  • acceptable latency

Parameters should be periodically reviewed.


69.19 Password Hash Migration

If an application changes password-hashing algorithms, users do not necessarily need to reset all passwords immediately.

A migration strategy can be:

```text id="1k8m7d"
Login

Verify old hash

Successful?

Rehash with stronger algorithm

Store new hash




This allows gradual migration.

---

# 69.20 Key Derivation Functions

Key derivation functions transform secret material into cryptographic keys.

They can be useful for:

* deriving application keys
* password-based encryption
* separating cryptographic contexts

Examples include:

* HKDF
* PBKDF2
* scrypt
* Argon2-based derivation

The appropriate function depends on the use case.

---

# 69.21 HKDF

HKDF is useful when a high-quality secret needs to produce multiple context-specific keys.

Conceptually:



```text id="q3j7y8"
Master Secret
     ↓
HKDF
 ┌───┼────┐
 ▼   ▼    ▼
Key A Key B Key C
Enter fullscreen mode Exit fullscreen mode

Each derived key can have a distinct purpose.

This supports key separation.


69.22 Key Separation

Avoid using one key for multiple unrelated purposes.

For example:

```text id="2o0c6b"
Master Secret

├── encryption key
├── signing key
├── token key
└── webhook key




This reduces the consequences of a compromise.

---

# 69.23 Digital Signatures

Digital signatures provide authenticity and integrity.

Conceptually:



```text id="7k8w3z"
Message
   ↓
Private Signing Key
   ↓
Signature
Enter fullscreen mode Exit fullscreen mode

Verification:

```text id="5k6j9a"
Message
+
Signature
+
Public Key

Valid / Invalid




Unlike symmetric encryption, verification can be performed using a public key.

---

# 69.24 Signing vs Encryption

These are different operations.

### Encryption

Protects confidentiality.



```text id="2s9d4j"
plaintext → ciphertext
Enter fullscreen mode Exit fullscreen mode

Signature

Protects authenticity/integrity.

```text id="7d0p1x"
message → signature




A secure AI platform may need both.

---

# 69.25 Token Security

AI applications often use tokens for:

* authentication
* authorization
* API access
* workflow correlation
* temporary download access

Tokens should be:

* unpredictable where opaque
* appropriately scoped
* short-lived when possible
* revocable where necessary
* protected from logs
* transmitted securely

---

# 69.26 Opaque Tokens

For sensitive sessions, opaque random identifiers can be useful.

Conceptually:



```text id="2q3x9m"
Browser
  ↓
opaque session ID
  ↓
server-side session
Enter fullscreen mode Exit fullscreen mode

The token itself does not need to contain user information.


69.27 Signed Tokens

Signed tokens can carry claims.

The receiver verifies:

```text id="4v7j2c"
signature
+
expiration
+
issuer
+
audience
+
claims




But a valid signature does not automatically mean the requested operation is authorized.

Authorization still matters.

---

# 69.28 Token Expiration

Tokens should have appropriate lifetimes.

Example:



```text id="w4p9h2"
Short-lived access token
        ↓
minutes

Refresh capability
        ↓
longer lifetime
Enter fullscreen mode Exit fullscreen mode

Shorter lifetimes reduce exposure if a token leaks.


69.29 Token Revocation

Some systems require immediate revocation.

Possible approaches include:

  • server-side session records
  • token versioning
  • revocation lists
  • short token lifetime
  • user security-version changes

The correct mechanism depends on the architecture.


69.30 Cryptographically Secure Randomness

Security-sensitive identifiers require secure randomness.

Use operating-system or library-provided cryptographically secure random-number generators.

Do not use ordinary pseudo-random functions intended for:

  • simulations
  • UI effects
  • games
  • non-security tasks

for security tokens.


69.31 Random Session IDs

A session identifier should have sufficient entropy to make guessing impractical.

The implementation should use a mature framework or cryptographic random generator.

Do not construct session IDs from:

```text id="r8k2v0"
timestamp
username
counter
IP address




These values are predictable.

---

# 69.32 Encryption Key Storage

Never hardcode master encryption keys into application source code.

Unsafe:



```text id="7s9p4n"
const MASTER_KEY = "..."
Enter fullscreen mode Exit fullscreen mode

Better:

```text id="q3x5m1"
Application

KMS / Secret Manager

Key operation




---

# 69.33 Envelope Encryption

For sensitive application data:



```text id="d9j3s6"
KMS Key
   ↓
Data Encryption Key
   ↓
Encrypted Object
Enter fullscreen mode Exit fullscreen mode

The application can use a data key for the actual encryption while the KMS protects the higher-level key.


69.34 Database Encryption

Databases can use encryption at rest.

But database encryption does not prevent an authorized application from reading data.

For highly sensitive fields, application-level encryption may also be appropriate.

Examples:

  • identity information
  • private user data
  • sensitive business records
  • highly confidential documents

69.35 Field-Level Encryption

Instead of encrypting the entire database manually, sensitive fields can be encrypted individually.

Conceptually:

```text id="h8w4p3"
User Record
├── user_id → plaintext
├── name → protected according to policy
├── email → protected according to policy
└── sensitive_field → encrypted




This can reduce exposure if database contents are accessed outside the intended application path.

---

# 69.36 Searchability Trade-Off

Encrypted fields can be harder to search.

For example:



```text id="x7n4y1"
encrypted email
Enter fullscreen mode Exit fullscreen mode

cannot necessarily be queried like ordinary plaintext.

Architects must therefore balance:

  • confidentiality
  • searchability
  • performance
  • complexity

Sometimes a carefully designed keyed hash or separate lookup index can help, but it must be designed to avoid creating new privacy leaks.


69.37 Object Storage Encryption

AI media files can be encrypted at rest.

Example:

```text id="3y6h8n"
User File

Object Storage

Encryption




Access should still be controlled through:

* authorization
* signed URLs
* object policies
* identity
* audit logging

Encryption does not replace access control.

---

# 69.38 Backup Encryption

Backups should receive protection equivalent to or stronger than production data.

Otherwise:



```text id="6g8r2w"
Production → encrypted
Backup     → plaintext
Enter fullscreen mode Exit fullscreen mode

creates an obvious security weakness.


69.39 Key Rotation

Keys should be rotated according to:

  • risk
  • regulatory requirements
  • organizational policy
  • cryptographic best practice
  • compromise indicators

Rotation should be automated wherever practical.


69.40 Key Versioning

Encrypted records should be associated with key versions.

Conceptually:

```text id="u7d5k2"
record
├── key_version = 12
└── ciphertext




During decryption:



```text id="2m8s4x"
key_version
     ↓
select appropriate key
     ↓
decrypt
Enter fullscreen mode Exit fullscreen mode

69.41 Cryptographic Failure Handling

Cryptographic verification failures must be treated seriously.

For example:

```text id="e8r6p1"
authentication tag invalid




The system should not:



```text id="k4x8j3"
ignore error
continue processing
Enter fullscreen mode Exit fullscreen mode

Instead:

```text id="f7q3m9"
verification failure

reject data

log security event

investigate if abnormal




---

# 69.42 Padding and Parsing

Modern authenticated encryption reduces many legacy padding problems.

Nevertheless, applications should still carefully validate:

* ciphertext length
* encoding
* algorithm identifiers
* version
* metadata
* authentication tags

Never assume encrypted input is correctly formatted.

---

# 69.43 Algorithm Agility

A mature cryptographic system should not permanently hardcode one algorithm into every data record.

Instead, encrypted records may include a versioned format:



```json id="4d8z6q"
{
  "version": 2,
  "algorithm": "approved-algorithm",
  "key_version": 12,
  "nonce": "...",
  "ciphertext": "...",
  "tag": "..."
}
Enter fullscreen mode Exit fullscreen mode

This makes future cryptographic migration easier.


69.44 Cryptographic Migration

Algorithms can eventually become obsolete.

A migration architecture should support:

```text id="m7x4v1"
Old Format

Read

Decrypt

Re-encrypt

New Format




Migration can happen gradually rather than requiring an immediate rewrite of every record.

---

# 69.45 Cryptographic Downgrade Attacks

An attacker may attempt to force the application to use weaker cryptography.

Defenses include:

* minimum algorithm versions
* strict protocol negotiation
* rejecting deprecated algorithms
* explicit configuration
* authenticated metadata

Never silently fall back to insecure algorithms.

---

# 69.46 AI Model Artifact Protection

AI systems may store:

* model weights
* adapters
* embeddings
* tokenizer files
* configuration
* evaluation data

Some of these may be proprietary or sensitive.

Protect them using:

* access control
* encryption
* integrity verification
* provenance
* versioning
* trusted distribution

---

# 69.47 Model Integrity

Before deploying a model artifact:



```text id="8m3q2z"
Model File
   ↓
Integrity Check
   ↓
Provenance Check
   ↓
Security Scan
   ↓
Evaluation
   ↓
Approved Registry
   ↓
Deployment
Enter fullscreen mode Exit fullscreen mode

A cryptographic hash can help verify that the file has not changed.

A signature can provide stronger provenance when a trusted signing infrastructure exists.


69.48 Container Image Integrity

AI services often run inside containers.

Container images should be:

  • versioned
  • scanned
  • signed where appropriate
  • verified before deployment

The goal is to ensure the deployed artifact corresponds to an approved build.


69.49 Software Supply Chain

Cryptography can help establish software provenance.

Conceptually:

```text id="5h2k7w"
Source

Build

Artifact

Signature

Registry

Deployment Verification




This can reduce the risk of unauthorized artifact substitution.

---

# 69.50 RAG Data Integrity

RAG systems should also track the integrity and provenance of documents.

A document record may include:



```text id="v8c3k0"
document_id
source
version
hash
created_at
owner
classification
Enter fullscreen mode Exit fullscreen mode

If content changes unexpectedly, the system can detect the difference.


69.51 Encryption and Multi-Tenancy

Multi-tenant systems should carefully define cryptographic boundaries.

Possible models include:

```text id="9j7w3p"
Tenant

Tenant-specific encryption context

Tenant data




Higher-risk environments may use separate keys or encryption contexts for different tenants.

This can reduce cross-tenant impact.

---

# 69.52 Cryptographic Context Binding

Encrypted data should not necessarily be portable between security contexts.

Authenticated metadata can bind ciphertext to:



```text id="6q9n2x"
tenant
object
environment
purpose
version
Enter fullscreen mode Exit fullscreen mode

This helps prevent ciphertext from being copied into another context and accepted incorrectly.


69.53 Privacy and Cryptography

Encryption helps protect confidentiality, but it does not automatically solve privacy.

Privacy also requires:

  • minimization
  • access control
  • retention limits
  • deletion
  • consent
  • governance
  • auditing

Encrypted unnecessary data is still unnecessary data.


69.54 Cryptographic Logging

Do not log raw cryptographic secrets.

Useful metadata can include:

```text id="2m6x9k"
key_version
algorithm_version
operation
service
request_id
result




Avoid:



```text id="r5c8v3"
private key
encryption key
plaintext
full token
Enter fullscreen mode Exit fullscreen mode

69.55 Cryptographic Monitoring

Useful signals include:

  • repeated authentication-tag failures
  • signature verification failures
  • unexpected key-version requests
  • decryption errors
  • unusual key-access patterns
  • deprecated algorithm usage
  • unexpected signing operations

A sudden increase in cryptographic failures can indicate corruption, implementation problems or attack activity.


69.56 Secure Cryptography Architecture

A complete model can look like:

```text id="f4v7q8"
Identity


Authorization


Application

┌─────────┼─────────┐
▼ ▼ ▼
KMS Database Storage
│ │ │
▼ ▼ ▼
Key Ops Encryption Encryption
│ │ │
└─────────┼─────────┘

Audit




The KMS or key-management layer controls high-value cryptographic operations.

---

# 69.57 Recommended Cryptographic Separation

A mature AI application might separate:



```text id="0y7j6p"
Authentication
 └── session/token keys

Application Data
 └── data encryption keys

Object Storage
 └── storage encryption

Database
 └── database encryption

Webhooks
 └── signing secrets

Software Supply Chain
 └── artifact signing keys

AI Models
 └── artifact integrity/signing
Enter fullscreen mode Exit fullscreen mode

This limits the blast radius of a single compromise.


69.58 Common Cryptographic Mistakes

Avoid:

```text id="c3k7m9"
[ ] Custom encryption algorithm
[ ] Hardcoded keys
[ ] Reused AES-GCM nonce
[ ] Plaintext passwords
[ ] SHA-256 directly for password storage
[ ] Disabled TLS verification
[ ] Ignoring authentication-tag failures
[ ] One key for every purpose
[ ] Long-lived unrestricted tokens
[ ] Secrets in logs
[ ] Production keys in development
[ ] No key rotation
[ ] No key versioning
[ ] No cryptographic migration plan
[ ] Weak random-number generator
[ ] Trusting hashes as proof of authorship
[ ] Treating encryption as authorization




---

# 69.59 Production Checklist



```text id="6k2p8w"
[ ] TLS is enabled for sensitive network communication
[ ] Certificate validation is enforced
[ ] Strong authenticated encryption is used
[ ] Cryptographic libraries are maintained
[ ] Nonce requirements are respected
[ ] Passwords use dedicated password hashing
[ ] Password salts are unique
[ ] Security-sensitive randomness uses CSPRNGs
[ ] Keys are stored outside source code
[ ] KMS/secret management is used where appropriate
[ ] Keys are separated by purpose
[ ] Key versions are tracked
[ ] Rotation procedures exist
[ ] Emergency key revocation exists
[ ] Encryption failures are fail-closed
[ ] Token lifetimes are bounded
[ ] Signing keys are protected
[ ] Webhooks use signature verification
[ ] Backups are encrypted
[ ] Object storage is encrypted
[ ] Sensitive fields receive appropriate protection
[ ] Model artifacts have integrity controls
[ ] Container artifacts are verified
[ ] RAG provenance is tracked
[ ] Cryptographic operations are audited
[ ] Deprecated algorithms are removed
[ ] Migration plans exist
Enter fullscreen mode Exit fullscreen mode

69.60 Final Architecture Principle

Cryptography should be viewed as a complete lifecycle rather than a single algorithm.

The lifecycle is:

```text id="7x5q1m"
Identify Data

Classify Data

Select Protection

Generate Key

Protect Key

Encrypt / Sign

Store / Transfer

Verify

Rotate

Revoke

Destroy




The strongest AI security architecture combines:

**modern cryptography + secure randomness + authenticated encryption + password hashing + digital signatures + key separation + KMS + secret management + rotation + versioning + integrity verification + strict failure handling.**

The central principle is:

> **Protecting data requires protecting the keys, the algorithms, the implementation, the metadata and the lifecycle—not merely encrypting the bytes.**

For an AI platform, cryptography must also extend into:

* agent tools
* RAG documents
* AI memory
* model artifacts
* generated media
* workflow state
* authentication
* service communication
* backups
* software supply chain

A cryptographically strong system is therefore not simply one that uses AES.

It is one where **every sensitive data flow has a deliberate confidentiality, integrity, authenticity and key-management strategy.**

The next logical chapter is:

**Chapter 70 — Secure AI Application Security Testing & Verification: SAST, DAST, SCA, Secret Scanning, IaC Scanning, Container Scanning, API Testing, Fuzzing, Threat Modeling, Penetration Testing, AI Red Teaming, Security Regression Testing & Continuous Assurance.**
Enter fullscreen mode Exit fullscreen mode

Top comments (0)