Implementing password Hashing Using Java/Python

Password Hashing : – As we all know security matters in today’s world. We cannot store everything in plane string format as it results in security breach. So here password hashing comes in picture.

So Password Hashing is a technique of saving data/passwords in encrypted form so that no one can use them to steal info. Using encryption what we do actually , we store encrypted password in database and whenever user tries to login then his/her passwords hash is matched against database hash, if it matches then user is valid/authenticated.

We have various hashing algorithm’s available for encryption. Some of famous are as follows:-

  • MD2
  • MD5
  • SHA-1
  • SHA-256
  • SHA-512
  • BCrypt etc.

Now let’s see practical implementation of Hashing :-

Using Java : –

import java.security.MessageDigest;
import javax.xml.bind.DatatypeConverter;

public class Encryption {
private static final String MD5="MD5";
private static final String SHA1="SHA-1";
public static String hashString(String data) {
String hashValue=null;
try {
MessageDigest digest=MessageDigest.getInstance(SHA1);
byte[] digestedBytes=digest.digest(data.getBytes());
hashValue = DatatypeConverter.printBase64Binary(digestedBytes).toString();
}
catch(Exception e) {

e.printStackTrace();
}
return hashValue;
}


public static void main(String[] args) {
System.out.println(hashString("password"));
}
}

 In above example we have used SHA-1 algorithm for generating password hash. MessageDigest class which is an abstract class is used to get instance of Hash type and then digest(byte[] bytes) method is called which returns bytes array given string and then used DataTypeConverter method to get string text in character/digit form.

Output  : – W6ph5Mm5Pz8GgiULbPgzG37mj9g=

Using Python : –

import hashlib,uuid
password_to_secure="pawd123"
salt=uuid.uuid4().hex

#here sha-512 algo will produce encrypted string

#here encode is used to format password_to_secure+salt to utf-8 otherwise you will get
# Error : Unicode-objects must be encoded before hashing

encrypted_pwd=hashlib.sha512(str(password_to_secure+salt).encode('utf-8')).hexdigest()
print(encrypted_pwd)

Output : – 0add3c5afda60ac5288305f2985ba03657371d0e84599b98f4c4407593c62ffb78a4e7f56fa8a3b8bb54bc38181332c2753b1953c7a8aba564ef5d64cbd1c67b

Note : – The encrypted value length depends upon algo you used for encryption. for example

MD2 will produce lowest length encrypted string,MD5 greater then MD2 and so on.

Happy Coding!!!