How do I create an encrypted string for a password?

You are creating a user management system that will keep user profile and their credential or password. For security reason you’ll need to protect the password, to do this you can use the MessageDigest provided by Java API to encrypt the password. The code example below show you an example how to use it.

package org.kodejava.security;

import java.security.MessageDigest;

public class EncryptExample {
    public static void main(String[] args) {
        String password = "secret";
        String algorithm = "SHA";

        byte[] plainText = password.getBytes();

        try {
            MessageDigest digest = MessageDigest.getInstance(algorithm);
            digest.reset();
            digest.update(plainText);
            byte[] encodedPassword = digest.digest();

            StringBuilder builder = new StringBuilder();
            for (byte b : encodedPassword) {
                if ((b & 0xff) < 0x10) {
                    builder.append("0");
                }
                builder.append(Long.toString(b & 0xff, 16));
            }

            System.out.println("Plain    : " + password);
            System.out.println("Encrypted: " + builder.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Here is the example of our encrypted password:

Plain    : secret
Encrypted: e5e9fa1ba31ecd1ae84f75caaa474f3a663f05f4
Wayan

7 Comments

  1. Hi Abhishek, the MD5 and SHA are actually not an encryption algorithms. They are hashing algorithms, so you cannot decrypt the string back. If you want to check if the password is correct you need to hash the plain text and compare it with the previous hashed string.

    Reply
  2. Oh my! How could I overlook something like this. Thank you very much Wayan. Actually I’m a .Net developer and just decided to convert to Java and other open source technologies, So I’m confused a bit lately. However I’m quite sure I’ll prevail. Any pointers would be greatly appreciated.

    Reply
  3. I have encrypted my password in this method. Now I need to use this on my automation script of bat file.

    How will I use encrypted password in windows batch file?

    Advance Thanks!!

    Reply
  4. I like your code. I’m a beginner trying to learn java. I understand a little about different kind of hashing. Your example hash with a given password. Can you provide and example of code to hash the user input (password) and verify with a .txt file

    Reply
  5. Never use MD5 or SHA algorithms. They are quite inadequate to hash passwords. I suggest you to use password4j that uses modern way to encrypt passwords.

    Reply

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.