Every application that you’ll create may require an authentication process. This authentication process will at least contains a process of checking user’s login name and their password. To make the system reliable the password we usually stored the password in an encrypted form.
The BasicPasswordEncryptor
which implements the PasswordEncryptor
interface provide a BasicPasswordEncryptor.encryptPassword(String password)
method for encrypting user’s password. To check if the user’s password is correct we use the BasicPasswordEncryptor.checkPassword(String plainText, String encryptedPassword)
method.
package org.kodejava.jasypt;
import org.jasypt.util.password.BasicPasswordEncryptor;
import org.jasypt.util.password.PasswordEncryptor;
public class PasswordEncryptorDemo {
public static void main(String[] args) {
// Creates an instance of BasicPasswordEncryptor.
PasswordEncryptor encryptor = new BasicPasswordEncryptor();
// Encrypted version of user password.
String encrypted = encryptor.encryptPassword("secret");
System.out.println("encrypted = " + encrypted);
// Compare user's plain text password with the encrypted one to check
// if they are match.
if (encryptor.checkPassword("secret", encrypted)) {
System.out.println("Welcome to Jasypt");
} else {
System.out.println("Invalid secret word, access denied!");
}
}
}
Maven Dependencies
<dependency>
<groupId>org.jasypt</groupId>
<artifactId>jasypt</artifactId>
<version>1.9.3</version>
</dependency>
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
Thank you. Thats quite OK, but my problem is that the resulting encrypted password is different every time you use encrypt.Password(myPassword). I guess that this is due to some autogenerated random salt, and that is also OK by it self, but how do I get my hand on this random salt? I need it right?
My practical problem is that I use the encrypted pw to encrypt data. But when the password-encryption does not produce the same output for the very same password – I cannot decrypt my data this way. Can you help me find the way?
Have a nice day!
Perhaps I finally found the solution to my problem. The BasicPasswordEncryptor is just ment for authorization and not for generating obscured passwords for passwordbased encryption of data such as BasicTextEncryptor. I guess I just use some hash function and a fixed salt manually. Sorry for bothering you 😛
You are partly right, because it’s not everything. It’s not that easy like you wrote. Every time when you hash the password, salt is different. So after you add encrypted password to database and match to password which was provided by user, you will always get false.