Whatever message this page gives is out now! Go check it out!

Encrypt

Last update:
May 18, 2026
Description
Encrypts a string using a specific algorithm and encoding method.

Returns

String; can be much longer than the original string.

Category

Function syntax

Encrypt(string, key, encoding, algorithm, IV_Salt, iterations)
See also

History

  • ColdFusion (2025 release): Removed CFMX_COMPAT algorithm support. The default algorithm 'CFMX_COMPAT' has been changed to 'AES/CBC/PKCS5Padding'.
  • ColdFusion (2023 release) Update 8 and ColdFusion (2021 release) Update 14: Changed the default algorithm from CFMX_COMPAT to AES/CBC/PKCS5Padding.
  • ColdFusion (2021 release): Added support for authentication encryption.
  • ColdFusion (2018 release): Introduced named parameters.
  • ColdFusion 8: Added support for encryption using the RSA BSafe Crypto-J library on Enterprise Edition.
  • ColdFusion MX 7.01: Added the IVorSalt and iterations parameters.
  • ColdFusion MX 7: Added the algorithm and encoding parameters.

Parameters

Parameter
Description
string
String to encrypt.
key
String. Key or seed used to encrypt the string.
  • For the CFMX_COMPAT algorithm, any combination of any number of characters; used as a seed used to generate a 32-bit encryption key.
  • For all other algorithms, a key in the format used by the algorithm. For these algorithms, use the GenerateSecretKey function to generate the key.
algorithm
(Optional) The algorithm to use to encrypt the string.
The Enterprise Edition of ColdFusion installs the RSA BSafe Crypto-J library, which provides FIPS-140 Compliant Strong Cryptography. It includes the following algorithms:
  • AES: the Advanced Encryption Standard specified by the National Institute of Standards and Technology (NIST) FIPS-19.
  • DES: the Data Encryption Standard algorithm defined by NIST FIPS-46-3.
  • DES-EDE: the "Triple DES" algorithm defined by NIST FIPS-46-3.
  • DESX: The extended Data Encryption Standard symmetric encryption algorithm.
  • RC2: The RC2 block symmetric encryption algorithm defined by RFC 2268.
  • RC4: The RC4 symmetric encryption algorithm.
  • RC5: The RC5 encryption algorithm.
  • PBE: Password-based encryption algorithm defined in PKCS #5.
  • AES/GCM/NoPadding: Encryption algorithm.
  • AES/CBC/PKCS5Padding: Encryption algorithm.
In addition to these algorithms, you can use the algorithms provided in the Standard Edition of ColdFusion.
The Standard Edition of ColdFusion installs a cryptography library with the following algorithms:
  • CFMX_COMPAT: the algorithm used in ColdFusion MX and prior releases. This is no longer the default algorithm.
  • AES: the Advanced Encryption Standard specified by the National Institute of Standards and Technology (NIST) FIPS-197.
  • BLOWFISH: the Blowfish algorithm defined by Bruce Schneier.
  • DES: the Data Encryption Standard algorithm defined by NIST FIPS-46-3.
  • DESEDE: the "Triple DES" algorithm defined by NIST FIPS-46-3.
If you install a security provider with additional cryptography algorithms, you can also specify any of its string encryption and decryption algorithms.
encoding
(Optional; if you specify this parameter, also specify the algorithm parameter). The binary encoding in which to represent the data as a string.
  • Base64: the Base64 algorithm, as specified by IETF RFC 2045.
  • Hex: the characters A-F0-9 represent the hexadecimal byte values.
  • UU: the UUEncode algorithm (default).
IV_Salt
(Optional) Specify this parameter to adjust ColdFusion encryption to match the details of other encryption software. If you specify this parameter, also specify thealgorithmparameter.
  • For Block Encryption algorithms: This is the binary Initialization Vector value to use with the algorithm. The algorithm must contain a Feedback Mode other than ECB. This must be a binary value that is exactly the same size as the algorithm block size. Use the same value in theDecryptfunction to successfully decrypt the data.
  • For Password Based Encryption algorithms: This is the binary Salt value to transform the password into a key. The same value must be used to decrypt the data.
iterations
(Optional) The number of iterations to transform the password into a binary key. Specify this parameter to adjust ColdFusion encryption to match the details of other encryption software. If you specify this parameter, also specify the algorithm parameter with a Password Based Encryption (PBE) algorithm. Do not specify this parameter for Block Encryption algorithms. Use the same value to encrypt and decrypt the data.

Usage

This function uses a symmetric key-based algorithm, in which the same key is used to encrypt and decrypt a string. The security of the encrypted string depends on maintaining the secrecy of the key.
The following are the FIPS-140 approved algorithms included in the RSA BSafe Crypto-J library that are used by ColdFusion. Some of these are not used with the encrypt function, but are used with other functions:
  • AES – ECB, CBC, CFB (128), OFB (128) – [128, 192, 256-bit key sizes]
  • AES – CTR
  • Diffie-Hellman Key Agreement
  • DSA
  • FIPS 186-2 General Purpose [(x-Change Notice); (SHA-1)]
  • FIPS 186-2 [(x-Change Notice); (SHA-1)]
  • HMAC-SHAx (where x is 1, 224, 256, 384, or 512)
  • RSA PKCS#1 v1.5 (sign, verify) (SHA-1,SHA-224,SHA-256,SHA-384,SHA-512)
  • Secure Hash Standard (SHA-1, SHA-224, SHA-256, SHA-384, SHA-512)
  • Triple DES - ECB, CBC, CFB (64 bit), and OFB (64 bit)
All algorithms included in the RSA BSafe Crypto-J library are available for use in the Enterprise Edition. In certain cases, you may want to disable some algorithms. To disable the DESX, RC5, and MD5PRNG algorithms, specify the following in the JVM arguments on the Java and JVM page of the ColdFusion Administrator:
-Dcoldfusion.enablefipscrypto=true
FIPS-140 approved cryptography is not available if you are running ColdFusion on WebSphere of JBoss.
To use the IBM/Lotus Sametime Instant Messaging Gateway in the Enterprise edition, disable the FIPS-140-only cryptography setting by specifying the following in the JVM arguments on the Java and JVM page of the ColdFusion Administrator:
-Dcoldfusion.disablejsafe=true
In Standard Edition, for all algorithms except the default algorithm, ColdFusion uses the Java Cryptography Extension (JCE) and installs a Sun Java runtime that includes the Sun JCE default security provider. This provider includes the algorithms listed in the Parameters section. The JCE framework includes facilities for using other provider implementations; however, Adobe cannot provide technical support for third-party security providers.
The default algorithm, which is the same one used in ColdFusion 5 and ColdFusion MX, uses an XOR-based algorithm that uses a pseudo-random 32-bit key, based on a seed passed by the user as a function parameter. This algorithm is less secure than the other available algorithms.

Example

The following example encrypts and decrypts a text string. It lets you specify the encryption algorithm and encoding technique. It also has a field for a key seed to use with the CFMX_COMPAT algorithm. For all other algorithms, it generates a secret key.
<h3>Encrypt Example</h3> 
 <!--- Do the following if the form has been submitted. ---> 
 <cfif IsDefined("Form.myString")> 
 <cfscript> 
 /* GenerateSecretKey does not generate key for the CFMX_COMPAT algorithm, 
 so use the key from the form. 
 */ 
 if (Form.myAlgorithm EQ "CFMX_COMPAT") 
 theKey=Form.MyKey; 
 // For all other encryption techniques, generate a secret key. 
 else 
 theKey=generateSecretKey(Form.myAlgorithm); 
 //Encrypt the string 
 encrypted=encrypt(Form.myString, theKey, Form.myAlgorithm, 
 Form.myEncoding); 
 //Decrypt it 
 decrypted=decrypt(encrypted, theKey, Form.myAlgorithm, Form.myEncoding); 
 </cfscript> 
 
 <!--- Display the values used for encryption and decryption, 
 and the results. ---> 
 <cfoutput> 
 <b>The algorithm:</b> #Form.myAlgorithm#<br> 
 <b>The key:</B> #theKey#<br> 
 <br> 
 <b>The string:</b> #Form.myString# <br> 
 <br> 
 <b>Encrypted:</b> #encrypted#<br> 
 <br> 
 <b>Decrypted:</b> #decrypted#<br> 
 </cfoutput> 
 </cfif> 
 
 <!--- The input form.---> 
 <form action="#CGI.SCRIPT_NAME#" method="post"> 
 <b>Select the encoding</b><br> 
 <select size="1" name="myEncoding"> 
 <option selected>UU</option> 
 <option>Base64</option> 
 <option>Hex</option> 
 </select><br> 
 <br> 
 <b>Select the algorithm</b><br> 
 <select size="1" name="myAlgorithm"> 
 <option selected>CFMX_COMPAT</option> 
 <option>AES</option> 
 <option>DES</option> 
 <option>DESEDE</option> 
 </select><br> 
 <br> 
 <b>Input your key</b> (used for CFMX_COMPAT encryption only)<br> 
 <input type = "Text" name = "myKey" value = "MyKey"><br> 
 <br> 
 <b>Enter string to encrypt</b><br> 
 <textArea name = "myString" cols = "40" rows = "5" WRAP = "VIRTUAL">This string will be encrypted (you can replace it with more typing). 
 </textArea><br> 
 <input type = "Submit" value = "Encrypt my String"> 
 </form>
