Chapter 69 — Secure AI Cryptography & Data Protection
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:
What needs protection?
From whom?
Where is the data?
Which algorithm is appropriate?
Where are the keys stored?
Who can use the keys?
How are keys rotated?
How is integrity verified?
What happens when cryptographic verification fails?
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:
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:
Client
│
│ encrypted connection
▼
API
│
│ encrypted connection
▼
Database / Provider
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.
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:
Plaintext
↓
Secret Key
↓
Encryption
↓
Ciphertext
↓
Secret Key
↓
Decryption
↓
Plaintext
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:
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:
ciphertext
If an attacker modifies it and the system cannot detect the modification, the application may process corrupted information.
Authenticated encryption instead produces:
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:
tenant_id
object_id
version
algorithm
Such metadata can be authenticated as associated data.
Conceptually:
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:
Input
↓
Hash Function
↓
Digest
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:
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:
password
or simply:
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:
Password
+
Unique Salt
↓
Password Hash Function
↓
Stored Hash
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:
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:
Master Secret
↓
HKDF
┌───┼────┐
▼ ▼ ▼
Key A Key B Key C
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:
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:
Message
↓
Private Signing Key
↓
Signature
Verification:
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.
plaintext → ciphertext
Signature
Protects authenticity/integrity.
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:
Browser
↓
opaque session ID
↓
server-side session
The token itself does not need to contain user information.
69.27 Signed Tokens
Signed tokens can carry claims.
The receiver verifies:
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:
Short-lived access token
↓
minutes
Refresh capability
↓
longer lifetime
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:
timestamp
username
counter
IP address
These values are predictable.
69.32 Encryption Key Storage
Never hardcode master encryption keys into application source code.
Unsafe:
const MASTER_KEY = "..."
Better:
Application
↓
KMS / Secret Manager
↓
Key operation
69.33 Envelope Encryption
For sensitive application data:
KMS Key
↓
Data Encryption Key
↓
Encrypted Object
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:
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:
encrypted email
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:
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:
Production → encrypted
Backup → plaintext
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:
record
├── key_version = 12
└── ciphertext
During decryption:
key_version
↓
select appropriate key
↓
decrypt
69.41 Cryptographic Failure Handling
Cryptographic verification failures must be treated seriously.
For example:
authentication tag invalid
The system should not:
ignore error
continue processing
Instead:
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:
{
"version": 2,
"algorithm": "approved-algorithm",
"key_version": 12,
"nonce": "...",
"ciphertext": "...",
"tag": "..."
}
This makes future cryptographic migration easier.
69.44 Cryptographic Migration
Algorithms can eventually become obsolete.
A migration architecture should support:
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:
Model File
↓
Integrity Check
↓
Provenance Check
↓
Security Scan
↓
Evaluation
↓
Approved Registry
↓
Deployment
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:
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:
document_id
source
version
hash
created_at
owner
classification
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:
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:
tenant
object
environment
purpose
version
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:
key_version
algorithm_version
operation
service
request_id
result
Avoid:
private key
encryption key
plaintext
full token
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:
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:
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
This limits the blast radius of a single compromise.
69.58 Common Cryptographic Mistakes
Avoid:
[ ] 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
[ ] 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
69.60 Final Architecture Principle
Cryptography should be viewed as a complete lifecycle rather than a single algorithm.
The lifecycle is:
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.
