View Javadoc
1   /**
2    * Copyright 2005-2014 The Kuali Foundation
3    *
4    * Licensed under the Educational Community License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    * http://www.opensource.org/licenses/ecl2.php
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  package org.kuali.rice.krad.data.jpa.converters;
17  
18  import javax.persistence.AttributeConverter;
19  import javax.persistence.Converter;
20  
21  import org.apache.commons.lang.StringUtils;
22  import org.kuali.rice.core.api.CoreApiServiceLocator;
23  import org.kuali.rice.core.api.encryption.EncryptionService;
24  
25  /**
26   * Calls the core service to hash values going to the database.
27   * 
28   *  @author Kuali Rice Team (rice.collab@kuali.org)
29   */
30  @Converter
31  public class HashConverter implements AttributeConverter<String, String> {
32  
33      /**
34       * {@inheritDoc}
35       *
36       * This implementation hashes the value going to the database.
37       */
38  	@Override
39  	public String convertToDatabaseColumn(String objectValue) {
40  		// don't attempt to encrypt nulls or empty strings
41  		if (objectValue == null) {
42  			return null;
43  		}
44  		if (StringUtils.isEmpty(objectValue.toString())) {
45  			return "";
46  		}
47  		// don't convert if already a hashed value
48  		if (objectValue.toString().endsWith(EncryptionService.HASH_POST_PREFIX)) {
49  			return StringUtils.stripEnd(objectValue.toString(), EncryptionService.HASH_POST_PREFIX);
50  		} else {
51  			try {
52  				return CoreApiServiceLocator.getEncryptionService().hash(objectValue);
53  			} catch (Exception e) {
54  				throw new RuntimeException("Exception while attempting to hash value for DB: ", e);
55  			}
56  		}
57  	}
58  
59      /**
60       * {@inheritDoc}
61       *
62       * This implementation directly returns the hash value coming from the database.
63       */
64  	@Override
65  	public String convertToEntityAttribute(String dataValue) {
66  		// don't attempt to decrypt nulls or empty strings
67  		if (dataValue == null) {
68  			return null;
69  		}
70  		if (StringUtils.isEmpty(dataValue.toString())) {
71  			return "";
72  		}
73  		return dataValue.toString() + EncryptionService.HASH_POST_PREFIX;
74  	}
75  
76  }