steeped
steeped

Reputation: 2633

Decoding a hash

I have some sensitive data in an online PHP application I am building. I want to store the data as a hash in the database, but that means I will have to decode the data every time I call it from the database. I know a hash is built to not be easily reversed engineered, so I would like to know what the best solution would be?

Unlike with passwords, I can't do a hash comparison - so how should I protect the information in the database?

Upvotes: 1

Views: 3405

Answers (3)

citizenen
citizenen

Reputation: 703

Try reading this article on web cryptography: http://www.alistapart.com/articles/web-cryptography-salted-hash-and-other-tasty-dishes/

You can encode variables using the SHA-1 hash as follows:

sha1('password')
=> 5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8

MySQL supports data encryption and decryption. Ex:

INSERT INTO people (pet_name) 
  VALUES (AES_ENCRYPT('Schmoopie','my-secret-key'));

SELECT AES_DECRYPT(pet_name, 'my-secret-key') AS pet_name
  FROM people;

Both of these examples are from the List Apart article.

Upvotes: 0

Chris Smith
Chris Smith

Reputation: 764

Cryptographic hash functions are one-way functions, meaning that you cannot reverse them. What I presume you are looking for is encryption. You can use the Mcrypt or OpenSSL extensions to do this. My recommendation would be using AES with a 256-bit key (but remember that you need to keep the key secure) to encrypt the data before inserting it into the database and decrypting it upon retrieval. Now, you could use the methods provided by MySQL but I'd use Mcrypt myself. If you can provide the nature and approximate size of the data you are trying to keep secure I could recommend a suitable mode of operation.

Upvotes: 0

John Conde
John Conde

Reputation: 219804

What you're looking for is encryption, not hashing. Encryption is two way which means you can unencrypt to view the contents assuming you have the proper information for doing so (you do, snoopers don't).

See this post for code on how to do this with PHP.

Upvotes: 5

Related Questions