1 19 20 package org.efs.openreports.util; 21 22 import java.io.Serializable ; 23 import java.sql.*; 24 25 import org.apache.commons.codec.DecoderException; 26 import org.apache.commons.codec.EncoderException; 27 import org.apache.commons.codec.net.BCodec; 28 import org.apache.log4j.Logger; 29 30 import org.hibernate.Hibernate; 31 import org.hibernate.HibernateException; 32 import org.hibernate.usertype.*; 33 34 public class EncryptedStringUserType implements UserType 35 { 36 protected static Logger log = Logger.getLogger(EncryptedStringUserType.class); 37 38 private static final int[] TYPES = new int[]{Types.VARCHAR}; 39 40 private BCodec bCodec = new BCodec(); 41 42 public int[] sqlTypes() 43 { 44 return TYPES; 45 } 46 47 public Class returnedClass() 48 { 49 return String .class; 50 } 51 52 public boolean equals(Object x, Object y) throws HibernateException 53 { 54 if (x == y) 55 { 56 return true; 57 } 58 59 if (x == null) 60 { 61 return false; 62 } 63 64 return x.equals(y); 65 } 66 67 public Object nullSafeGet(ResultSet rs, String [] names, Object owner) 68 throws HibernateException, SQLException 69 { 70 String encryptedValue = (String ) Hibernate.STRING.nullSafeGet(rs, names[0]); 71 72 if (encryptedValue != null) 73 { 74 return decrypt(encryptedValue); 75 } 76 else 77 { 78 return null; 79 } 80 } 81 82 public void nullSafeSet(PreparedStatement pStmt, Object value, int index) 83 throws HibernateException, SQLException 84 { 85 if (value != null) 86 { 87 String encryptedValue = encrypt((String ) value); 88 Hibernate.STRING.nullSafeSet(pStmt, encryptedValue, index); 89 } 90 else 91 { 92 Hibernate.STRING.nullSafeSet(pStmt, value, index); 93 } 94 } 95 96 public Object deepCopy(Object value) throws HibernateException 97 { 98 if (value == null) 99 { 100 return null; 101 } 102 else 103 { 104 return new String ((String ) value); 105 } 106 } 107 108 public boolean isMutable() 109 { 110 return false; 111 } 112 113 protected String encrypt(String value) 114 { 115 try 116 { 117 return bCodec.encode(value); 118 } 119 catch(EncoderException ee) 120 { 121 log.warn("ENCRYPT - " + value + " : " + ee.getMessage()); 122 return value; 123 } 124 } 125 126 protected String decrypt(String value) 127 { 128 try 129 { 130 return bCodec.decode(value); 131 } 132 catch(DecoderException de) 133 { 134 log.warn("DECRYPT - " + value + " : " + de.getMessage()); 135 return value; 136 } 137 } 138 139 public int hashCode(Object arg0) throws HibernateException 140 { 141 return arg0.hashCode(); 142 } 143 144 145 public Object replace(Object arg0, Object arg1, Object arg2) 146 throws HibernateException 147 { 148 return deepCopy(arg0); 149 } 150 151 public Object assemble(Serializable arg0, Object arg1) throws HibernateException 152 { 153 return deepCopy(arg0); 154 } 155 156 public Serializable disassemble(Object value) 157 { 158 return (Serializable ) deepCopy(value); 159 } 160 161 } | Popular Tags |