Pci Compliance
Secure payment processing with PCI DSS compliance requirements
✨ The solution you've been looking for
Implement PCI DSS compliance requirements for secure handling of payment card data and payment systems. Use when securing payment processing, achieving PCI compliance, or implementing payment card security measures.
See It In Action
Interactive preview & real-world examples
AI Conversation Simulator
See how users interact with this skill
User Prompt
Help me build a payment processing system that handles credit cards securely and meets PCI compliance requirements
Skill Processing
Analyzing request...
Agent Response
Complete implementation guidance including tokenization, encryption, access controls, and audit logging to achieve PCI DSS compliance
Quick Start (3 Steps)
Get up and running in minutes
Install
claude-code skill install pci-compliance
claude-code skill install pci-complianceConfig
First Trigger
@pci-compliance helpCommands
| Command | Description | Required Args |
|---|---|---|
| @pci-compliance building-a-pci-compliant-payment-system | Design and implement secure payment processing that meets PCI DSS requirements | None |
| @pci-compliance implementing-data-tokenization | Replace sensitive card data with secure tokens to minimize PCI scope | None |
| @pci-compliance pci-compliance-assessment-preparation | Audit existing systems and prepare for PCI DSS assessment | None |
Typical Use Cases
Building a PCI-Compliant Payment System
Design and implement secure payment processing that meets PCI DSS requirements
Implementing Data Tokenization
Replace sensitive card data with secure tokens to minimize PCI scope
PCI Compliance Assessment Preparation
Audit existing systems and prepare for PCI DSS assessment
Overview
PCI Compliance
Master PCI DSS (Payment Card Industry Data Security Standard) compliance for secure payment processing and handling of cardholder data.
When to Use This Skill
- Building payment processing systems
- Handling credit card information
- Implementing secure payment flows
- Conducting PCI compliance audits
- Reducing PCI compliance scope
- Implementing tokenization and encryption
- Preparing for PCI DSS assessments
PCI DSS Requirements (12 Core Requirements)
Build and Maintain Secure Network
- Install and maintain firewall configuration
- Don’t use vendor-supplied defaults for passwords
Protect Cardholder Data
- Protect stored cardholder data
- Encrypt transmission of cardholder data across public networks
Maintain Vulnerability Management
- Protect systems against malware
- Develop and maintain secure systems and applications
Implement Strong Access Control
- Restrict access to cardholder data by business need-to-know
- Identify and authenticate access to system components
- Restrict physical access to cardholder data
Monitor and Test Networks
- Track and monitor all access to network resources and cardholder data
- Regularly test security systems and processes
Maintain Information Security Policy
- Maintain a policy that addresses information security
Compliance Levels
Level 1: > 6 million transactions/year (annual ROC required) Level 2: 1-6 million transactions/year (annual SAQ) Level 3: 20,000-1 million e-commerce transactions/year Level 4: < 20,000 e-commerce or < 1 million total transactions
Data Minimization (Never Store)
1# NEVER STORE THESE
2PROHIBITED_DATA = {
3 'full_track_data': 'Magnetic stripe data',
4 'cvv': 'Card verification code/value',
5 'pin': 'PIN or PIN block'
6}
7
8# CAN STORE (if encrypted)
9ALLOWED_DATA = {
10 'pan': 'Primary Account Number (card number)',
11 'cardholder_name': 'Name on card',
12 'expiration_date': 'Card expiration',
13 'service_code': 'Service code'
14}
15
16class PaymentData:
17 """Safe payment data handling."""
18
19 def __init__(self):
20 self.prohibited_fields = ['cvv', 'cvv2', 'cvc', 'pin']
21
22 def sanitize_log(self, data):
23 """Remove sensitive data from logs."""
24 sanitized = data.copy()
25
26 # Mask PAN
27 if 'card_number' in sanitized:
28 card = sanitized['card_number']
29 sanitized['card_number'] = f"{card[:6]}{'*' * (len(card) - 10)}{card[-4:]}"
30
31 # Remove prohibited data
32 for field in self.prohibited_fields:
33 sanitized.pop(field, None)
34
35 return sanitized
36
37 def validate_no_prohibited_storage(self, data):
38 """Ensure no prohibited data is being stored."""
39 for field in self.prohibited_fields:
40 if field in data:
41 raise SecurityError(f"Attempting to store prohibited field: {field}")
Tokenization
Using Payment Processor Tokens
1import stripe
2
3class TokenizedPayment:
4 """Handle payments using tokens (no card data on server)."""
5
6 @staticmethod
7 def create_payment_method_token(card_details):
8 """Create token from card details (client-side only)."""
9 # THIS SHOULD ONLY BE DONE CLIENT-SIDE WITH STRIPE.JS
10 # NEVER send card details to your server
11
12 """
13 // Frontend JavaScript
14 const stripe = Stripe('pk_...');
15
16 const {token, error} = await stripe.createToken({
17 card: {
18 number: '4242424242424242',
19 exp_month: 12,
20 exp_year: 2024,
21 cvc: '123'
22 }
23 });
24
25 // Send token.id to server (NOT card details)
26 """
27 pass
28
29 @staticmethod
30 def charge_with_token(token_id, amount):
31 """Charge using token (server-side)."""
32 # Your server only sees the token, never the card number
33 stripe.api_key = "sk_..."
34
35 charge = stripe.Charge.create(
36 amount=amount,
37 currency="usd",
38 source=token_id, # Token instead of card details
39 description="Payment"
40 )
41
42 return charge
43
44 @staticmethod
45 def store_payment_method(customer_id, payment_method_token):
46 """Store payment method as token for future use."""
47 stripe.Customer.modify(
48 customer_id,
49 source=payment_method_token
50 )
51
52 # Store only customer_id and payment_method_id in your database
53 # NEVER store actual card details
54 return {
55 'customer_id': customer_id,
56 'has_payment_method': True
57 # DO NOT store: card number, CVV, etc.
58 }
Custom Tokenization (Advanced)
1import secrets
2from cryptography.fernet import Fernet
3
4class TokenVault:
5 """Secure token vault for card data (if you must store it)."""
6
7 def __init__(self, encryption_key):
8 self.cipher = Fernet(encryption_key)
9 self.vault = {} # In production: use encrypted database
10
11 def tokenize(self, card_data):
12 """Convert card data to token."""
13 # Generate secure random token
14 token = secrets.token_urlsafe(32)
15
16 # Encrypt card data
17 encrypted = self.cipher.encrypt(json.dumps(card_data).encode())
18
19 # Store token -> encrypted data mapping
20 self.vault[token] = encrypted
21
22 return token
23
24 def detokenize(self, token):
25 """Retrieve card data from token."""
26 encrypted = self.vault.get(token)
27 if not encrypted:
28 raise ValueError("Token not found")
29
30 # Decrypt
31 decrypted = self.cipher.decrypt(encrypted)
32 return json.loads(decrypted.decode())
33
34 def delete_token(self, token):
35 """Remove token from vault."""
36 self.vault.pop(token, None)
Encryption
Data at Rest
1from cryptography.hazmat.primitives.ciphers.aead import AESGCM
2import os
3
4class EncryptedStorage:
5 """Encrypt data at rest using AES-256-GCM."""
6
7 def __init__(self, encryption_key):
8 """Initialize with 256-bit key."""
9 self.key = encryption_key # Must be 32 bytes
10
11 def encrypt(self, plaintext):
12 """Encrypt data."""
13 # Generate random nonce
14 nonce = os.urandom(12)
15
16 # Encrypt
17 aesgcm = AESGCM(self.key)
18 ciphertext = aesgcm.encrypt(nonce, plaintext.encode(), None)
19
20 # Return nonce + ciphertext
21 return nonce + ciphertext
22
23 def decrypt(self, encrypted_data):
24 """Decrypt data."""
25 # Extract nonce and ciphertext
26 nonce = encrypted_data[:12]
27 ciphertext = encrypted_data[12:]
28
29 # Decrypt
30 aesgcm = AESGCM(self.key)
31 plaintext = aesgcm.decrypt(nonce, ciphertext, None)
32
33 return plaintext.decode()
34
35# Usage
36storage = EncryptedStorage(os.urandom(32))
37encrypted_pan = storage.encrypt("4242424242424242")
38# Store encrypted_pan in database
Data in Transit
1# Always use TLS 1.2 or higher
2# Flask/Django example
3app.config['SESSION_COOKIE_SECURE'] = True # HTTPS only
4app.config['SESSION_COOKIE_HTTPONLY'] = True
5app.config['SESSION_COOKIE_SAMESITE'] = 'Strict'
6
7# Enforce HTTPS
8from flask_talisman import Talisman
9Talisman(app, force_https=True)
Access Control
1from functools import wraps
2from flask import session
3
4def require_pci_access(f):
5 """Decorator to restrict access to cardholder data."""
6 @wraps(f)
7 def decorated_function(*args, **kwargs):
8 user = session.get('user')
9
10 # Check if user has PCI access role
11 if not user or 'pci_access' not in user.get('roles', []):
12 return {'error': 'Unauthorized access to cardholder data'}, 403
13
14 # Log access attempt
15 audit_log(
16 user=user['id'],
17 action='access_cardholder_data',
18 resource=f.__name__
19 )
20
21 return f(*args, **kwargs)
22
23 return decorated_function
24
25@app.route('/api/payment-methods')
26@require_pci_access
27def get_payment_methods():
28 """Retrieve payment methods (restricted access)."""
29 # Only accessible to users with pci_access role
30 pass
Audit Logging
1import logging
2from datetime import datetime
3
4class PCIAuditLogger:
5 """PCI-compliant audit logging."""
6
7 def __init__(self):
8 self.logger = logging.getLogger('pci_audit')
9 # Configure to write to secure, append-only log
10
11 def log_access(self, user_id, resource, action, result):
12 """Log access to cardholder data."""
13 entry = {
14 'timestamp': datetime.utcnow().isoformat(),
15 'user_id': user_id,
16 'resource': resource,
17 'action': action,
18 'result': result,
19 'ip_address': request.remote_addr
20 }
21
22 self.logger.info(json.dumps(entry))
23
24 def log_authentication(self, user_id, success, method):
25 """Log authentication attempt."""
26 entry = {
27 'timestamp': datetime.utcnow().isoformat(),
28 'user_id': user_id,
29 'event': 'authentication',
30 'success': success,
31 'method': method,
32 'ip_address': request.remote_addr
33 }
34
35 self.logger.info(json.dumps(entry))
36
37# Usage
38audit = PCIAuditLogger()
39audit.log_access(user_id=123, resource='payment_methods', action='read', result='success')
Security Best Practices
Input Validation
1import re
2
3def validate_card_number(card_number):
4 """Validate card number format (Luhn algorithm)."""
5 # Remove spaces and dashes
6 card_number = re.sub(r'[\s-]', '', card_number)
7
8 # Check if all digits
9 if not card_number.isdigit():
10 return False
11
12 # Luhn algorithm
13 def luhn_checksum(card_num):
14 def digits_of(n):
15 return [int(d) for d in str(n)]
16
17 digits = digits_of(card_num)
18 odd_digits = digits[-1::-2]
19 even_digits = digits[-2::-2]
20 checksum = sum(odd_digits)
21 for d in even_digits:
22 checksum += sum(digits_of(d * 2))
23 return checksum % 10
24
25 return luhn_checksum(card_number) == 0
26
27def sanitize_input(user_input):
28 """Sanitize user input to prevent injection."""
29 # Remove special characters
30 # Validate against expected format
31 # Escape for database queries
32 pass
PCI DSS SAQ (Self-Assessment Questionnaire)
SAQ A (Least Requirements)
- E-commerce using hosted payment page
- No card data on your systems
- ~20 questions
SAQ A-EP
- E-commerce with embedded payment form
- Uses JavaScript to handle card data
- ~180 questions
SAQ D (Most Requirements)
- Store, process, or transmit card data
- Full PCI DSS requirements
- ~300 questions
Compliance Checklist
1PCI_COMPLIANCE_CHECKLIST = {
2 'network_security': [
3 'Firewall configured and maintained',
4 'No vendor default passwords',
5 'Network segmentation implemented'
6 ],
7 'data_protection': [
8 'No storage of CVV, track data, or PIN',
9 'PAN encrypted when stored',
10 'PAN masked when displayed',
11 'Encryption keys properly managed'
12 ],
13 'vulnerability_management': [
14 'Anti-virus installed and updated',
15 'Secure development practices',
16 'Regular security patches',
17 'Vulnerability scanning performed'
18 ],
19 'access_control': [
20 'Access restricted by role',
21 'Unique IDs for all users',
22 'Multi-factor authentication',
23 'Physical security measures'
24 ],
25 'monitoring': [
26 'Audit logs enabled',
27 'Log review process',
28 'File integrity monitoring',
29 'Regular security testing'
30 ],
31 'policy': [
32 'Security policy documented',
33 'Risk assessment performed',
34 'Security awareness training',
35 'Incident response plan'
36 ]
37}
Resources
- references/data-minimization.md: Never store prohibited data
- references/tokenization.md: Tokenization strategies
- references/encryption.md: Encryption requirements
- references/access-control.md: Role-based access
- references/audit-logging.md: Comprehensive logging
- assets/pci-compliance-checklist.md: Complete checklist
- assets/encrypted-storage.py: Encryption utilities
- scripts/audit-payment-system.sh: Compliance audit script
Common Violations
- Storing CVV: Never store card verification codes
- Unencrypted PAN: Card numbers must be encrypted at rest
- Weak Encryption: Use AES-256 or equivalent
- No Access Controls: Restrict who can access cardholder data
- Missing Audit Logs: Must log all access to payment data
- Insecure Transmission: Always use TLS 1.2+
- Default Passwords: Change all default credentials
- No Security Testing: Regular penetration testing required
Reducing PCI Scope
- Use Hosted Payments: Stripe Checkout, PayPal, etc.
- Tokenization: Replace card data with tokens
- Network Segmentation: Isolate cardholder data environment
- Outsource: Use PCI-compliant payment processors
- No Storage: Never store full card details
By minimizing systems that touch card data, you reduce compliance burden significantly.
What Users Are Saying
Real feedback from the community
Environment Matrix
Dependencies
Framework Support
Context Window
Security & Privacy
Information
- Author
- wshobson
- Updated
- 2026-01-30
- Category
- architecture-patterns
Related Skills
Pci Compliance
Implement PCI DSS compliance requirements for secure handling of payment card data and payment …
View Details →Billing Automation
Build automated billing systems for recurring payments, invoicing, subscription lifecycle, and …
View Details →Billing Automation
Build automated billing systems for recurring payments, invoicing, subscription lifecycle, and …
View Details →