001/**
002 * Copyright 2005-2018 The Kuali Foundation
003 *
004 * Licensed under the Educational Community License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 * http://www.opensource.org/licenses/ecl2.php
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016package org.kuali.rice.core.framework.persistence.ojb.conversion;
017
018import java.security.GeneralSecurityException;
019
020import org.apache.commons.lang.StringUtils;
021import org.apache.ojb.broker.accesslayer.conversions.FieldConversion;
022import org.kuali.rice.core.api.CoreApiServiceLocator;
023import org.kuali.rice.core.api.encryption.EncryptionService;
024
025
026/**
027 * This class calls core service to hash values going to the database.
028 * 
029 * 
030 */
031
032public class OjbKualiHashFieldConversion implements FieldConversion {
033
034    /**
035     * @see FieldConversion#javaToSql(Object)
036     */
037    public Object javaToSql(Object source) {
038        Object converted = source;
039        if ( converted != null ) {
040            // don't convert if already a hashed value
041            if ( converted.toString().endsWith( EncryptionService.HASH_POST_PREFIX ) ) {
042                converted = StringUtils.stripEnd( converted.toString(), EncryptionService.HASH_POST_PREFIX );
043            } else {
044                try {
045                    converted = CoreApiServiceLocator.getEncryptionService().hash(converted);
046                } catch (GeneralSecurityException e) {
047                    throw new RuntimeException("Unable to hash value to db: " + e.getMessage());
048                }
049            }
050        }
051
052        return converted;
053    }
054
055    /**
056     * @see FieldConversion#sqlToJava(Object)
057     */
058    public Object sqlToJava(Object source) {
059        if ( source == null ) {
060            return "";
061        }
062        return source.toString() + EncryptionService.HASH_POST_PREFIX;
063    }
064}