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
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024
Hi there! The tutorial was enlightening but how do I decrypt the password back?
Hi Abhishek, the
MD5
andSHA
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.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.
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!!
Nice tutorial. Thank you
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
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.