View Javadoc
1   /**
2    * Copyright 2005-2015 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  
24  /**
25   * Calls the core service to encrypt values going to the database and decrypt values coming back from the database.
26   *
27   * @author Kuali Rice Team (rice.collab@kuali.org)
28   */
29  @Converter
30  public class EncryptionConverter implements AttributeConverter<String, String> {
31  
32      /**
33       * {@inheritDoc}
34       *
35       * This implementation encrypts the value going to the database.
36       */
37  	@Override
38  	public String convertToDatabaseColumn(String objectValue) {
39  		// don't attempt to encrypt nulls or empty strings
40  		if (objectValue == null) {
41  			return null;
42  		}
43  		if (StringUtils.isEmpty(objectValue.toString())) {
44  			return "";
45  		}
46  		try {
47  			// check if the encryption service is enable before using it
48  			if (CoreApiServiceLocator.getEncryptionService().isEnabled()) {
49  				return CoreApiServiceLocator.getEncryptionService().encrypt(objectValue);
50  			}
51  		} catch (Exception e) {
52  			throw new RuntimeException("Exception while attempting to encrypt value for DB: ", e);
53  		}
54  		return objectValue;
55  	}
56  
57      /**
58       * {@inheritDoc}
59       *
60       * This implementation decrypts the value coming from the database.
61       */
62  	@Override
63  	public String convertToEntityAttribute(String dataValue) {
64  		// don't attempt to decrypt nulls or empty strings
65  		if (dataValue == null) {
66  			return null;
67  		}
68  		if (StringUtils.isEmpty(dataValue.toString())) {
69  			return "";
70  		}
71  		try {
72  			// check if the encryption service is enable before using it
73  			if (CoreApiServiceLocator.getEncryptionService().isEnabled()) {
74  				return CoreApiServiceLocator.getEncryptionService().decrypt(dataValue.toString());
75  			}
76  		} catch (Exception e) {
77  			throw new RuntimeException("Exception while attempting to decrypt value from DB: ", e);
78  		}
79  		return dataValue;
80  	}
81  
82  }