How do I create an encrypted string for 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.



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

        byte[] plainText = password.getBytes();

        try {
            MessageDigest md = MessageDigest.getInstance(algorithm);

            byte[] encodedPassword = md.digest();

            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < encodedPassword.length; i++) {
                if ((encodedPassword[i] & 0xff) < 0x10) {

                sb.append(Long.toString(encodedPassword[i] & 0xff, 16));

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

Here is the example of our encrypted password:

Plain    : secret
Encrypted: e5e9fa1ba31ecd1ae84f75caaa474f3a663f05f4

Wayan Saryada

Founder at Kode Java Org
I am a programmer, a runner, a recreational diver, currently live in the island of Bali, Indonesia. Mostly programming in Java, Spring Framework, Hibernate / JPA. If these posts help, you can support me, buy me a cup of coffee or tea. Thank you 🥳


  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.

  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.

  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!!


Leave a Reply to Abhishek Purohit Cancel reply

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