Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * =============================================================================
   * 
   *   Copyright (c) 2007, The JASYPT team (http://www.jasypt.org)
   * 
   *   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 org.jasypt.hibernate.type;
 
 

A Hibernate 3 UserType implementation which allows transparent encryption of byte[] values during persistence of entities.

This class is intended only for declarative use from a Hibernate mapping file. Do not use it directly from your .java files (although of course you can use it when mapping entities using annotations).

To use this Hibernate type in one of your Hibernate mappings, you can add it like this:

  <hibernate-mapping package="myapp">
    ...
    <typedef name="encryptedBinary" class="org.jasypt.hibernate.type.EncryptedBinaryType">
      <param name="encryptorRegisteredName">myHibernateByteEncryptor</param>
    </typedef>
    ...
    <class name="UserData" table="USER_DATA">
      ...
      <property name="resume" column="RESUME" type="encryptedBinary" />
      ...
    <class>
    ...
  <hibernate-mapping>
 

...where a HibernatePBEByteEncryptor object should have been previously registered to be used from Hibernate with name myHibernateByteEncryptor (see org.jasypt.hibernate.encryptor.HibernatePBEByteEncryptor and org.jasypt.hibernate.encryptor.HibernatePBEEncryptorRegistry).

Or, if you prefer to avoid registration of encryptors, you can configure your encryptor directly in the mapping file (although not recommended), like this:

  <hibernate-mapping package="myapp">
    ...
    <typedef name="encryptedBinary" class="org.jasypt.hibernate.type.EncryptedBinaryType">
      <param name="algorithm">PBEWithMD5AndTripleDES</param>
      <param name="password">XXXXX</param>
      <param name="keyObtentionIterations">1000</param>
    </typedef>
    ...
    <class name="UserData" table="USER_DATA">
      ...
      <property name="resume" column="RESUME" type="encryptedBinary" />
      ...
    <class>
    ...
  <hibernate-mapping>
 

To learn more about usage of user-defined types, please refer to the Hibernate Reference Documentation.

Author(s):
Daniel Fernández Garrido
Since:
1.2
public final class EncryptedBinaryType implements UserTypeParameterizedType {
    private static final int BLOCK_SIZE = 2048;
    
    private static NullableType nullableType = .;
    private static int sqlType = .sqlType();
    private static int[] sqlTypes = new int[]{  };
    
    private boolean initialized = false;
    private boolean useEncryptorName = false;
    
    private String encryptorName = null;
    private String algorithm = null;
    private String password = null;
    private Integer keyObtentionIterations = null;
    
    private PBEByteEncryptor encryptor = null;
    
    public int[] sqlTypes() {
        return ;
    }
    
    public Class returnedClass() {
        return byte[].class;
    }
    
    public boolean equals(Object xObject y
            throws HibernateException {
        
        return (x == y) || 
               (x != null && y != null && java.util.Arrays.equals((byte[]) x, (byte[]) y));
        
    }
    
    
    public Object deepCopy(Object value)
            throws HibernateException {
        
        if (value == null) {
            return null;
        }
        byte[] valueBytes = (byte[]) value;
        byte[] copyBytes = new byte[valueBytes.length];
        System.arraycopy(valueBytes, 0, copyBytes, 0, valueBytes.length);
        return copyBytes;
        
    }
    
    
    public Object assemble(Serializable cachedObject owner)
            throws HibernateException {
        if (cached == null) {
            return null;
        } else {
            return deepCopy(cached);
        }
    }
    
    public Serializable disassemble(Object value
            throws HibernateException {
        if (value == null) {
            return null;
        } else {
            return (SerializabledeepCopy(value);
        }
    }
    
    public boolean isMutable() {
        return true;
    }
    public int hashCode(Object x)
            throws HibernateException {
        
        byte[] valueBytes = (byte[]) x;
        int result = 1;
        for (int i = 0; i < valueBytes.lengthi++ ) {
            result = (result * 17) + valueBytes[i];
        }
        return result;
        
    }
    
    public Object replace(Object originalObject targetObject owner
            throws HibernateException {
        return (original == null)? null : deepCopy(original);
    }
    
    public Object nullSafeGet(ResultSet rsString[] namesObject owner)
            throws HibernateExceptionSQLException {
        checkInitialization();
        byte[] encryptedValue = null;
        if (Environment.useStreamsForBinary()) {
            InputStream inputStream = rs.getBinaryStream(names[0]);
            if (rs.wasNull()) {
                return null;
            }
            
            ByteArrayOutputStream outputStream = 
                new ByteArrayOutputStream();
            byte[] inputBuff = new byte[];
            try {
                int readBytes = 0;
                while (readBytes != -1) {
                    readBytes = inputStream.read(inputBuff);
                    if (readBytes != -1) {
                        outputStream.write(inputBuff, 0, readBytes);
                    }
                }
            } catch (IOException e) {
                throw new HibernateException(
                        "IOException occurred reading a binary value"e);
            } finally {
                try {
                    inputStream.close();
                } catch (IOException e) {}
                try {
                    outputStream.close();
                } catch (IOException e) {}
            }
            
            encryptedValue = outputStream.toByteArray();
            
        } else {
            
            encryptedValue = rs.getBytes(names[0]);
            if (rs.wasNull()) {
                return null;
            }
            
        }
        
        return this..decrypt(encryptedValue);
        
    }
    
    public void nullSafeSet(PreparedStatement stObject valueint index)
            throws HibernateExceptionSQLException {
        checkInitialization();
        
        if (value == null) {
            st.setNull(index);
        } else {
            byte[] encryptedValue = this..encrypt((byte[]) value);
            if (Environment.useStreamsForBinary()) {
                st.setBinaryStream(
                        index
                        new ByteArrayInputStream(encryptedValue), 
                        encryptedValue.length);
            } else {
                st.setBytes(indexencryptedValue);
            }
        }
        
    }
    
    public synchronized void setParameterValues(Properties parameters) {
        
        String paramEncryptorName =
            parameters.getProperty(.);
        String paramAlgorithm =
            parameters.getProperty(.);
        String paramPassword =
            parameters.getProperty(.);
        String paramKeyObtentionIterations =
            parameters.getProperty(.);
        
        this. = false;
        if (paramEncryptorName != null) {
            
            if ((paramAlgorithm != null) ||
                (paramPassword != null) ||
                (paramKeyObtentionIterations != null)) {
                
                throw new EncryptionInitializationException(
                        "If \"" + . + 
                        "\" is specified, none of \"" +
                        . + "\", \"" +
                        . + "\" or \"" + 
                        . + "\" " +
                        "can be specified");
                
            }
            this. = paramEncryptorName;
            this. = true;
            
        } else if ((paramPassword != null)) {
            this. = paramPassword;
            
            if (paramAlgorithm != null) {
                this. = paramAlgorithm;
            }
            
            if (paramKeyObtentionIterations != null) {
                try {
                    this. = 
                        new Integer(
                                Integer.parseInt(paramKeyObtentionIterations));
                } catch (NumberFormatException e) {
                    throw new EncryptionInitializationException(
                            "Value specified for \"" + 
                            . + 
                            "\" is not a valid integer");
                }
                
            }
            
        } else {
            
            throw new EncryptionInitializationException(
                    "If \"" + . + 
                    "\" is not specified, then \"" +
                    . + "\" (and optionally \"" +
                    . + "\" and \"" + 
                    . + "\") " +
                    "must be specified");
            
        }
    }
    
    
    private synchronized void checkInitialization() {
        
        if (!this.) {
            
            if (this.) {
                HibernatePBEEncryptorRegistry registry = 
                    HibernatePBEEncryptorRegistry.getInstance();
                PBEByteEncryptor pbeEncryptor = 
                    registry.getPBEByteEncryptor();
                if (pbeEncryptor == null) {
                    throw new EncryptionInitializationException(
                            "No big integer encryptor registered for hibernate " +
                            "with name \"" +  + "\"");
                }
                this. = pbeEncryptor;
                
            } else {
                
                StandardPBEByteEncryptor newEncryptor = 
                    new StandardPBEByteEncryptor();
                
                newEncryptor.setPassword(this.);
                
                if (this. != null) {
                    newEncryptor.setAlgorithm(this.);
                }
                
                if (this. != null) {
                    newEncryptor.setKeyObtentionIterations(
                            this..intValue());
                }
                
                newEncryptor.initialize();
                
                this. = newEncryptor;
                
            }
            
            this. = true;
        }
        
    }
    
    
New to GrepCode? Check out our FAQ X