SupportWriter space ↗
← Back to the journal
Security

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 […]

DWayan · 14 Nov 2006 · 1 min read

Article by Wayan · Source: Kode Java ↗

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

Comments 0

Share your questions, experiences, or feedback about this article.

No comments yet. Be the first to share your feedback.

← Explore more notes