This is my Blog.

It's full of opinions on a wide range of stuff.

Adding JASYPT encryption to your scala JPA entity classes

I've recently been looking at how best to make sensitive user data encrpytable within JPA models when in use with lift. I came accross JASYPT and it seems to be a really nice encryption tool. If you want to add it to your scala JPA models, do something like this:

package eu.getintheloop.bloglite.model

import javax.persistence._
import java.util.Date
import org.jasypt.util.password.BasicPasswordEncryptor

@Entity
@Table(){val name="users"}
class User extends BaseEntity {
  @Id
  @GeneratedValue(){val strategy = GenerationType.IDENTITY}
  @Column(){val insertable = false, val unique = true}
  var id: Long = _

  @Column{val nullable = true}
  var first_name: String = "" 

  @Column{val nullable = true}
  var last_name: String = "" 

  @Column{val unique = true, val nullable = false}
  var username: String = "" 

  @Column{val nullable = false}
  var password_hash: String = "" 

  @Column{val unique = false, val nullable = false}
  var email: String = "" 

  @Column{val unique = false, val nullable = false}
  var is_active: Boolean = false

  def password: String = this.password_hash

  def password_=(in: String) = this.password_hash = encrypt(in)

  def authenticate(in: String): Boolean = {
    new BasicPasswordEncryptor().checkPassword(in, password) 
      && is_active
  }

  private def encrypt(in: String): String = 
    new BasicPasswordEncryptor().encryptPassword(in)

}
blog comments powered by Disqus