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 BigDecimal 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="encryptedBigDecimal" class="org.jasypt.hibernate.type.EncryptedBigDecimalType">
      <param name="encryptorRegisteredName">myHibernateBigDecimalEncryptor</param>
      <param name="decimalScale">2</param>
    </typedef>
    ...
    <class name="UserData" table="USER_DATA">
      ...
      <property name="salary" column="SALARY" type="encryptedBigDecimal" />
      ...
    <class>
    ...
  <hibernate-mapping>
 

...where a HibernatePBEBigDecimalEncryptor object should have been previously registered to be used from Hibernate with name myHibernateBigDecimalEncryptor (see org.jasypt.hibernate.encryptor.HibernatePBEBigDecimalEncryptor 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="encryptedBigDecimal" class="org.jasypt.hibernate.type.EncryptedBigDecimalType">
      <param name="algorithm">PBEWithMD5AndTripleDES</param>
      <param name="password">XXXXX</param>
      <param name="keyObtentionIterations">1000</param>
      <param name="decimalScale">2</param>
    </typedef>
    ...
    <class name="UserData" table="USER_DATA">
      ...
      <property name="address" column="ADDRESS" type="encryptedBigDecimal" />
      ...
    <class>
    ...
  <hibernate-mapping>
 

About the decimalScale parameter

The decimalScale parameter is aimed at setting the scale with which BigDecimal numbers will be set to and retrieved from the database. It is an important parameter because many DBMSs return BigDecimal numbers with a scale equal to the amount of decimal positions declared for the field (e.g. if we store "18.23" (scale=2) in a DECIMAL(15,5) field, we can get a "18.23000" (scale=5) back when we retrieve the number). This can affect correct decryption of encrypted numbers, but specifying a decimalScale parameter will solve this issue.

So, if we set decimalScale to 3, and we store "18.23", this Hibernate type will send "18.230" to the encryptor, which is the value that we will get back from the database at retrieval time (a scale of "3" will be set again on the value obtained from DB). If it is necessary, a DOWN rounding operation is executed on the number.


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 EncryptedBigDecimalType implements UserTypeParameterizedType {
    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 Integer decimalScale = null;
    
    private PBEBigDecimalEncryptor encryptor = null;
    
    public int[] sqlTypes() {
        return ;
    }
    
    public Class returnedClass() {
        return BigDecimal.class;
    }
    
    public boolean equals(Object xObject y
            throws HibernateException {
        return EqualsHelper.equals(xy);
    }
    
    
    public Object deepCopy(Object value)
            throws HibernateException {
        return value;
    }
    
    
    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 false;
    }
    public int hashCode(Object x)
            throws HibernateException {
        return x.hashCode();
    }
    
    public Object replace(Object originalObject targetObject owner
            throws HibernateException {
        return original;
    }
    
    public Object nullSafeGet(ResultSet rsString[] namesObject owner)
            throws HibernateExceptionSQLException {
        checkInitialization();
        BigDecimal storedEncryptedMessage = rs.getBigDecimal(names[0]);
        if (rs.wasNull()) {
            return null;
        }
        BigDecimal scaledEncryptedMessage = 
            storedEncryptedMessage.setScale(
                    .intValue(), .); 
        return this..decrypt(scaledEncryptedMessage);
    }
    
    public void nullSafeSet(PreparedStatement stObject valueint index)
            throws HibernateExceptionSQLException {
        checkInitialization();
        if (value == null) {
            st.setNull(index);
        } else {
            BigDecimal scaledValue = 
                ((BigDecimalvalue).setScale(
                        .intValue(), .);
            BigDecimal encryptedMessage = 
                this..encrypt(scaledValue);
            st.setBigDecimal(indexencryptedMessage);
        }
    }
    
    public synchronized void setParameterValues(Properties parameters) {
        
        String paramEncryptorName =
            parameters.getProperty(.);
        String paramAlgorithm =
            parameters.getProperty(.);
        String paramPassword =
            parameters.getProperty(.);
        String paramKeyObtentionIterations =
            parameters.getProperty(.);
        String paramDecimalScale =
            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");
            
        }
        
        if (paramDecimalScale != null) {
            
            try {
                this. = 
                    new Integer(Integer.parseInt(paramDecimalScale));
            } catch (NumberFormatException e) {
                throw new EncryptionInitializationException(
                        "Value specified for \"" + 
                        . + 
                        "\" is not a valid integer");
            }
            
        } else {
            
            throw new EncryptionInitializationException(
                    . + 
                    " must be specified");
            
        }
        
    }
    
    
    private synchronized void checkInitialization() {
        
        if (!this.) {
            
            if (this.) {
                HibernatePBEEncryptorRegistry registry = 
                    HibernatePBEEncryptorRegistry.getInstance();
                PBEBigDecimalEncryptor pbeEncryptor = 
                    registry.getPBEBigDecimalEncryptor();
                if (pbeEncryptor == null) {
                    throw new EncryptionInitializationException(
                            "No big decimal encryptor registered for hibernate " +
                            "with name \"" +  + "\"");
                }
                this. = pbeEncryptor;
                
            } else {
                
                StandardPBEBigDecimalEncryptor newEncryptor = 
                    new StandardPBEBigDecimalEncryptor();
                
                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