Hash functions in web security

Hash functions in web security


Table of Contents

  • What the hash function is?
  • Http Cookies
  • password

1 What the hash function is?

A hash function is a one-directional one-to-one or multiply-to-one function, which can project data in one space to another, but not reverse. The key point here is one-directional projection, if you found a way to reverse this process, then this hash algorithm is corrupted, if the hash algorithm corrupted, the whole web security is down. You would not want that happen, right?

So, which hash functions are the popular ones? the popular hash function includes md5, sha256. In python standard distribution, it provided an hashlib module which provided the usual hash functions.
The following code snippet is an example to get digest from messages by python's hashlib module. The digest is the hash value of a message. 

digest = hash(message).

import hashlib

hashlib.md5('hello world').hexdigest()
hashlib.sha256('hello world').hexdigest()
hashlib.sha512('hello world').hexdigest()

The Following two sections illustrate hash function in the web security.

2 Http Cookies

The hash function is used in HTTP cookies to prevent some cheating from the client. A hash function is usually considered a way to generate a digest of messages, we can compare the digests to judge whether they come from the same value. In this way, sometimes, we append digest to the message as a security way to prevent cheating. So, the following is what the cookie items looks like?
key=value,hash(value)
But if I guessed the hash function used to generate the digest, then I still can cheating server by attaching the digest generated by same hash function after the value in the same way. In this case, you need to attach the hash of value plus a secret phase, it is not easy to guess both hash function and secret phase together. We give this secret phase a name – salt.
key=value,hash(value+salt)
python provided a module named hmac to do this job.

import hmac

salt = 'passwd'

hmac.new(salt, 'hello').hexdigest()

3 password

When you need to transmit the password across the internet to the server, you should not use the plain text password directly, instead, you need to transmit the hash value of your password all times, and the server has no right to store your plain text password.

Beside the password plus salt way to get the hash value, a better way is to use bcrypt which is a much safer way.

import bcrypt

salt = bcrypt.gensalt()
hash = bcrypt.hashpw('passwd', salt)
# salt is attached in the head of generated hash
hash.find(salt)

#how to verify the passwd
#since salt is included in the hash, so same hashpw
#function generate the same result.
hash == bcrypt.hashpw('passwd', hash)

Comments

Popular posts from this blog

Bluedroid stack in android

How to setup a NAT server?

Network programming in elisp