Petr Dušek
Petr Dušek

Reputation: 627

Simple encryption (username - password) in JPA, mysql

I am completely new in Java encryption and I need your help. I would like to implement a simple login system with mysql and JPA entity UserRecord:

    @Entity
    public class UserRecord implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    private Long id;
    @Column(unique=true)
    private String username;
    private String password;

Now, what is the best way to keep secret the system? I think, I have to encrypt the password and manage to decrypt it at the time of comparing the inputs with database records. Are there some special ways to make this in JPA? I want to create nothing difficult, it is only for my study issues. The only requirement: it has to be salted (?). Could you advice me, please?

Thanks a lot!

Upvotes: 2

Views: 8473

Answers (1)

ben75
ben75

Reputation: 28706

The password must encrypted in your database... and it's better to not being able to decrypt it ! It means that when encrypting your password you MUST loose some information so that it became impossible to compute the original password from it's encrypted form. (there are many algorithms to do that like PBKDF2, ...). (Sample PBKDF2 in java)

Using a salt means that you will append a random string (it is the salt) to the password when the user create it's account. You will store this random string in the user table (just like the encrypted password).

To validate the user password at login :

  • find the salt that was generated for the user trying to login.
  • run the encryption algorithm on password+salt
  • compare the result with the encrypted password stored in DB : if they match the password is correct.

Here is a link with more details and sample code.

BTW : this question as nothing to see with JPA. AFAIK: there is nothing related to encryption in JPA specs.

Upvotes: 4

Related Questions