<cfscript>
    myMessage = "Message to encrypt"
    key = generateSecretKey('AES');
    encryptedMsg = encrypt(myMessage,key,'AES', 'Base64');
    writeOutput(encryptedMsg);
</cfscript>
Output
JbRh2Ez58OJc9wpZUDefz0GZyDnA0/IMuV9qaRcFzCY=
EXAMPLE 2
<cfscript>  
    // string data  
    a = "abcd"  
    // generate the key  
    key = GenerateSecretKey("AES")  
    iterations="AssoicatedData"  
    randomIntegers = [];  
    // generate the SALT value  
    for ( i = 1 ; i <= 12 ; i++ ) {  
        arrayAppend( randomIntegers, randRange( -128, 127, "SHA1PRNG" ) );  
    }  
    initializationVector = javaCast( "byte[]", randomIntegers )  
    enc1 = Encrypt(string=a,   
                   key=key,   
                   encoding="UU",   
                   algorithm="AES/GCM/NoPadding",  
                   IV_Salt=initializationVector,   
                   iterations=iterations)  
    writeDump(enc1)  
</cfscript>
Output
4Z1!>"1'E8=$3Y%'"KJ!/T-3S?[X

Real-world uses of the Encrypt function

Customer data protection and GDPR compliance

E-commerce and SaaS companies must protect customer PII (Personally Identifiable Information) to comply with GDPR, CCPA, and other privacy regulations. Storing customer data in plaintext creates significant liability risks, regulatory violations, and potential data breach costs averaging over $4 million. Use Encrypt to secure sensitive customer data like SSNs, addresses, payment information, and personal details.
<!--- Encrypt: Customer Data Protection & GDPR Compliance --->
<cfscript>
    // Sample customer data requiring PII protection
    customerDatabase = [
        {"customerId": "CUST001", "name": "Sarah Johnson", "ssn": "123-45-6789", "email": "sarah.j@email.com", "phone": "555-0123", "address": "123 Main St, Anytown, ST 12345", "dob": "1985-03-15"},
        {"customerId": "CUST002", "name": "Michael Brown", "ssn": "987-65-4321", "email": "mike.b@email.com", "phone": "555-0456", "address": "456 Oak Ave, Another City, ST 67890", "dob": "1978-11-22"},
        {"customerId": "CUST003", "name": "Lisa Garcia", "ssn": "456-78-9012", "email": "lisa.g@email.com", "phone": "555-0789", "address": "789 Pine Rd, Somewhere, ST 54321", "dob": "1992-07-08"},
        {"customerId": "CUST004", "name": "David Wilson", "ssn": "321-54-9876", "email": "david.w@email.com", "phone": "555-0321", "address": "321 Elm Dr, Elsewhere, ST 98765", "dob": "1990-05-12"}
    ];
    
    // Generate secure encryption key for customer PII
    customerEncryptionKey = GenerateSecretKey("AES");
</cfscript>

<h1>🛡️ Encrypt: Customer Data Protection Demo</h1>
<p><strong>Business Need:</strong> GDPR-compliant protection of customer personally identifiable information</p>
<p><strong>Challenge:</strong> Store sensitive customer data securely while maintaining operational efficiency</p>
<p><strong>Solution:</strong> Use Encrypt() with AES-256 to protect PII and meet regulatory requirements</p>
<hr>

<cfoutput>
    <h2>📊 Customer Data Protection Dashboard</h2>
    <p><strong>Protection Standard:</strong> AES-256 encryption with Base64 encoding</p>
    <p><strong>Compliance:</strong> GDPR Article 32 - Technical and organizational measures</p>
    
    <cfscript>
        totalCustomers = ArrayLen(customerDatabase);
        encryptedFields = 0;
        processingErrors = 0;
        
        // Function to encrypt customer PII
        function protectCustomerPII(customer, encryptionKey) {
            local.protectedRecord = {};
            local.protectedRecord["customerId"] = customer.customerId; // Non-sensitive identifier
            local.protectedRecord["name"] = customer.name; // May remain unencrypted for operational use
            
            try {
                // Encrypt sensitive PII fields
                local.protectedRecord["ssn_encrypted"] = Encrypt(customer.ssn, encryptionKey, "AES", "Base64");
                local.protectedRecord["email_encrypted"] = Encrypt(customer.email, encryptionKey, "AES", "Base64");
                local.protectedRecord["phone_encrypted"] = Encrypt(customer.phone, encryptionKey, "AES", "Base64");
                local.protectedRecord["address_encrypted"] = Encrypt(customer.address, encryptionKey, "AES", "Base64");
                local.protectedRecord["dob_encrypted"] = Encrypt(customer.dob, encryptionKey, "AES", "Base64");
                
                // Add GDPR compliance metadata
                local.protectedRecord["protected_date"] = DateTimeFormat(Now(), "yyyy-mm-dd HH:nn:ss");
                local.protectedRecord["encryption_algorithm"] = "AES-256";
                local.protectedRecord["gdpr_compliant"] = true;
                local.protectedRecord["data_controller"] = "Customer Service Department";
                
                return local.protectedRecord;
            } catch (any e) {
                WriteLog(file="gdpr_security", text="Customer PII encryption failed for " & customer.customerId & ": " & e.message, type="Error");
                return {"error": "PII protection failed", "customerId": customer.customerId};
            }
        }
        
        // Function to safely access customer data (for authorized personnel only)
        function accessCustomerPII(protectedRecord, encryptionKey, userRole = "", userId = "") {
            // GDPR requires documented lawful basis for processing
            local.authorizedRoles = "CustomerService,DataController,GDPR Officer,Manager";
            
            if (NOT ListFindNoCase(local.authorizedRoles, userRole)) {
                WriteLog(file="gdpr_audit", text="Unauthorized PII access attempt by " & userId & " (" & userRole & ")", type="Warning");
                return {"error": "Access to PII requires proper authorization"};
            }
            
            try {
                local.customerInfo = {};
                local.customerInfo["customerId"] = protectedRecord.customerId;
                local.customerInfo["name"] = protectedRecord.name;
                
                // Decrypt sensitive fields for authorized access
                local.customerInfo["ssn"] = Decrypt(protectedRecord.ssn_encrypted, encryptionKey, "AES", "Base64");
                local.customerInfo["email"] = Decrypt(protectedRecord.email_encrypted, encryptionKey, "AES", "Base64");
                local.customerInfo["phone"] = Decrypt(protectedRecord.phone_encrypted, encryptionKey, "AES", "Base64");
                local.customerInfo["address"] = Decrypt(protectedRecord.address_encrypted, encryptionKey, "AES", "Base64");
                local.customerInfo["dob"] = Decrypt(protectedRecord.dob_encrypted, encryptionKey, "AES", "Base64");
                
                // Calculate age for business use
                local.customerInfo["age"] = DateDiff("yyyy", local.customerInfo["dob"], Now());
                
                // Log access for GDPR audit trail (required by Article 30)
                WriteLog(file="gdpr_audit", text="Customer PII accessed: " & protectedRecord.customerId & " by " & userId & " (" & userRole & ") - Purpose: Customer service", type="Information");
                
                return local.customerInfo;
            } catch (any e) {
                WriteLog(file="gdpr_security", text="Customer PII access failed for " & protectedRecord.customerId & ": " & e.message, type="Error");
                return {"error": "PII access failed"};
            }
        }
        
        // Function to create anonymized data for analytics (GDPR Article 4)
        function anonymizeCustomerData(customer) {
            local.anonymized = {};
            local.anonymized["customerId"] = "ANON_" & Hash(customer.customerId, "SHA-256").substring(1, 8);
            local.anonymized["ageGroup"] = getAgeGroup(customer.dob);
            local.anonymized["locationRegion"] = getRegion(customer.address);
            local.anonymized["phoneAreaCode"] = Left(customer.phone, 3);
            local.anonymized["emailDomain"] = ListLast(customer.email, "@");
            
            return local.anonymized;
        }
        
        // Helper functions
        function getAgeGroup(dob) {
            local.age = DateDiff("yyyy", dob, Now());
            if (local.age LT 25) return "18-24";
            if (local.age LT 35) return "25-34";
            if (local.age LT 45) return "35-44";
            if (local.age LT 55) return "45-54";
            if (local.age LT 65) return "55-64";
            return "65+";
        }
        
        function getRegion(address) {
            // Simple region extraction based on state abbreviation
            local.state = Trim(ListGetAt(address, 2, ","));
            local.stateCode = Trim(ListLast(local.state, " "));
            
            // Group states into regions
            if (ListFindNoCase("NY,NJ,PA,CT,MA,VT,NH,ME,RI", local.stateCode)) return "Northeast";
            if (ListFindNoCase("FL,GA,SC,NC,VA,WV,KY,TN,AL,MS,AR,LA", local.stateCode)) return "Southeast";
            if (ListFindNoCase("OH,IN,IL,MI,WI,MN,IA,MO,ND,SD,NE,KS", local.stateCode)) return "Midwest";
            if (ListFindNoCase("TX,OK,NM,AZ,CO,WY,MT,UT,NV,ID", local.stateCode)) return "Southwest";
            if (ListFindNoCase("CA,OR,WA,AK,HI", local.stateCode)) return "West";
            return "Other";
        }
    </cfscript>
    
    <div style="background: ##f8f9fa; padding: 20px; border-radius: 8px;">
        <h3>🔐 Customer PII Protection Results</h3>
        
        <cfloop array="#customerDatabase#" index="customer">
            <cfscript>
                // Protect customer PII
                protectedCustomer = protectCustomerPII(customer, customerEncryptionKey);
                
                // Simulate authorized access by customer service representative
                authorizedAccess = accessCustomerPII(protectedCustomer, customerEncryptionKey, "CustomerService", "CS001");
                
                // Simulate unauthorized access attempt
                unauthorizedAccess = accessCustomerPII(protectedCustomer, customerEncryptionKey, "Intern", "INT001");
                
                // Create anonymized version for analytics
                anonymizedData = anonymizeCustomerData(customer);
                
                if (NOT StructKeyExists(protectedCustomer, "error")) {
                    encryptedFields += 5; // SSN, Email, Phone, Address, DOB
                } else {
                    processingErrors++;
                }
            </cfscript>
            
            <div style="background: white; padding: 20px; margin: 15px 0; border-radius: 8px; border-left: 5px solid ##28a745;">
                <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px;">
                    <div>
                        <h3 style="margin: 0;">#customer.name#</h3>
                        <p style="margin: 5px 0;"><strong>Customer ID:</strong> #customer.customerId#</p>
                    </div>
                    <span style="background: ##28a745; color: white; padding: 8px 15px; border-radius: 15px; font-weight: bold;">
                        ✅ GDPR COMPLIANT
                    </span>
                </div>
                
                <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 15px;">
                    <div>
                        <h4>🔒 Protected Data Storage</h4>
                        <div style="background: ##f8f9fa; padding: 10px; border-radius: 5px; font-family: monospace; font-size: 0.85em;">
                            <p><strong>SSN:</strong> #Left(protectedCustomer.ssn_encrypted, 20)#...</p>
                            <p><strong>Email:</strong> #Left(protectedCustomer.email_encrypted, 20)#...</p>
                            <p><strong>Phone:</strong> #Left(protectedCustomer.phone_encrypted, 20)#...</p>
                            <p><strong>Address:</strong> #Left(protectedCustomer.address_encrypted, 20)#...</p>
                            <p><strong>DOB:</strong> #Left(protectedCustomer.dob_encrypted, 20)#...</p>
                        </div>
                        <small><em>Encrypted with AES-256, Base64 encoded</em></small>
                    </div>
                    
                    <div>
                        <h4>👥 Authorized Access (Customer Service)</h4>
                        <cfif NOT StructKeyExists(authorizedAccess, "error")>
                            <div style="background: ##d4edda; padding: 10px; border-radius: 5px;">
                                <p><strong>Name:</strong> #authorizedAccess.name#</p>
                                <p><strong>Email:</strong> #authorizedAccess.email#</p>
                                <p><strong>Phone:</strong> #authorizedAccess.phone#</p>
                                <p><strong>Age:</strong> #authorizedAccess.age# years</p>
                                <p><strong>SSN:</strong> ***-**-#### (masked)</p>
                                <small><em>Access logged for audit trail</em></small>
                            </div>
                        <cfelse>
                            <div style="background: ##f8d7da; padding: 10px; border-radius: 5px;">
                                <p><strong>Error:</strong> #authorizedAccess.error#</p>
                            </div>
                        </cfif>
                    </div>
                    
                    <div>
                        <h4>🚫 Unauthorized Access Attempt</h4>
                        <div style="background: ##f8d7da; padding: 10px; border-radius: 5px;">
                            <p><strong>Status:</strong> ❌ Access Denied</p>
                            <p><strong>Reason:</strong> #unauthorizedAccess.error#</p>
                            <p><strong>Action:</strong> Security event logged</p>
                            <small><em>GDPR requires access controls</em></small>
                        </div>
                    </div>
                    
                    <div>
                        <h4>📊 Anonymized Analytics Data</h4>
                        <div style="background: ##e3f2fd; padding: 10px; border-radius: 5px;">
                            <p><strong>Anonymous ID:</strong> #anonymizedData.customerId#</p>
                            <p><strong>Age Group:</strong> #anonymizedData.ageGroup#</p>
                            <p><strong>Region:</strong> #anonymizedData.locationRegion#</p>
                            <p><strong>Email Domain:</strong> #anonymizedData.emailDomain#</p>
                            <small><em>Safe for analytics and reporting</em></small>
                        </div>
                    </div>
                </div>
                
                <div style="background: ##e8f5e8; padding: 15px; border-radius: 5px; margin-top: 15px;">
                    <h4>📋 GDPR Compliance Features:</h4>
                    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px;">
                        <div>
                            <p>✅ <strong>Data Protection by Design:</strong> AES-256 encryption</p>
                            <p>✅ <strong>Access Controls:</strong> Role-based authorization</p>
                            <p>✅ <strong>Audit Trail:</strong> Complete activity logging</p>
                            <p>✅ <strong>Data Minimization:</strong> Only necessary fields encrypted</p>
                        </div>
                        <div>
                            <p>✅ <strong>Right to Access:</strong> Secure data retrieval</p>
                            <p>✅ <strong>Right to Portability:</strong> Structured data export</p>
                            <p>✅ <strong>Anonymization:</strong> Analytics without PII</p>
                            <p>✅ <strong>Security Breach Prevention:</strong> Encrypted storage</p>
                        </div>
                    </div>
                </div>
            </div>
        </cfloop>
    </div>
    
    <h2>📈 GDPR Compliance Dashboard</h2>
    <div style="background: ##e8f5e8; padding: 20px; border-radius: 8px;">
        <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 15px; margin-bottom: 20px;">
            <div style="background: white; padding: 15px; text-align: center; border-radius: 8px;">
                <h3>Total Customers</h3>
                <h2 style="color: ##007bff;">#totalCustomers#</h2>
            </div>
            <div style="background: white; padding: 15px; text-align: center; border-radius: 8px;">
                <h3>Encrypted Fields</h3>
                <h2 style="color: ##28a745;">#encryptedFields#</h2>
            </div>
            <div style="background: white; padding: 15px; text-align: center; border-radius: 8px;">
                <h3>Processing Errors</h3>
                <h2 style="color: ##dc3545;">#processingErrors#</h2>
            </div>
            <div style="background: white; padding: 15px; text-align: center; border-radius: 8px;">
                <h3>Compliance Rate</h3>
                <h2 style="color: ##6f42c1;">#NumberFormat(((encryptedFields / (totalCustomers * 5)) * 100), "0.0")#%</h2>
            </div>
        </div>
        
        <cfscript>
            // Calculate compliance metrics
            dataProtectionScore = (encryptedFields / (totalCustomers * 5)) * 100;
            riskReduction = 95; // Percentage risk reduction from encryption
            complianceCost = totalCustomers * 50; // Estimated compliance cost per customer
            breachRiskReduction = 4450000 * (riskReduction / 100); // Average breach cost * risk reduction
        </cfscript>
        
        <h3>📊 Business Impact Metrics:</h3>
        <div style="background: white; padding: 15px; border-radius: 5px; margin: 10px 0;">
            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px;">
                <div>
                    <p><strong>Data Protection Score:</strong> #NumberFormat(dataProtectionScore, "0.0")#%</p>
                    <p><strong>Risk Reduction:</strong> #riskReduction#%</p>
                    <p><strong>Compliance Investment:</strong> $#NumberFormat(complianceCost, "9,999")#</p>
                    <p><strong>Audit Readiness:</strong> 100% (Complete audit trail)</p>
                </div>
                <div>
                    <p><strong>Breach Risk Reduction:</strong> $#NumberFormat(breachRiskReduction, "9,999,999")#</p>
                    <p><strong>Customer Trust Score:</strong> High (Transparent data protection)</p>
                    <p><strong>Regulatory Status:</strong> Fully Compliant</p>
                    <p><strong>Data Retention Policy:</strong> Automated (Right to be forgotten)</p>
                </div>
            </div>
        </div>
        
        <h3>🎯 GDPR Article Compliance:</h3>
        <div style="background: white; padding: 15px; border-radius: 5px; margin: 10px 0;">
            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px;">
                <div>
                    <p>📜 <strong>Article 25:</strong> Data protection by design and default</p>
                    <p>🔒 <strong>Article 32:</strong> Security of processing (encryption)</p>
                    <p>📋 <strong>Article 30:</strong> Records of processing activities</p>
                    <p>👥 <strong>Article 15:</strong> Right of access by data subject</p>
                </div>
                <div>
                    <p>📤 <strong>Article 20:</strong> Right to data portability</p>
                    <p>🗑️ <strong>Article 17:</strong> Right to erasure (right to be forgotten)</p>
                    <p>⚠️ <strong>Article 33:</strong> Notification of personal data breach</p>
                    <p>🛡️ <strong>Article 5:</strong> Principles relating to processing</p>
                </div>
            </div>
        </div>
    </div>
</cfoutput>

Payment processing and financial security

Financial institutions and e-commerce platforms handle sensitive payment data requiring PCI DSS compliance and fraud prevention. Payment data breaches cost millions of dollars and result in loss of payment processing privileges, devastating business operations. Use Encrypt to secure credit card numbers, bank account details, payment tokens, and transaction history.
<!--- Encrypt: Payment Processing & Financial Security --->
<cfscript>
    // Sample payment data requiring PCI DSS protection
    paymentTransactions = [
        {"transactionId": "TXN001", "cardNumber": "4111111111111111", "expiryDate": "12/25", "cvv": "123", "amount": 299.99, "merchantId": "MERCH001", "cardholderName": "Sarah Johnson"},
        {"transactionId": "TXN002", "cardNumber": "5555555555554444", "expiryDate": "06/26", "cvv": "456", "amount": 156.75, "merchantId": "MERCH002", "cardholderName": "Michael Brown"},
        {"transactionId": "TXN003", "cardNumber": "378282246310005", "expiryDate": "09/27", "cvv": "789", "amount": 1299.00, "merchantId": "MERCH003", "cardholderName": "Lisa Garcia"},
        {"transactionId": "TXN004", "cardNumber": "6011111111111117", "expiryDate": "03/28", "cvv": "321", "amount": 89.50, "merchantId": "MERCH001", "cardholderName": "David Wilson"}
    ];
    
    // Generate PCI DSS compliant encryption key
    paymentEncryptionKey = GenerateSecretKey("AES");
</cfscript>

<h1>💳 Encrypt: Payment Processing Security Demo</h1>
<p><strong>Business Need:</strong> PCI DSS compliant protection of cardholder data and payment information</p>
<p><strong>Challenge:</strong> Secure payment processing while maintaining transaction speed and compliance</p>
<p><strong>Solution:</strong> Use Encrypt() with AES-256 to protect payment data and meet PCI DSS requirements</p>
<hr>

<cfoutput>
    <h2>🏦 Payment Security Dashboard</h2>
    <p><strong>Security Standard:</strong> PCI DSS Level 1 - AES-256 encryption</p>
    <p><strong>Compliance:</strong> PCI DSS Requirement 3 - Protect stored cardholder data</p>
    
    <cfscript>
        totalTransactions = ArrayLen(paymentTransactions);
        secureTransactions = 0;
        securityFailures = 0;
        totalRevenue = 0;
        
        // Function to securely encrypt payment data
        function securePaymentData(transaction, encryptionKey) {
            local.secureTxn = {};
            local.secureTxn["transactionId"] = transaction.transactionId;
            local.secureTxn["merchantId"] = transaction.merchantId;
            local.secureTxn["amount"] = transaction.amount; // Amount may remain unencrypted for processing
            local.secureTxn["cardholderName"] = transaction.cardholderName; // Name typically encrypted in production
            
            try {
                // Encrypt sensitive cardholder data (PCI DSS Requirement 3)
                local.secureTxn["cardNumber_encrypted"] = Encrypt(transaction.cardNumber, encryptionKey, "AES", "Base64");
                local.secureTxn["expiryDate_encrypted"] = Encrypt(transaction.expiryDate, encryptionKey, "AES", "Base64");
                local.secureTxn["cvv_encrypted"] = Encrypt(transaction.cvv, encryptionKey, "AES", "Base64");
                
                // Create PAN (Primary Account Number) mask for display
                local.secureTxn["cardDisplay"] = "****-****-****-" & Right(transaction.cardNumber, 4);
                
                // Determine card type for processing
                local.secureTxn["cardType"] = getCardType(transaction.cardNumber);
                
                // Add PCI DSS compliance metadata
                local.secureTxn["pci_compliant"] = true;
                local.secureTxn["encryption_standard"] = "AES-256-PCI";
                local.secureTxn["protected_date"] = DateTimeFormat(Now(), "yyyy-mm-dd HH:nn:ss");
                local.secureTxn["data_retention_policy"] = "90_days_max";
                
                // Security logging for fraud detection
                WriteLog(file="pci_security", text="Payment data encrypted: Transaction " & transaction.transactionId, type="Information");
                
                return local.secureTxn;
            } catch (any e) {
                WriteLog(file="pci_security", text="Payment encryption failed for transaction " & transaction.transactionId & ": " & e.message, type="Error");
                return {"error": "Payment encryption failed", "transactionId": transaction.transactionId};
            }
        }
        
        // Function to process secure payment (requires special authorization)
        function processSecurePayment(secureTxn, encryptionKey, processorId = "", authorized = false) {
            // PCI DSS requires strict access controls for cardholder data
            if (NOT authorized) {
                WriteLog(file="pci_security", text="Unauthorized payment processing attempt by " & processorId, type="Warning");
                return {"error": "Unauthorized access to cardholder data"};
            }
            
            try {
                local.paymentResult = {};
                local.paymentResult["transactionId"] = secureTxn.transactionId;
                local.paymentResult["amount"] = secureTxn.amount;
                local.paymentResult["cardDisplay"] = secureTxn.cardDisplay;
                local.paymentResult["cardType"] = secureTxn.cardType;
                
                // Decrypt for payment processing only (never for display)
                local.cardNumber = Decrypt(secureTxn.cardNumber_encrypted, encryptionKey, "AES", "Base64");
                local.expiryDate = Decrypt(secureTxn.expiryDate_encrypted, encryptionKey, "AES", "Base64");
                local.cvv = Decrypt(secureTxn.cvv_encrypted, encryptionKey, "AES", "Base64");
                
                // Validate card number using Luhn algorithm
                local.paymentResult["luhnValid"] = validateLuhn(local.cardNumber);
                
                // Check expiry date
                local.paymentResult["expiryValid"] = validateExpiry(local.expiryDate);
                
                // Simulate payment processing result
                local.processingSuccess = local.paymentResult["luhnValid"] AND local.paymentResult["expiryValid"];
                local.paymentResult["processingStatus"] = local.processingSuccess ? "Approved" : "Declined";
                local.paymentResult["authorizationCode"] = local.processingSuccess ? "AUTH" & RandRange(100000, 999999) : "";
                
                // Log payment processing for audit (PCI DSS Requirement 10)
                WriteLog(file="pci_audit", text="Payment processed: " & secureTxn.transactionId & " - Status: " & local.paymentResult["processingStatus"], type="Information");
                
                return local.paymentResult;
            } catch (any e) {
                WriteLog(file="pci_security", text="Payment processing failed for transaction " & secureTxn.transactionId & ": " & e.message, type="Error");
                return {"error": "Payment processing failed"};
            }
        }
        
        // Helper function to determine card type
        function getCardType(cardNumber) {
            local.firstDigit = Left(cardNumber, 1);
            local.firstTwo = Left(cardNumber, 2);
            local.firstFour = Left(cardNumber, 4);
            
            // Visa: starts with 4
            if (local.firstDigit EQ "4") return "Visa";
            
            // MasterCard: starts with 5 or 2221-2720
            if (local.firstDigit EQ "5" OR (local.firstFour GE "2221" AND local.firstFour LE "2720")) return "MasterCard";
            
            // American Express: starts with 34 or 37
            if (local.firstTwo EQ "34" OR local.firstTwo EQ "37") return "American Express";
            
            // Discover: starts with 6011, 622126-622925, 644-649, or 65
            if (local.firstFour EQ "6011" OR Left(cardNumber, 2) EQ "65") return "Discover";
            
            return "Unknown";
        }
        
        // Luhn algorithm validation for card numbers
        function validateLuhn(cardNumber) {
            local.sum = 0;
            local.alternate = false;
            
            // Process from right to left
            for (local.i = Len(cardNumber); local.i GTE 1; local.i--) {
                local.digit = Val(Mid(cardNumber, local.i, 1));
                
                if (local.alternate) {
                    local.digit *= 2;
                    if (local.digit GT 9) {
                        local.digit = (local.digit \ 10) + (local.digit MOD 10);
                    }
                }
                
                local.sum += local.digit;
                local.alternate = NOT local.alternate;
            }
            
            return (local.sum MOD 10) EQ 0;
        }
        
        // Validate expiry date
        function validateExpiry(expiryDate) {
            try {
                local.parts = ListToArray(expiryDate, "/");
                local.month = Val(local.parts[1]);
                local.year = 2000 + Val(local.parts[2]);
                
                // Check if date is in the future
                local.expiryDateTime = CreateDate(local.year, local.month, DaysInMonth(CreateDate(local.year, local.month, 1)));
                return DateCompare(Now(), local.expiryDateTime, "d") LTE 0;
            } catch (any e) {
                return false;
            }
        }
        
        // Function to create payment receipt data (non-sensitive)
        function createPaymentReceipt(paymentResult) {
            local.receipt = {};
            local.receipt["receiptId"] = "RCP_" & paymentResult.transactionId;
            local.receipt["transactionId"] = paymentResult.transactionId;
            local.receipt["amount"] = paymentResult.amount;
            local.receipt["cardType"] = paymentResult.cardType;
            local.receipt["cardDisplay"] = paymentResult.cardDisplay;
            local.receipt["authCode"] = paymentResult.authorizationCode;
            local.receipt["status"] = paymentResult.processingStatus;
            local.receipt["timestamp"] = DateTimeFormat(Now(), "yyyy-mm-dd HH:nn:ss");
            
            return local.receipt;
        }
    </cfscript>
    
    <div style="background: ##f8f9fa; padding: 20px; border-radius: 8px;">
        <h3>💳 Payment Processing Results</h3>
        
        <cfloop array="#paymentTransactions#" index="transaction">
            <cfscript>
                // Secure the payment data
                securePayment = securePaymentData(transaction, paymentEncryptionKey);
                
                // Process payment with authorized access
                paymentResult = processSecurePayment(securePayment, paymentEncryptionKey, "PROCESSOR001", true);
                
                // Simulate unauthorized access attempt
                unauthorizedResult = processSecurePayment(securePayment, paymentEncryptionKey, "UNAUTHORIZED", false);
                
                // Create customer receipt
                if (NOT StructKeyExists(paymentResult, "error")) {
                    receipt = createPaymentReceipt(paymentResult);
                    secureTransactions++;
                    
                    if (paymentResult.processingStatus EQ "Approved") {
                        totalRevenue += transaction.amount;
                    }
                } else {
                    securityFailures++;
                }
            </cfscript>
            
            <div style="background: white; padding: 20px; margin: 15px 0; border-radius: 8px; border-left: 5px solid ##007bff;">
                <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px;">
                    <div>
                        <h3 style="margin: 0;">Transaction #transaction.transactionId#</h3>
                        <p style="margin: 5px 0;"><strong>Amount:</strong> $#NumberFormat(transaction.amount, "999.00")# | <strong>Merchant:</strong> #transaction.merchantId#</p>
                    </div>
                    <span style="background: ##007bff; color: white; padding: 8px 15px; border-radius: 15px; font-weight: bold;">
                        🔒 PCI DSS COMPLIANT
                    </span>
                </div>
                
                <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); gap: 15px;">
                    <div>
                        <h4>🔐 Encrypted Storage</h4>
                        <div style="background: ##f8f9fa; padding: 10px; border-radius: 5px; font-family: monospace; font-size: 0.8em;">
                            <p><strong>Card:</strong> #Left(securePayment.cardNumber_encrypted, 20)#...</p>
                            <p><strong>Expiry:</strong> #Left(securePayment.expiryDate_encrypted, 16)#...</p>
                            <p><strong>CVV:</strong> #Left(securePayment.cvv_encrypted, 16)#...</p>
                            <p><strong>Algorithm:</strong> #securePayment.encryption_standard#</p>
                        </div>
                        <small><em>Encrypted for secure storage</em></small>
                    </div>
                    
                    <div>
                        <h4>💳 Payment Processing</h4>
                        <cfif NOT StructKeyExists(paymentResult, "error")>
                            <div style="background: #paymentResult.processingStatus EQ 'Approved' ? '##d4edda' : '##f8d7da'#; padding: 10px; border-radius: 5px;">
                                <p><strong>Card Type:</strong> #paymentResult.cardType#</p>
                                <p><strong>Card Display:</strong> #paymentResult.cardDisplay#</p>
                                <p><strong>Luhn Check:</strong> #paymentResult.luhnValid ? "✅ Valid" : "❌ Invalid"#</p>
                                <p><strong>Expiry Check:</strong> #paymentResult.expiryValid ? "✅ Valid" : "❌ Expired"#</p>
                                <p><strong>Status:</strong> #paymentResult.processingStatus#</p>
                                <cfif paymentResult.processingStatus EQ "Approved">
                                    <p><strong>Auth Code:</strong> #paymentResult.authorizationCode#</p>
                                </cfif>
                            </div>
                        <cfelse>
                            <div style="background: ##f8d7da; padding: 10px; border-radius: 5px;">
                                <p><strong>Error:</strong> #paymentResult.error#</p>
                            </div>
                        </cfif>
                    </div>
                    
                    <div>
                        <h4>🧾 Customer Receipt</h4>
                        <cfif isdefined("receipt")>
                            <div style="background: ##e8f5e8; padding: 10px; border-radius: 5px; border: 1px dashed ##28a745;">
                                <p><strong>Receipt:</strong> #receipt.receiptId#</p>
                                <p><strong>Date/Time:</strong> #receipt.timestamp#</p>
                                <p><strong>Card:</strong> #receipt.cardDisplay#</p>
                                <p><strong>Amount:</strong> $#NumberFormat(receipt.amount, "999.00")#</p>
                                <p><strong>Status:</strong> #receipt.status#</p>
                                <cfif receipt.status EQ "Approved">
                                    <p><strong>Auth:</strong> #receipt.authCode#</p>
                                </cfif>
                                <small><em>Safe for customer display</em></small>
                            </div>
                        <cfelse>
                            <div style="background: ##f8d7da; padding: 10px; border-radius: 5px;">
                                <p><strong>Receipt:</strong> Not generated due to processing error</p>
                            </div>
                        </cfif>
                    </div>
                    
                    <div>
                        <h4>🚫 Security Control Test</h4>
                        <div style="background: ##f8d7da; padding: 10px; border-radius: 5px;">
                            <p><strong>Unauthorized Access:</strong> ❌ Blocked</p>
                            <p><strong>Reason:</strong> #unauthorizedResult.error#</p>
                            <p><strong>Security Event:</strong> Logged for audit</p>
                            <small><em>PCI DSS access controls working</em></small>
                        </div>
                    </div>
                </div>
                
                <div style="background: ##e3f2fd; padding: 15px; border-radius: 5px; margin-top: 15px;">
                    <h4>🏛️ PCI DSS Compliance Checklist:</h4>
                    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px;">
                        <div>
                            <p>✅ <strong>Req 3.4:</strong> Strong cryptography (AES-256)</p>
                            <p>✅ <strong>Req 3.3:</strong> Mask PAN when displayed</p>
                            <p>✅ <strong>Req 7.1:</strong> Limit access by business need</p>
                            <p>✅ <strong>Req 8.2:</strong> Unique user identification</p>
                        </div>
                        <div>
                            <p>✅ <strong>Req 10.2:</strong> Automated audit trails</p>
                            <p>✅ <strong>Req 4.1:</strong> Strong cryptography for transmission</p>
                            <p>✅ <strong>Req 6.5:</strong> Secure coding practices</p>
                            <p>✅ <strong>Req 12.3:</strong> Daily operational security</p>
                        </div>
                    </div>
                </div>
            </div>
        </cfloop>
    </div>
    
    <h2>📊 Payment Security Analytics</h2>
    <div style="background: ##e8f5e8; padding: 20px; border-radius: 8px;">
        <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 15px; margin-bottom: 20px;">
            <div style="background: white; padding: 15px; text-align: center; border-radius: 8px;">
                <h3>Total Transactions</h3>
                <h2 style="color: ##007bff;">#totalTransactions#</h2>
            </div>
            <div style="background: white; padding: 15px; text-align: center; border-radius: 8px;">
                <h3>Secured</h3>
                <h2 style="color: ##28a745;">#secureTransactions#</h2>
            </div>
            <div style="background: white; padding: 15px; text-align: center; border-radius: 8px;">
                <h3>Security Failures</h3>
                <h2 style="color: ##dc3545;">#securityFailures#</h2>
            </div>
            <div style="background: white; padding: 15px; text-align: center; border-radius: 8px;">
                <h3>Revenue Protected</h3>
                <h2 style="color: ##6f42c1;">$#NumberFormat(totalRevenue, "9,999")#</h2>
            </div>
        </div>
        
        <cfscript>
            // Calculate security and compliance metrics
            securitySuccessRate = (secureTransactions / totalTransactions) * 100;
            encryptionEfficiency = 99.9; // Encryption processing efficiency
            complianceScore = securitySuccessRate; // Overall compliance score
            fraudPrevention = 85; // Estimated fraud prevention percentage
            
            // Calculate business impact
            breachRiskReduction = 10900000 * 0.95; // Average financial breach cost * risk reduction
            complianceCost = totalTransactions * 15; // Cost per transaction for compliance
            fraudSavings = totalRevenue * (fraudPrevention / 100) * 0.05; // 5% fraud rate prevented
        </cfscript>
        
        <h3>💼 Business Impact Analysis:</h3>
        <div style="background: white; padding: 15px; border-radius: 5px; margin: 10px 0;">
            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px;">
                <div>
                    <p><strong>Security Success Rate:</strong> #NumberFormat(securitySuccessRate, "0.0")#%</p>
                    <p><strong>Encryption Efficiency:</strong> #encryptionEfficiency#%</p>
                    <p><strong>PCI Compliance Score:</strong> #NumberFormat(complianceScore, "0.0")#%</p>
                    <p><strong>Fraud Prevention:</strong> #fraudPrevention#%</p>
                </div>
                <div>
                    <p><strong>Breach Risk Reduction:</strong> $#NumberFormat(breachRiskReduction, "99,999,999")#</p>
                    <p><strong>Compliance Investment:</strong> $#NumberFormat(complianceCost, "999")#</p>
                    <p><strong>Fraud Savings:</strong> $#NumberFormat(fraudSavings, "999.00")#</p>
                    <p><strong>ROI Timeframe:</strong> 3 months</p>
                </div>
            </div>
        </div>
        
        <h3>🎯 PCI DSS Requirements Status:</h3>
        <div style="background: white; padding: 15px; border-radius: 5px; margin: 10px 0;">
            <div style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 15px;">
                <div>
                    <p>🔒 <strong>Req 3:</strong> Protect cardholder data ✅</p>
                    <p>🔐 <strong>Req 4:</strong> Encrypt transmission ✅</p>
                    <p>🛡️ <strong>Req 7:</strong> Restrict access ✅</p>
                    <p>👤 <strong>Req 8:</strong> Identify users ✅</p>
                </div>
                <div>
                    <p>📊 <strong>Req 10:</strong> Track access ✅</p>
                    <p>🧪 <strong>Req 11:</strong> Test security ✅</p>
                    <p>📋 <strong>Req 12:</strong> Maintain policy ✅</p>
                    <p>🔍 <strong>Req 1:</strong> Install firewall ✅</p>
                </div>
                <div>
                    <p>🚫 <strong>Req 2:</strong> Change defaults ✅</p>
                    <p>🔑 <strong>Req 5:</strong> Use antivirus ✅</p>
                    <p>🛠️ <strong>Req 6:</strong> Secure systems ✅</p>
                    <p>🌐 <strong>Req 9:</strong> Restrict physical ✅</p>
                </div>
            </div>
        </div>
        
        <cfif securityFailures GT 0>
            <div style="background: ##f8d7da; padding: 15px; border-radius: 5px; margin: 10px 0;">
                <h4>⚠️ Security Alerts:</h4>
                <p><strong>Failures Detected:</strong> #securityFailures# transaction(s) failed encryption</p>
                <p><strong>Action Required:</strong> Review security logs and investigate failures</p>
                <p><strong>Compliance Impact:</strong> Address failures to maintain PCI DSS compliance</p>
            </div>
        <cfelse>
            <div style="background: ##d4edda; padding: 15px; border-radius: 5px; margin: 10px 0;">
                <h4>✅ Security Status: Optimal</h4>
                <p><strong>All Transactions:</strong> Successfully encrypted and processed</p>
                <p><strong>Compliance Status:</strong> Fully PCI DSS compliant</p>
                <p><strong>Risk Level:</strong> Minimal - All controls functioning properly</p>
            </div>
        </cfif>
    </div>
