For a demo that didn't happen, I wrote a quick example of using passwords with cfzip in ColdFusion 11. The idea behind the demo was that the user had asked for a set of files (in this case, a hard coded folder of kitten pictures - because - kittens). The password will be randomly selected, used in the zip operation, and then given to the user. The code is rather simple, so let's look at the complete template and then I'll break it down a bit.

Generate a zip file from our assets folder and password protect it.

<cfinclude template="udfs.cfm">

<!--- First, a temp file/loc ---> <cfset tmpFile = expandPath("./temp") & "/" & createUUID() & ".zip">

<!--- Our source directory... ---> <cfset sourceDir = expandPath("./assets")>

<!--- Now generate a random password. ---> <cfset password = generatePassword(7)>

<!--- Now ZIP THIS LIKE A ROCK STAR! ---> <cfzip action="zip" file="#tmpFile#" source="#sourceDir#" password="#password#" encryptionAlgorithm="AES-256">

<cfoutput> <p> Your zip file of kitten pictures has been created. Download via the link below. To unzip your archive, use this password: #password# </p>

<p> <a href="temp/#listLast(tmpFile, "/")#">Zip File</a> </p> </cfoutput>

Before I continue, let me just get the expected comments about frameworks and stuff out of the way. Normally I would not have everything in one CFM. Hopefully folks understand that. Ok, carrying on...

The first set of code includes a UDFs file. The UDFs file will be present in the attachment. It contains GeneratePassword from CFLib, which just - as you can probably guess - generates a random password.

Next we generate a random file name based on a UUID. While we can stream binary data to the user, in this case I need to tell the user their password too so I need to have HTML in my response instead. You could actually email the password instead, but this seemed more direct. Note that if I were truly creating files like this I'd want to have a scheduled task that cleaned up the files.

The next line is simply a pointer to the folder we're zipping. This is the folder of kitten pictures. I sourced this from a folder of 88 pictures of kittens. I'm not kidding. The attachment will only have a couple of them.

The next step is to generate the password. I selected seven for the number of characters because it seemed reasonable enough.

Finally we get to the hot zipping action. For the most part this is no different than using cfzip in the past, but notice now we pass both the password and an encryption algorithm to the tag. That's it really. We end up outputting a message to the user that includes their password and provide a link to the download.

That's it! One word of caution if you try this on OS X. The default Finder ability to unzip files does not work with password protected zips. I installed The Unarchiver and it worked great.

Download attached file.