How do I create an encrypted string for password?

Category: java.security, viewed: 7682 time(s).

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 a example how to use it.

package org.kodejava.example.security;

import java.security.MessageDigest;

public class EncryptExample {
	public static void main(String[] args) {
		String password = "secret";
		String algorithm = "SHA";
		
		byte[] plainText = password.getBytes();
		
		MessageDigest md = null;
		
		try {		
			md = MessageDigest.getInstance(algorithm);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		md.reset();		
		md.update(plainText);
		byte[] encodedPassword = md.digest();
		
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < encodedPassword.length; i++) {
			if ((encodedPassword[i] & 0xff) < 0x10) {
				sb.append("0");
			}
			
			sb.append(Long.toString(encodedPassword[i] & 0xff, 16));
		}

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

Here is the example of our encrypted password:

Plain    : secret
Encrypted: e5e9fa1ba31ecd1ae84f75caaa474f3a663f05f4
Click here to lend your support to: Kode Java Org and make a donation at www.pledgie.com !

 

Uncensored Newsgroups
Download Hundreds of Complimentary Industry Resources

Get hundreds of popular Industry magazines, white papers, webinars, podcasts, and more; all available at no cost to you. With more than 600 complimentary offers, you'll find plenty of titles to suit your professional interests and needs. Click Here and Sign up today!

Java Training

Sponsored Links

Our Friends

Statistics

Locations of visitors to this page
visitor stats