</cfoutput>

User authentication and session security

Web applications and SaaS platforms need secure user authentication and session management to prevent account takeovers and unauthorized access. Weak password storage and session management lead to account breaches, affecting majority of data breaches. Use Encrypt to secure password hashes, session tokens, API keys, and authentication credentials.
<!--- Encrypt: User Authentication & Session Security --->
<cfscript>
    // Sample user authentication data
    userAccounts = [
        {"userId": "USR001", "username": "johndoe", "password": "SecurePass123!", "email": "john@company.com", "role": "Manager", "apiKey": "ak_live_5B3mN8fGhK9qL2pW", "sessionToken": "sess_1a2b3c4d5e6f7g8h"},
        {"userId": "USR002", "username": "janedoe", "password": "MyStr0ngP@ssw0rd", "email": "jane@company.com", "role": "Developer", "apiKey": "ak_live_9X7cV1eRtY3uI8oP", "sessionToken": "sess_9z8y7x6w5v4u3t2s"},
        {"userId": "USR003", "username": "adminuser", "password": "Admin2024##Secure", "email": "admin@company.com", "role": "Administrator", "apiKey": "ak_live_2Q4wE6rT8yU1iO5p", "sessionToken": "sess_a1s2d3f4g5h6j7k8"}
    ];
    
    // Generate secure encryption keys for different authentication components
    passwordEncryptionKey = GenerateSecretKey("AES");
    sessionEncryptionKey = GenerateSecretKey("AES");
    apiKeyEncryptionKey = GenerateSecretKey("AES");
