View Javadoc

1   /**
2    * Copyright 2005-2013 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   * This class calls core service to hash values going to the database.
27   * 
28   * 
29   */
30  @Converter
31  public class HashConverter implements AttributeConverter<String, String> {
32  
33  	@Override
34  	public String convertToDatabaseColumn(String objectValue) {
35  		// don't attempt to encrypt nulls or empty strings
36  		if (objectValue == null) {
37  			return null;
38  		}
39  		if (StringUtils.isEmpty(objectValue.toString())) {
40  			return "";
41  		}
42  		// don't convert if already a hashed value
43  		if (objectValue.toString().endsWith(EncryptionService.HASH_POST_PREFIX)) {
44  			return StringUtils.stripEnd(objectValue.toString(), EncryptionService.HASH_POST_PREFIX);
45  		} else {
46  			try {
47  				return CoreApiServiceLocator.getEncryptionService().hash(objectValue);
48  			} catch (Exception e) {
49  				throw new RuntimeException("Exception while attempting to hash value for DB: ", e);
50  			}
51  		}
52  	}
53  
54  	@Override
55  	public String convertToEntityAttribute(String dataValue) {
56  		// don't attempt to decrypt nulls or empty strings
57  		if (dataValue == null) {
58  			return null;
59  		}
60  		if (StringUtils.isEmpty(dataValue.toString())) {
61  			return "";
62  		}
63  		return dataValue.toString() + EncryptionService.HASH_POST_PREFIX;
64  	}
65  
66  }