We all have heard of MD5 encryption and it is one of the best encryptors so far. In this Blog, we will learn how to convert a String to MD5 Hashes in Android.
A brief introduction to MD5 :
MD5 stands for ‘Message Digest algorithm 5’.
The MD5 algorithm is used as a cryptographic hash function or a file fingerprint. Often used to encrypt
Often used to encrypt the password in databases, MD5 can also generate a fingerprint file to ensure that a file is the same after a transfer for example.
MD5 means a 128-bit encryption algorithm, generating a 32-character hexadecimal hash.
Although MD5 was initially designed to be used as a cryptographic hash function, it has been found to suffer from extensive vulnerabilities. It can still be used as a checksum to verify data integrity, but only against unintentional corruption.
It can still be used as a checksum to verify data integrity, but only against unintentional corruption.
Like most hash functions, MD5 is neither encryption nor encoding. It can be cracked by brute-force attack and suffers from extensive vulnerabilities.
With all this being said, let’s have a look at what you exactly need to do to convert a String to MD5 Hashes. This indeed is very easy.
APPROACH :
- Get an Instance of the MessageDigest class of the package “java.security.MessageDigest”.
- Pass the bytecode of your string in the update method [update()] of this Instance
- Create a byte array and allocate it the value returned by the digest method[digest()] of the same Instance.With these steps only your MD5 Hash has been generated, but this is in byte array form, so in order to get all data in a sing le variable we will convert all this data into a String and then return the same.
- Create a new Object of StringBuffer or StringBuilder.
- Traverse the byte array earlier created and append values in you Object.
- Return the value returned by the toString method on this Object.
Now Let’s have a look at the code:
CODE :
1 2 3 |
String string_to_be_converted_to_MD5 = "REPLACE_WITH YOUR_OWN_STRING"; String MD5_Hash_String = md5(string_to_be_converted_to_MD5); System.out.println(MD5_Hash_String); |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
public String md5(String s) { try { // Create MD5 Hash MessageDigest digest = java.security.MessageDigest.getInstance("MD5"); digest.update(s.getBytes()); byte messageDigest[] = digest.digest(); // Create Hex String StringBuffer hexString = new StringBuffer(); for (int i=0; i<messageDigest.length; i++) hexString.append(String.format(“%02X”, messageDigest[i])); return hexString.toString(); }catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return ""; } |
You can Definitely use StringBuilder class to create the returned String.
That’s All.
Keep Coding And Keep Sharing.
Sources : https://en.wikipedia.org/