enkripsi data kolom di hibernate menggunakan jasypt


kalo kita pake JDBC, iBatis gampang sekali jika kita mau membaut sebuah kolom yang hasil save ke databasenya itu di enkripsi, tinggal kasih funsi PASSWORD(value) di perintah INSERT nya aja (itu kalo di MySQL. Tapi berbeda dengan di Hibernate, kalo kita akan mengenkripsi hasil data di database agak triki untuk melakukannya.

cara pertama mungkin kita enkripsi di class Entity yang kita buat dan cara yang kedua adalah kita membaut UserType sendiri. Dan sekarang gw mo kasih tutorial tentang cara enkripsi data kolom menggunakan UserType. UserType itu adalah tipe kolom yang bisa kita buat jika memang hibernate tidak memiliki kemampuan yang kita inginkan, di contoh ini adalah enkripsi data 😀Jadi sekarang kita dituntut untuk jadi Developer bukan User 😀 , maksudnya kita bukan cuma jadi pengguna Hibernate tapi juga bisa jadi pengembang Hibernate 😀 .  Langkah awal pada tutorial ini adalah download dulu framework Jasypt, karena kita akan pake Jasypt untuk mengenkripsi data, hal ini agar memudahkan aja 😀 silahkan download disini http://www.jasypt.org/

setelah itu buat UserType baru, misal disini gw kasih nama classnya EncryptedStringUserType, dimana untuk membuat UserType baru kita harus membuat class yang mengimplementasi dari class UserType milik Hibernate :

/*
 * Copyright 2009 echo.khannedy@gmail.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.echo.learninghibernate.type;

import java.io.Serializable;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.hibernate.Hibernate;
import org.hibernate.HibernateException;
import org.hibernate.usertype.UserType;
import org.jasypt.util.text.BasicTextEncryptor;

/**
 *
 * @author echo
 */
public class EncryptedStringUserType implements UserType {

    private BasicTextEncryptor encryptor;

    public EncryptedStringUserType() {
        encryptor = new BasicTextEncryptor();
        encryptor.setPassword(")(*&^%$#@!~!&#%~*#^~(#~%$");
    }

    public int[] sqlTypes() {
        return new int[]{
                    Hibernate.STRING.sqlType()
                };
    }

    public Class returnedClass() {
        return String.class;
    }

    public boolean equals(Object x, Object y) throws HibernateException {
        return x.equals(y);
    }

    public int hashCode(Object x) throws HibernateException {
        return x.hashCode();
    }

    public Object nullSafeGet(ResultSet rs, String[] names, Object owner) throws HibernateException, SQLException {
        String value = rs.getString(names[0]);
        String result = encryptor.decrypt(value);
        return result;
    }

    public void nullSafeSet(PreparedStatement st, Object value, int index) throws HibernateException, SQLException {
        if (value == null) {
            st.setNull(index, Hibernate.STRING.sqlType());
        } else {
            String result = encryptor.encrypt((String) value);
            st.setString(index, result);
        }
    }

    public Object deepCopy(Object value) throws HibernateException {
        return value;
    }

    public boolean isMutable() {
        return false;
    }

    public Serializable disassemble(Object value) throws HibernateException {
        return (Serializable) value;
    }

    public Object assemble(Serializable cached, Object owner) throws HibernateException {
        return cached;
    }

    public Object replace(Object original, Object target, Object owner) throws HibernateException {
        return original;
    }
}

setelah itu, tinggal kita mapping ke kolom yang ada di class Entity, misal gw buat class Entity COntoh :

/*
 * Copyright 2009 echo.khannedy@gmail.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.echo.learninghibernate.entity;

import com.echo.learninghibernate.type.EncryptedStringUserType;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.annotations.Type;
import org.hibernate.annotations.TypeDef;
import org.hibernate.annotations.TypeDefs;

/**
 *
 * @author echo
 */
@Entity
@Table(name="table_contoh")
@TypeDefs(
    @TypeDef(name="password", typeClass=EncryptedStringUserType.class)
)
public class Contoh implements Serializable{

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private Long id;

    @Column(name="username", nullable=false)
    private String username;

    @Type(type="password")
    @Column(name="password", nullable=false)
    private String password;

    public Contoh() {
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        final Contoh other = (Contoh) obj;
        if (this.id != other.id && (this.id == null || !this.id.equals(other.id))) {
            return false;
        }
        if ((this.username == null) ? (other.username != null) : !this.username.equals(other.username)) {
            return false;
        }
        if ((this.password == null) ? (other.password != null) : !this.password.equals(other.password)) {
            return false;
        }
        return true;
    }

    @Override
    public int hashCode() {
        int hash = 3;
        hash = 97 * hash + (this.id != null ? this.id.hashCode() : 0);
        hash = 97 * hash + (this.username != null ? this.username.hashCode() : 0);
        hash = 97 * hash + (this.password != null ? this.password.hashCode() : 0);
        return hash;
    }

}

diatas itu gw mapping usertype di kolom username, yang artinya kolom username sekarang akan di enkripsi saat di save ke databae, tapi saat di load ke Object maka aman di dekripsi lagi sehingga akan menjadi string aslinya. dan dibawah ini contoh hasil di databasenya :

mysql> select * from table_contoh;
+----+----------------------------------------------+---------------+
| id | password                                     | username      |
+----+----------------------------------------------+---------------+
|  1 | 0f+0RvY/75rd1uBbsZ4maGIHoLY/GFatQO+pIA6hmIo= | eko.keren     |
|  2 | lZi311FOoG1ZvitYOhtrtj46qdyLQFGh             | echo.khannedy |
+----+----------------------------------------------+---------------+
2 rows in set (0.00 sec)

enjoy

Iklan

10 pemikiran pada “enkripsi data kolom di hibernate menggunakan jasypt

  1. Mas tutorialnya bagus tp memahaminya butuh waktu. Sy mau nanya bagian baris yang ini : hash = 97 * hash + (this.id != null ? this.id.hashCode() : 0); Baris ini maksudnya apa ya ? Trus 97 itu konstanta apa ? Thx.

Tinggalkan Balasan

Isikan data di bawah atau klik salah satu ikon untuk log in:

Logo WordPress.com

You are commenting using your WordPress.com account. Logout / Ubah )

Gambar Twitter

You are commenting using your Twitter account. Logout / Ubah )

Foto Facebook

You are commenting using your Facebook account. Logout / Ubah )

Foto Google+

You are commenting using your Google+ account. Logout / Ubah )

Connecting to %s