- CFML Reference User Guide
- ColdFusion functions
- ColdFusion functions by category
- Functions a-b
- Abs
- ACos
- AddSOAPRequestHeader
- AddSOAPResponseHeader
- AjaxLink
- AjaxOnLoad
- ApplicationStop
- ArrayAppend
- ArrayAvg
- ArrayClear
- ArrayContains
- ArrayContainsNoCase
- ArrayDelete
- ArrayDeleteAt
- ArrayDeleteNoCase
- ArrayEach
- ArrayFilter
- ArrayFind
- ArrayFindAll
- ArrayFindAllNoCase
- ArrayFindNoCase
- ArrayInsertAt
- ArrayIsDefined
- ArrayIsEmpty
- ArrayLen
- ArrayMap
- ArrayMax
- ArrayMin
- ArrayNew
- ArrayPrepend
- ArrayReduce
- ArrayResize
- ArraySet
- ArraySetMetadata
- ArraySlice
- ArraySort
- ArraySum
- ArraySwap
- ArrayToList
- Asc
- ASin
- Atn
- AuthenticatedContext
- AuthenticatedUser
- BinaryDecode
- BinaryEncode
- BitAnd
- BitMaskClear
- BitMaskRead
- BitMaskSet
- BitNot
- BitOr
- BitSHLN
- BitSHRN
- BitXor
- BooleanFormat
- Abs
- Functions-c-d
- CacheGet
- CacheGetAllIds
- CacheGetMetadata
- CacheGetProperties
- CacheGetSession
- CacheIdExists
- CachePut
- CacheRegionExists
- CacheRegionNew
- CacheRegionRemove
- CacheRemove
- CacheRemoveAll
- CacheSetProperties
- CallStackDump
- CallStackGet
- CanDeSerialize
- Canonicalize
- CanSerialize
- Ceiling
- CharsetDecode
- CharsetEncode
- Chr
- CJustify
- Compare
- CompareNoCase
- Cos
- CreateDate
- CreateDateTime
- CreateObject
- CreateObject: .NET object
- CreateObject: COM object
- CreateObject: component object
- CreateObject: CORBA object
- CreateObject: Java or EJB object
- CreateObject: web service object
- CreateODBCDate
- CreateODBCDateTime
- CreateODBCTime
- CreateSignedJWT
- CreateEncryptedJWT
- CreateTime
- CreateTimeSpan
- CreateUUID
- CSRFGenerateToken
- CSRFVerifyToken
- CSVRead
- CSVWrite
- CSVProcess
- DateAdd
- DateCompare
- DateConvert
- DateDiff
- DateFormat
- DatePart
- DateTimeFormat
- Day
- DayOfWeek
- DayOfWeekAsString
- DayOfYear
- DaysInMonth
- DaysInYear
- DE
- DecimalFormat
- DecodeForHTML
- DecodeFromURL
- DecrementValue
- Decrypt
- DecryptBinary
- DeleteClientVariable
- Deserialize
- DeserializeJSON
- DeserializeXML
- DirectoryCopy
- DirectoryCreate
- DirectoryDelete
- DirectoryExists
- DirectoryList
- DirectoryRename
- DollarFormat
- DotNetToCFType
- Duplicate
- Functions-e-g
- EncodeForCSS
- EncodeForDN
- EncodeForHTML
- EncodeForHTMLAttribute
- EncodeForJavaScript
- EncodeForLDAP
- EncodeForURL
- EncodeForXML
- EncodeForXMLAttribute
- EncodeForXpath
- Encrypt
- EncryptBinary
- EntityDelete
- EntityLoad
- EntityLoadByExample
- EntityLoadByPK
- EntityMerge
- EntityNew
- EntityReload
- EntitySave
- EntityToQuery
- Evaluate
- Exp
- ExpandPath
- FileClose
- FileCopy
- FileDelete
- FileExists
- FileGetMimeType
- FileIsEOF
- FileMove
- FileOpen
- FileRead
- FileReadBinary
- FileReadLine
- FileSeek
- FileSetAccessMode
- FileSetAttribute
- FileSetLastModified
- FileSkipBytes
- FileUpload
- FileUploadAll
- FileWrite
- FileWriteLine
- Find
- FindNoCase
- FindOneOf
- FirstDayOfMonth
- Fix
- Floor
- FormatBaseN
- GeneratePBKDFKey
- GenerateSecretKey
- GetApplicationMetadata
- GetAuthUser
- GetBaseTagData
- GetBaseTagList
- GetBaseTemplatePath
- GetClientVariablesList
- GetComponentMetaData
- GetContextRoot
- GetCPUUsage
- GetCurrentTemplatePath
- GetCSPNonce
- GetDirectoryFromPath
- GetEncoding
- GetException
- GetFileFromPath
- GetFileInfo
- GetFreeSpace
- GetFunctionCalledName
- GetFunctionList
- GetGatewayHelper
- GetHttpRequestData
- GetHttpTimeString
- GetK2ServerDocCount
- GetK2ServerDocCountLimit
- GetLocale
- GetLocaleDisplayName
- GetLocalHostIP
- GetMetaData
- GetMetricData
- GetPageContext
- GetPropertyString
- GetPropertyFile
- GetPrinterInfo
- GetPrinterList
- GetProfileSections
- GetProfileString
- GetReadableImageFormats
- GetSafeHTML
- GetSAMLAuthRequest
- GetSAMLLogoutRequest
- Generate3DesKey
- GenerateSAMLSPMetadata
- GetSOAPRequest
- GetSOAPRequestHeader
- GetSOAPResponse
- GetSOAPResponseHeader
- GetSystemFreeMemory
- GetSystemTotalMemory
- GetTempDirectory
- GetTempFile
- GetTemplatePath
- GetTickCount
- GetTimeZoneInfo
- GetToken
- GetTotalSpace
- GetUserRoles
- GetVFSMetaData
- GetWriteableImageFormats
- Functions-h-im
- Hash
- HMac
- Hour
- HQLMethods
- HTMLCodeFormat
- HTMLEditFormat
- IIf
- ImageAddBorder
- ImageBlur
- ImageClearRect
- ImageCopy
- ImageCreateCaptcha
- ImageCrop
- ImageDrawArc
- ImageDrawBeveledRect
- ImageDrawCubicCurve
- ImageDrawLine
- ImageDrawLines
- ImageDrawOval
- ImageDrawPoint
- ImageDrawQuadraticCurve
- ImageDrawRect
- ImageDrawRoundRect
- ImageDrawText
- ImageFlip
- ImageGetBlob
- ImageGetBufferedImage
- ImageGetEXIFMetadata
- ImageGetEXIFTag
- ImageGetHeight
- ImageGetIPTCMetadata
- ImageGetIPTCTag
- ImageGetMetadata
- ImageGetWidth
- ImageGrayscale
- ImageInfo
- ImageMakeColorTransparent
- ImageMakeTranslucent
- ImageNegative
- ImageNew
- ImageOverlay
- ImagePaste
- ImageRead
- ImageReadBase64
- ImageResize
- ImageRotate
- ImageRotateDrawingAxis
- ImageScaleToFit
- ImageSetAntialiasing
- ImageSetBackgroundColor
- ImageSetDrawingColor
- ImageSetDrawingStroke
- ImageSetDrawingTransparency
- ImageSharpen
- ImageShear
- ImageShearDrawingAxis
- ImageTranslate
- ImageTranslateDrawingAxis
- ImageWrite
- ImageWriteBase64
- ImageXORDrawingMode
- Functions-in-k
- IncrementValue
- InputBaseN
- Insert
- Int
- InterruptThread
- InvalidateOauthAccesstoken
- Invoke
- InitSAMLAuthRequest
- InitSAMLLogoutRequest
- InvokeCFClientFunction
- IsArray
- IsAuthenticated
- IsAuthorized
- IsBinary
- IsBoolean
- IsClosure
- IsCustomFunction
- IsDate
- IsDateObject
- IsDDX
- IsDebugMode
- IsDefined
- IsImage
- IsImageFile
- IsInstanceOf
- IsIPv6
- IsJSON
- IsK2ServerABroker
- IsK2ServerDocCountExceeded
- IsK2ServerOnline
- IsLeapYear
- IsLocalHost
- IsNull
- IsNumeric
- IsNumericDate
- IsObject
- isOnline
- IsPDFArchive
- IsPDFFile
- IsPDFObject
- IsProtected
- IsQuery
- isSamlLogoutResponse
- isSafeHTML
- IsSimpleValue
- IsSOAPRequest
- IsSpreadsheetFile
- IsSpreadsheetObject
- IsStruct
- isThreadInterrupted
- IsUserInAnyRole
- IsUserInRole
- IsUserLoggedIn
- IsValid
- IsValidOauthAccesstoken
- IsWDDX
- IsXML
- IsXmlAttribute
- IsXmlDoc
- IsXmlElem
- IsXmlNode
- IsXmlRoot
- JavaCast
- JSStringFormat
- Functions-l
- LCase
- Left
- Len
- ListAppend
- ListChangeDelims
- ListContains
- ListContainsNoCase
- ListDeleteAt
- ListEach
- ListFilter
- ListFind
- ListFindNoCase
- ListFirst
- ListGetAt
- ListGetDuplicates
- ListInsertAt
- ListLast
- ListLen
- ListMap
- ListPrepend
- ListQualify
- ListReduce
- ListRemoveDuplicates
- ListRest
- ListSetAt
- ListSort
- ListToArray
- ListValueCount
- ListValueCountNoCase
- LJustify
- Location
- Log
- Log10
- LSCurrencyFormat
- LSDateFormat
- LSDateTimeFormat
- LSEuroCurrencyFormat
- LSIsCurrency
- LSIsDate
- LSIsNumeric
- LSNumberFormat
- LSParseCurrency
- LSParseDateTime
- LSParseEuroCurrency
- LSParseNumber
- LSTimeFormat
- LTrim
- Functions-m-r
- Max
- Mid
- Min
- Minute
- Month
- MonthAsString
- Now
- NumberFormat
- ObjectEquals
- ObjectLoad
- ObjectSave
- OnWSAuthenticate
- ORMClearSession
- ORMCloseAllSessions
- ORMCloseSession
- ORMEvictCollection
- ORMEvictEntity
- ORMEvictQueries
- ORMExecuteQuery
- ORMFlush
- ORMFlushall
- ORMGetSession
- ORMGetSessionFactory
- ORMIndex
- ORMIndexPurge
- ORMReload
- ORMSearch
- ORMSearchOffline
- ParagraphFormat
- ParameterExists
- ParseDateTime
- Pi
- PrecisionEvaluate
- ProcessSAMLResponse
- ProcessSAMLLogoutRequest
- Quarter
- PreserveSingleQuotes
- QueryAddColumn
- QueryAddRow
- QueryConvertForGrid
- QueryExecute
- QueryFilter
- QueryGetResult
- QueryGetRow
- QueryKeyExists
- QueryMap
- QueryNew
- QueryReduce
- QuerySetCell
- QuotedValueList
- QueryEach
- Rand
- Randomize
- RandRange
- ReEscape
- REFind
- REFindNoCase
- ReleaseComObject
- REMatch
- REMatchNoCase
- RemoveCachedQuery
- RemoveChars
- RepeatString
- Replace
- ReplaceList
- ReplaceNoCase
- REReplace
- REReplaceNoCase
- RestDeleteApplication
- RestSetResponse
- RestInitApplication
- Reverse
- Right
- RJustify
- Round
- RTrim
- Functions-s
- Second
- SendGatewayMessage
- SendSAMLLogoutResponse
- Serialize
- SerializeJSON
- SerializeXML
- SessionInvalidate
- SessionRotate
- SessionGetMetaData
- SessionInvalidate
- SessionRotate
- SetDay
- SetEncoding
- SetHour
- SetLocale
- SetMonth
- SetProfileString
- SetPropertyString
- SetVariable
- SetYear
- Sgn
- Sin
- Sleep
- SpanExcluding
- SpanIncluding
- SpreadsheetAddAutoFilter
- SpreadsheetAddColumn
- SpreadsheetAddFreezePane
- SpreadsheetAddImage
- SpreadsheetAddInfo
- SpreadsheetAddPageBreaks
- SpreadsheetAddRow
- SpreadsheetAddRows
- SpreadsheetAddSplitPane
- SpreadsheetCreateSheet
- SpreadsheetDeleteColumn
- SpreadsheetDeleteColumns
- SpreadsheetDeleteRow
- SpreadsheetDeleteRows
- SpreadsheetFormatCell
- SpreadsheetFormatColumn
- SpreadsheetFormatCellRange
- SpreadsheetFormatColumn
- SpreadsheetFormatColumns
- SpreadsheetFormatRow
- SpreadsheetFormatRows
- SpreadsheetGetCellComment
- SpreadsheetGetCellFormula
- SpreadsheetGetCellValue
- SpreadsheetGetColumnCount
- SpreadsheetInfo
- SpreadsheetMergeCells
- SpreadsheetNew
- SpreadsheetRead
- SpreadsheetReadBinary
- SpreadsheetRemoveSheet
- SpreadsheetSetActiveSheet
- SpreadsheetSetActiveSheetNumber
- SpreadsheetSetCellComment
- SpreadsheetSetCellFormula
- SpreadsheetSetCellValue
- SpreadsheetSetColumnWidth
- SpreadsheetSetFooter
- SpreadsheetSetHeader
- SpreadsheetSetRowHeight
- SpreadsheetShiftColumns
- SpreadsheetShiftRows
- SpreadsheetWrite
- StreamingSpreadsheetNew
- StreamingSpreadsheetCleanup
- StreamingSpreadsheetRead
- StreamingSpreadsheetProcess
- SpreadsheetSetFooterImage
- SpreadsheetSetHeaderImage
- SpreadsheetSetFittoPage
- SpreadsheetUngroupColumns
- SpreadsheetGroupColumns
- SpreadsheetUngroupRows
- SpreadsheetGroupRows
- SpreadsheetRemoveColumnBreak
- SpreadsheetSetColumnBreak
- SpreadsheetRemoveRowBreak
- SpreadsheetSetRowBreak
- SpreadsheetRemovePrintGridlines
- SpreadsheetAddPrintGridlines
- SpreadsheetGetColumnWidth
- SpreadsheetSetColumnHidden
- SpreadsheetSetRowHidden
- SpreadsheetisColumnHidden
- SpreadsheetisRowHidden
- SpreadsheetisStreamingXmlFormat
- SpreadsheetisXmlFormat
- SpreadsheetisBinaryFormat
- SpreadsheetRenameSheet
- SpreadsheetRemoveSheetNumber
- SpreadsheetGetLastRowNumber
- SpreadsheetGetPrintOrientation
- Sqr
- StripCR
- StructAppend
- StructClear
- StructCopy
- StructCount
- StructDelete
- StructEach
- StructFilter
- StructFind
- StructFindKey
- StructFindValue
- StructGet
- StructGetMetadata
- StructInsert
- StructIsEmpty
- StructKeyArray
- StructKeyExists
- StructKeyList
- StructMap
- StructNew
- StructReduce
- StructSetMetadata
- StructSort
- StructToSorted
- StructUpdate
- StructValueArray
- StoreSetMetadata
- StoreGetACL
- StoreGetMetadata
- StoreAddACL
- StoreSetACL
- Functions-t-z
- Tan
- ThreadJoin
- ThreadTerminate
- Throw
- TimeFormat
- ToBase64
- ToBinary
- ToScript
- ToString
- Trace
- Transactionandconcurrency
- TransactionCommit
- TransactionRollback
- TransactionSetSavePoint
- Trim
- UCase
- URLDecode
- URLEncodedFormat
- URLSessionFormat
- Val
- ValueList
- VerifyClient
- Week
- Wrap
- WriteDump
- WriteLog
- WriteOutput
- WSGetAllChannels
- WSGetSubscribers
- WSPublish
- WSSendMessage
- XmlChildPos
- XmlElemNew
- XmlFormat
- XmlGetNodeType
- XmlNew
- XmlParse
- XmlSearch
- XmlTransform
- XmlValidate
- Year
- YesNoFormat
- ColdFusion tags
- ColdFusion tag summary
- ColdFusion tags by category
- Application framework tags
- Communications tags
- Database manipulation tags
- Data output tags
- Debugging tags
- Exception handling tags
- Extensibility tags
- File management tags
- Flow-control tags
- Forms tags
- Internet Protocol tags
- Page processing tags
- Security tags
- Variable manipulation tags
- Other tags
- Tags a-b
- Tags c
- cfcache
- cfcalendar
- cfcase
- cfcatch
- cfchart
- cfchart tag in ColdFusion
- Get started with cfchart
- Customize a chart using cfchart
- Advanced cfchart customization options
- Create an area chart in ColdFusion
- Create line charts in ColdFusion
- Create bar charts in ColdFusion
- Create floating bar charts in ColdFusion
- Create histograms in ColdFusion
- Create pie charts in ColdFusion
- Create funnel charts in ColdFusion
- Create pyramid charts in ColdFusion
- Create curve charts in ColdFusion
- Create boxplots in ColdFusion
- Create donut charts in ColdFusion
- Create bubble charts in ColdFusion
- Create scatterplots in ColdFusion
- Create radar charts in ColdFusion
- Other chart types in ColdFusion (Cone, Cylinder, Piano, and Bullet)
- Advanced customization options in cfchart
- cfchartdata
- cfchartseries
- cfchartset
- cfclient
- cfclientsettings
- cfcol
- cfcollection
- cfcomponent
- cfcontent
- cfcontinue
- cfcookie
- Tags f
- cffeed
- cffile
- cffile action = "append"
- cffile action = "copy"
- cffile action = "delete"
- cffile action = "move"
- cffile action = "read"
- cffile action = "readBinary"
- cffile action = "rename"
- cffile action = "upload"
- cffile action = "uploadAll"
- cffile action = "write"
- cffileupload
- cffinally
- cfflush
- cfform
- cfformgroup
- cfformitem
- cfftp
- cfftp: Connection: file and directory operations
- cfftp: Opening and closing FTP server connections
- cfftp : Opening and closing secure FTP server connections
- cfftp action = "listDir"
- cffunction
- Tags g-h
- Tags i
- Tags j-l
- cfjava
- cflayout
- cflayoutarea
- cfldap
- cflocation
- cflock
- cflog
- cflogin
- cfloginuser
- cflogout
- cfloop
- cfloop : conditional loop
- cfloop : index loop
- cfloop : looping over a COM collection or structure
- cfloop : looping over a date or time range
- cfloop : looping over a list, a file, or an array
- cfloop : looping over a query
- Tags m-o
- cfmail
- cfmailparam
- cfmailpart
- cfmap
- cfmapitem
- cfmediaplayer
- cfmenu
- cfmenuitem
- cfmessagebox
- cfmodule
- cfNTauthenticate
- cfoauth
- cfobject
- cfobject: .NET object
- cfobject: COM object
- cfobject: component object
- cfobject: CORBA object
- cfobject: Java or EJB object
- cfobject: web service object
- cfobjectcache
- cfoutput
- Tags p-q
- Tags r-s
- Tags t
- Tags u-z
- CFML Reference
- Reserved words and variables
- Ajax JavaScript functions
- Ajax JavaScript functions
- Function summary Ajax
- ColdFusion.Ajax.submitForm
- ColdFusion.Autosuggest.getAutosuggestObject
- ColdFusion.Layout.enableSourceBind
- ColdFusion.MessageBox.getMessageBoxObject
- ColdFusion.ProgressBar.getProgressBarObject
- ColdFusion.MessageBox.isMessageBoxDefined
- JavaScriptFunctionsinColdFusion9Update1
- ColdFusion ActionScript functions
- ColdFusion mobile functions
- Application.cfc reference
- Script functions implemented as CFCs
- ColdFusion Flash Form style reference
- Styles valid for all controls
- Styles for cfform
- Styles for cfformgroup with horizontal or vertical type attributes
- Styles for box-style cfformgroup elements
- Styles for cfformgroup with accordion type attribute
- Styles for cfformgroup with tabnavigator type attribute
- Styles for cfformitem with hrule or vrule type attributes
- Styles for cfinput with radio, checkbox, button, image, or submit type attributes
- Styles for cftextarea tag and cfinput with text, password, or hidden type attributes
- Styles for cfselect with size attribute value of 1
- Styles for cfselect with size attribute value greater than 1
- Styles for cfcalendar tag and cfinput with dateField type attribute
- Styles for the cfgrid tag
- Styles for the cftree tag
- ColdFusion Flash Form Style Reference
- ColdFusion event gateway reference
- ColdFusion Event Gateway reference
- addEvent
- CFEvent
- CFEventclass
- Constructor
- Gateway development interfaces and classes
- getStatus
- setCFCPath
- setCFCMethod
- getOriginatorID
- getLogger
- getBuddyList
- getBuddyInfo
- IM gateway message sending commands
- IM Gateway GatewayHelper class methods
- onIncomingMessage
- onIMServerMessage
- onBuddyStatus
- onAddBuddyResponse
- onAddBuddyRequest
- IM Gateway CFC incoming message methods
- IM gateway methods and commands
- CFML CFEvent structure
- warn
- info
- setOriginatorID
- data command
- submit Multi command
- submit command
- setGatewayType
- setGatewayID
- setData
- setCFCListeners
- outgoingMessage
- getStatusTimeStamp
- numberOfMessagesReceived
- numberOfMessagesSent
- removeBuddy
- removeDeny
- removePermit
- setNickName
- setPermitMode
- setStatus
- SMS Gateway CFEvent structure and commands
- SMS Gateway incoming message CFEvent structure
- getStatusAsString
- getProtocolName
- getPermitMode
- getPermitList
- getNickName
- getName
- getDenyList
- getCustomAwayMessage
- getQueueSize
- getMaxQueueSize
- getHelper
- getGatewayType
- getGatewayServices
- getGatewayID_1
- getGatewayID
- getData
- getCFCTimeout
- setCFCTimeout
- getCFCPath
- getCFCMethod
- GatewayServices class
- Gateway interface
- GatewayHelper interface
- addPermit
- addDeny
- addBuddy
- error
- debug
- Logger class
- stop
- start
- CFML event gateway SendGatewayMessage data parameter
- restart
- fatal
- SMS gateway message sending commands
- ColdFusion C++ CFX Reference
- ColdFusion Java CFX reference
- WDDX JavaScript Objects
- Cloud services
- ColdFusion and GCP Storage
- ColdFusion and GCP Firestore
- ColdFusion and GCP PubSub
- ColdFusion and Amazon S3
- ColdFusion and DynamoDB
- ColdFusion and Amazon SQS
- ColdFusion and Amazon SNS
- ColdFusion and MongoDB
- ColdFusion and Azure Blob
- ColdFusion and Azure Service Bus
- Multi-cloud storage services
- Multi-cloud RDS databases
- ColdFusion and Azure Cosmos DB
Description
Encrypts a string using a specific algorithm and encoding method.
Returns
String; can be much longer than the original string.
Category
Security functions, String functions
Function syntax
Encrypt(string, key, encoding, algorithm, IV_Salt, iterations)
Decrypt,EncryptBinary,DecryptBinary
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.
|
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:
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:
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.
|
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.
|
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>
|
<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>
