Recently, we had a client who needed a way to store
encrypted files on their server. As much as we would have liked to do a normal
upload form, this client needed to store sensitive user files on their website, which requires tighter security.
Most websites that are dealing with sensitive user information include an SSL. SSL is short for “Secure Sockets Layer” this allows you to encrypt all the communications with your site. Any websites that are processing payments, or dealing with sensitive information are required to have one.
You might be thinking, if my site has an SSL certificate, why would I need to encrypt the files? The
answer is for an extra layer of security. Sure, an SSL would protect the data
transmitted by the website but it would not protect the data stored on
the server. If the server were to be compromised, we would know the data would be
safe, as it is stored in an encrypted file on the server.
When
you encrypt a file essentially what you are doing is making a file
unreadable to anyone that does not know the key for that file. So as long
as you know the key, you are able to read the file. The first step to file encryption is to grab
the contents of the file as it’s uploaded. Once we have the
contents, it is encrypted with a unique key assigned to each user, so
that only that user, upon retrieval, will be able to decrypt the file. Simple.
Now, back to the point, this solution was something that Back40
has never done before. We had to research file encryption with PHP extensively.
After doing research for PHP encryption, I found a few solutions, but not many
were tailored to what we needed. I took the knowledge that I learned from my research and
incorporated it into our final solution. What was this solution you may ask?
PHP’s filter_stream_append. With this function, you are able to append a filter
to the filestream (the file that is being uploaded or downloaded) which allows
you to encrypt and decrypt the file without ever storing a hard copy of
the unencrypted file on your server. This is important because if the unencrypted file was on the server, anyone with access could read it. Filter_stream_append can also append a filter that will apply to a filestream as it is being downloaded, so the only time it is unencrypted is when it is on the user’s computer. There are many filters for this function, but the one I used was mcrypt, a basic library that allows you to encrypt various things.
This solution worked wonderfully, and is
definitely something we will be able to use in the future. This is one of the
reasons our clients choose us for their custom projects, the solution was not
something you could just find, it had to be customized and tailored
to this clients specific needs.