Se finisci di eseguire il lavoro nell'applicazione, puoi utilizzare i tipi personalizzati di Hibernate e non aggiungerebbero molte modifiche al tuo codice.
Ecco un tipo personalizzato di stringa crittografata che ho usato:
import org.hibernate.usertype.UserType
import org.apache.log4j.Logger
import java.sql.PreparedStatement
import java.sql.ResultSet
import java.sql.SQLException
import java.sql.Types
class EncryptedString implements UserType {
// prefix category name with 'org.hibernate.type' to make logging of all types easier
private final Logger _log = Logger.getLogger('org.hibernate.type.com.yourcompany.EncryptedString')
Object nullSafeGet(ResultSet rs, String[] names, Object owner) throws SQLException {
String value = rs.getString(names[0])
if (!value) {
_log.trace "returning null as column: $names[0]"
return null
}
_log.trace "returning '$value' as column: $names[0]"
return CryptoUtils.decrypt(value)
}
void nullSafeSet(PreparedStatement st, Object value, int index) throws SQLException {
if (value) {
String encrypted = CryptoUtils.encrypt(value.toString())
_log.trace "binding '$encrypted' to parameter: $index"
st.setString index, encrypted
}
else {
_log.trace "binding null to parameter: $index"
st.setNull(index, Types.VARCHAR)
}
}
Class<String> returnedClass() { String }
int[] sqlTypes() { [Types.VARCHAR] as int[] }
Object assemble(Serializable cached, Object owner) { cached.toString() }
Object deepCopy(Object value) { value.toString() }
Serializable disassemble(Object value) { value.toString() }
boolean equals(Object x, Object y) { x == y }
int hashCode(Object x) { x.hashCode() }
boolean isMutable() { true }
Object replace(Object original, Object target, Object owner) { original }
}
e in base a questo dovrebbe essere semplice creare classi simili per int, long, ecc. Per usarlo, aggiungi il tipo alla chiusura della mappatura:
class MyDomainClass {
String name
String otherField
static mapping = {
name type: EncryptedString
otherField type: EncryptedString
}
}
Ho omesso i metodi CryptoUtils.encrypt() e CryptoUtils.decrypt() poiché non sono specifici di Grails. Stiamo usando AES, ad es. "Cifrario cifrato =Cipher.getInstance('AES/CBC/PKCS5Padding')". Qualunque cosa tu finisca per usare, assicurati che sia una crittografia a 2 vie, cioè non usare SHA-256.