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

Programmer, runner, recreational diver, currently living in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, Hibernate / JPA.


  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 encrypt the plain text and compare it with the previous encrypted 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.


Leave a Reply