</cfscript>

<h1>🔐 Encrypt: User Authentication Security Demo</h1>
<p><strong>Business Need:</strong> Secure user credentials, session management, and API key protection</p>
<p><strong>Challenge:</strong> Prevent credential theft, session hijacking, and unauthorized API access</p>
<p><strong>Solution:</strong> Use Encrypt() with multi-layer security for comprehensive authentication protection</p>
<hr>

<cfoutput>
    <h2>🔑 Authentication Security Dashboard</h2>
    <p><strong>Security Approach:</strong> Multi-layer encryption with hashing and secure key management</p>
    <p><strong>Standards:</strong> OWASP Authentication Guidelines and NIST Cybersecurity Framework</p>
    
    <cfscript>
        totalUsers = ArrayLen(userAccounts);
        secureCredentials = 0;
        activeeSessions = 0;
        protectedApiKeys = 0;
        
        // Function to securely store user passwords
        function secureUserPassword(plainPassword, encryptionKey) {
            try {
                // Generate unique salt for each password
                local.salt = GenerateSecretKey("AES");
                
                // Hash password with salt (first layer of security)
                local.saltedPassword = plainPassword & local.salt;
                local.hashedPassword = Hash(local.saltedPassword, "SHA-256");
                
                // Encrypt the hash (second layer of security)
                local.encryptedHash = Encrypt(local.hashedPassword, encryptionKey, "AES", "Base64");
                
                return {
                    "encrypted_hash": local.encryptedHash,
                    "salt": local.salt,
                    "algorithm": "SHA-256+AES-256",
                    "strength_score": calculatePasswordStrength(plainPassword),
                    "created_date": DateTimeFormat(Now(), "yyyy-mm-dd HH:nn:ss")
                };
            } catch (any e) {
                WriteLog(file="auth_security", text="Password encryption failed: " & e.message, type="Error");
                return {"error": "Password encryption failed"};
            }
        }
        
        // Function to encrypt session tokens
        function secureSessionToken(sessionToken, encryptionKey) {
            try {
                local.encryptedToken = Encrypt(sessionToken, encryptionKey, "AES", "Base64");
                local.tokenHash = Hash(sessionToken, "SHA-256");
                
                return {
                    "encrypted_token": local.encryptedToken,
                    "token_hash": local.tokenHash,
                    "expires_at": DateAdd("h", 8, Now()), // 8-hour session
                    "created_at": DateTimeFormat(Now(), "yyyy-mm-dd HH:nn:ss"),
                    "secure": true
                };
            } catch (any e) {
                WriteLog(file="auth_security", text="Session token encryption failed: " & e.message, type="Error");
                return {"error": "Session encryption failed"};
            }
        }
        
        // Function to protect API keys
        function protectApiKey(apiKey, encryptionKey) {
            try {
                local.encryptedKey = Encrypt(apiKey, encryptionKey, "AES", "Base64");
                local.keyHash = Hash(apiKey, "SHA-256");
                local.keyPrefix = Left(apiKey, 8) & "...";
                
                return {
                    "encrypted_key": local.encryptedKey,
                    "key_hash": local.keyHash,
                    "key_preview": local.keyPrefix,
                    "algorithm": "AES-256",
                    "last_used": DateTimeFormat(Now(), "yyyy-mm-dd HH:nn:ss"),
                    "active": true
                };
            } catch (any e) {
                WriteLog(file="auth_security", text="API key encryption failed: " & e.message, type="Error");
                return {"error": "API key encryption failed"};
            }
        }
        
        // Function to verify user credentials during login
        function verifyUserCredentials(username, providedPassword, storedCredentials, encryptionKey) {
            try {
                // Decrypt stored password hash
                local.storedHash = Decrypt(storedCredentials.encrypted_hash, encryptionKey, "AES", "Base64");
                
                // Hash provided password with stored salt
                local.providedSaltedPassword = providedPassword & storedCredentials.salt;
                local.providedHash = Hash(local.providedSaltedPassword, "SHA-256");
                
                // Compare hashes for authentication
                local.isAuthenticated = (local.storedHash EQ local.providedHash);
                
                if (local.isAuthenticated) {
                    WriteLog(file="auth_audit", text="Successful authentication: " & username, type="Information");
                } else {
                    WriteLog(file="auth_security", text="Failed authentication attempt: " & username, type="Warning");
                }
                
                return {
                    "authenticated": local.isAuthenticated,
                    "timestamp": DateTimeFormat(Now(), "yyyy-mm-dd HH:nn:ss"),
                    "method": "encrypted_hash_comparison"
                };
            } catch (any e) {
                WriteLog(file="auth_security", text="Credential verification failed for " & username & ": " & e.message, type="Error");
                return {"authenticated": false, "error": "Verification failed"};
            }
        }
        
        // Function to validate session tokens
        function validateSessionToken(encryptedSession, providedToken, encryptionKey) {
            try {
                // Decrypt stored session token
                local.storedToken = Decrypt(encryptedSession.encrypted_token, encryptionKey, "AES", "Base64");
                
                // Check token match and expiration
                local.tokenValid = (local.storedToken EQ providedToken);
                local.notExpired = DateCompare(Now(), encryptedSession.expires_at, "n") LT 0;
                
                local.sessionValid = local.tokenValid AND local.notExpired;
                
                if (local.sessionValid) {
                    WriteLog(file="auth_audit", text="Valid session token accessed", type="Information");
                } else {
                    WriteLog(file="auth_security", text="Invalid or expired session token", type="Warning");
                }
                
                return {
                    "valid": local.sessionValid,
                    "token_match": local.tokenValid,
                    "not_expired": local.notExpired,
                    "expires_at": encryptedSession.expires_at
                };
            } catch (any e) {
                WriteLog(file="auth_security", text="Session validation failed: " & e.message, type="Error");
                return {"valid": false, "error": "Session validation failed"};
            }
        }
        
        // Helper function to calculate password strength
        function calculatePasswordStrength(password) {
            local.score = 0;
            
            // Length check
            if (Len(password) GTE 8) local.score += 25;
            if (Len(password) GTE 12) local.score += 15;
            
            // Character type checks
            if (REFind("[a-z]", password)) local.score += 15; // lowercase
            if (REFind("[A-Z]", password)) local.score += 15; // uppercase
            if (REFind("[0-9]", password)) local.score += 15; // numbers
            if (REFind('[!@##$%^&*(),.?":{}|<>]', password)) local.score += 15; // special characters
            
            return Min(local.score, 100);
        }
    </cfscript>
    
    <div style="background: ##f8f9fa; padding: 20px; border-radius: 8px;">
        <h3>🔐 User Authentication Security Results</h3>
        
        <cfloop array="#userAccounts#" index="user">
            <cfscript>
                // Secure user credentials
                securePassword = secureUserPassword(user.password, passwordEncryptionKey);
                secureSession = secureSessionToken(user.sessionToken, sessionEncryptionKey);
                secureAPI = protectApiKey(user.apiKey, apiKeyEncryptionKey);
                
                // Verify authentication works correctly
                authResult = verifyUserCredentials(user.username, user.password, securePassword, passwordEncryptionKey);
                sessionResult = validateSessionToken(secureSession, user.sessionToken, sessionEncryptionKey);
                
                // Count successful security implementations
                if (NOT StructKeyExists(securePassword, "error")) secureCredentials++;
                if (NOT StructKeyExists(secureSession, "error") AND sessionResult.valid) activeeSessions++;
                if (NOT StructKeyExists(secureAPI, "error")) protectedApiKeys++;
            </cfscript>
            
            <div style="background: white; padding: 20px; margin: 15px 0; border-radius: 8px; border-left: 5px solid ##6f42c1;">
                <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px;">
                    <div>
                        <h3 style="margin: 0;">#user.username#</h3>
                        <p style="margin: 5px 0;"><strong>Role:</strong> #user.role# | <strong>Email:</strong> #user.email#</p>
                    </div>
                    <span style="background: ##6f42c1; color: white; padding: 8px 15px; border-radius: 15px; font-weight: bold;">
                        🔐 SECURE AUTH
                    </span>
                </div>
                
                <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); gap: 15px;">
                    <div>
                        <h4>🔒 Password Security</h4>
                        <cfif NOT StructKeyExists(securePassword, "error")>
                            <div style="background: ##f8f9fa; padding: 10px; border-radius: 5px;">
                                <p><strong>Algorithm:</strong> #securePassword.algorithm#</p>
                                <p><strong>Strength:</strong> #securePassword.strength_score#/100</p>
                                <p><strong>Encrypted Hash:</strong> #Left(securePassword.encrypted_hash, 16)#...</p>
                                <p><strong>Salt Length:</strong> #Len(securePassword.salt)# chars</p>
                                <p><strong>Authentication:</strong> #authResult.authenticated ? "✅ Valid" : "❌ Failed"#</p>
                            </div>
                        <cfelse>
                            <div style="background: ##f8d7da; padding: 10px; border-radius: 5px;">
                                <p><strong>Error:</strong> #securePassword.error#</p>
                            </div>
                        </cfif>
                    </div>
                    
                    <div>
                        <h4>🎫 Session Management</h4>
                        <cfif NOT StructKeyExists(secureSession, "error")>
                            <div style="background: ##f8f9fa; padding: 10px; border-radius: 5px;">
                                <p><strong>Encrypted Token:</strong> #Left(secureSession.encrypted_token, 16)#...</p>
                                <p><strong>Token Hash:</strong> #Left(secureSession.token_hash, 12)#...</p>
                                <p><strong>Expires:</strong> #TimeFormat(secureSession.expires_at, "h:nn tt")#</p>
                                <p><strong>Valid:</strong> #sessionResult.valid ? "✅ Active" : "❌ Invalid"#</p>
                                <p><strong>Status:</strong> #sessionResult.not_expired ? "Current" : "Expired"#</p>
                            </div>
                        <cfelse>
                            <div style="background: ##f8d7da; padding: 10px; border-radius: 5px;">
                                <p><strong>Error:</strong> #secureSession.error#</p>
                            </div>
                        </cfif>
                    </div>
                    
                    <div>
                        <h4>🔑 API Key Protection</h4>
                        <cfif NOT StructKeyExists(secureAPI, "error")>
                            <div style="background: ##f8f9fa; padding: 10px; border-radius: 5px;">
                                <p><strong>Key Preview:</strong> #secureAPI.key_preview#</p>
                                <p><strong>Encrypted Key:</strong> #Left(secureAPI.encrypted_key, 16)#...</p>
                                <p><strong>Algorithm:</strong> #secureAPI.algorithm#</p>
                                <p><strong>Status:</strong> #secureAPI.active ? "✅ Active" : "❌ Inactive"#</p>
                                <p><strong>Last Used:</strong> #TimeFormat(secureAPI.last_used, "h:nn tt")#</p>
                            </div>
                        <cfelse>
                            <div style="background: ##f8d7da; padding: 10px; border-radius: 5px;">
                                <p><strong>Error:</strong> #secureAPI.error#</p>
                            </div>
                        </cfif>
                    </div>
                </div>
                
                <div style="background: ##f3e5f5; padding: 15px; border-radius: 5px; margin-top: 15px;">
                    <h4>🛡️ Security Features:</h4>
                    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px;">
                        <div>
                            <p>✅ <strong>Password Hashing:</strong> SHA-256 with unique salt</p>
                            <p>✅ <strong>Encryption Layer:</strong> AES-256 for hash protection</p>
                            <p>✅ <strong>Session Security:</strong> Encrypted tokens with expiration</p>
                            <p>✅ <strong>API Protection:</strong> Secure key storage and access</p>
                        </div>
                        <div>
                            <p>✅ <strong>Audit Logging:</strong> Complete authentication tracking</p>
                            <p>✅ <strong>Token Validation:</strong> Automatic expiry management</p>
                            <p>✅ <strong>Multi-layer Security:</strong> Hash + Encrypt approach</p>
                            <p>✅ <strong>Secure Storage:</strong> No plaintext credentials</p>
                        </div>
                    </div>
                </div>
            </div>
        </cfloop>
    </div>
    
    <h2>📊 Authentication Security Analytics</h2>
    <div style="background: ##e8f5e8; padding: 20px; border-radius: 8px;">
        <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 15px; margin-bottom: 20px;">
            <div style="background: white; padding: 15px; text-align: center; border-radius: 8px;">
                <h3>Total Users</h3>
                <h2 style="color: ##007bff;">#totalUsers#</h2>
            </div>
            <div style="background: white; padding: 15px; text-align: center; border-radius: 8px;">
                <h3>Secure Credentials</h3>
                <h2 style="color: ##28a745;">#secureCredentials#</h2>
            </div>
            <div style="background: white; padding: 15px; text-align: center; border-radius: 8px;">
                <h3>Active Sessions</h3>
                <h2 style="color: ##6f42c1;">#activeeSessions#</h2>
            </div>
            <div style="background: white; padding: 15px; text-align: center; border-radius: 8px;">
                <h3>Protected API Keys</h3>
                <h2 style="color: ##fd7e14;">#protectedApiKeys#</h2>
            </div>
        </div>
        
        <cfscript>
            // Calculate security metrics
            credentialSecurityRate = (secureCredentials / totalUsers) * 100;
            sessionSecurityRate = (activeeSessions / totalUsers) * 100;
            apiSecurityRate = (protectedApiKeys / totalUsers) * 100;
            overallSecurityScore = (credentialSecurityRate + sessionSecurityRate + apiSecurityRate) / 3;
            
            // Calculate average password strength
            totalPasswordStrength = 0;
            for (user in userAccounts) {
                pwd = secureUserPassword(user.password, passwordEncryptionKey);
                if (NOT StructKeyExists(pwd, "error")) {
                    totalPasswordStrength += pwd.strength_score;
                }
            }
            avgPasswordStrength = totalPasswordStrength / secureCredentials;
        </cfscript>
        
        <h3>🔐 Security Performance Metrics:</h3>
        <div style="background: white; padding: 15px; border-radius: 5px; margin: 10px 0;">
            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px;">
                <div>
                    <p><strong>Credential Security Rate:</strong> #NumberFormat(credentialSecurityRate, "0.0")#%</p>
                    <p><strong>Session Security Rate:</strong> #NumberFormat(sessionSecurityRate, "0.0")#%</p>
                    <p><strong>API Security Rate:</strong> #NumberFormat(apiSecurityRate, "0.0")#%</p>
                    <p><strong>Overall Security Score:</strong> #NumberFormat(overallSecurityScore, "0.0")#%</p>
                </div>
                <div>
                    <p><strong>Average Password Strength:</strong> #NumberFormat(avgPasswordStrength, "0.0")#/100</p>
                    <p><strong>Multi-factor Ready:</strong> Yes (encrypted tokens)</p>
                    <p><strong>Session Timeout:</strong> 8 hours (configurable)</p>
                    <p><strong>Encryption Standard:</strong> AES-256 + SHA-256</p>
                </div>
            </div>
        </div>
        
        <h3>🎯 Security Compliance Status:</h3>
        <div style="background: white; padding: 15px; border-radius: 5px; margin: 10px 0;">
            <div style="display: grid; grid-template-columns: repeat(2, 1fr); gap: 15px;">
                <div>
                    <p>🔒 <strong>OWASP Authentication:</strong> ✅ Compliant</p>
                    <p>🛡️ <strong>NIST Cybersecurity:</strong> ✅ Framework aligned</p>
                    <p>🔐 <strong>Password Security:</strong> ✅ Strong hashing + encryption</p>
                    <p>📊 <strong>Audit Requirements:</strong> ✅ Complete logging</p>
                </div>
                <div>
                    <p>🎫 <strong>Session Management:</strong> ✅ Secure token handling</p>
                    <p>🔑 <strong>API Security:</strong> ✅ Key protection implemented</p>
                    <p>⏰ <strong>Expiry Management:</strong> ✅ Automated timeout</p>
                    <p>🚫 <strong>Brute Force Protection:</strong> ✅ Logging enabled</p>
                </div>
            </div>
        </div>
    </div>
</cfoutput>

Share this page

Was this page helpful?
We're glad. Tell us how this page helped.
We're sorry. Can you tell us what didn't work for you?
Thank you for your feedback. Your response will help improve this page.

On this page