Sample spring configuration file encryption method

  • 2020-11-18 06:15:39
  • OfStack

The Spring configuration file is the "drawing" that guides the Spring factory to perform Bean generation, dependency injection, and Bean sample distribution. It is an XML document with one or more tiles. The J2EE programmer must learn to flexibly apply this "drawing" to accurately express his "build intent". The Spring configuration file is one or more standard XML documents, and applicationContext.xml is the default configuration file for Spring. When the container starts, the specified configuration file cannot be found, it will attempt to load the default configuration file.

spring framework in some production environments with high security requirements, configuration files do not allow plaintext username and password configuration, such as database configuration. This paper is mainly used to solve the plaintext username and password encryption.

Decryption of ciphertext by inheriting the spring configuration class override method


public class EncryptPropertyPlaceholderConfigurer extends PropertyPlaceholderConfigurer {
	 private String[] encryptPropNames = {"username", "password"}; 

	@Override
	protected void processProperties(ConfigurableListableBeanFactory beanFactory,
			Properties props) throws BeansException {
		try {
		for (int i = 0;i<encryptPropNames.length;i++){
			 String value = props.getProperty(encryptPropNames[i]);
       if (value != null) {
					props.setProperty(encryptPropNames[i],new String(DES.decrypt(new BASE64Decoder().decodeBuffer(value), " Solution of the secret key ")));
       }
      
		}
		super.processProperties(beanFactory, props);
		} catch (Exception e) {
			 e.printStackTrace();
       throw new BeanInitializationException(e.getMessage());
		}
	} 
}

Configure the applicationContext.xml file and set the ciphertext in jdbc.properties (generated from the decryption key)


<!-- class Fill in the classpath for that code -->
<bean id="propertyConfigurer" class="com.**.EncryptPropertyPlaceholderConfigurer"> 
      <property name="locations">
        <list>
          <value>classpath:jdbc.properties</value>
        </list>
      </property>
  </bean>

conclusion

That's the end of this article on the spring configuration file encryption example, and I hope you found it helpful. Those who are interested can continue to see this site:

Java programming implementation springMVC simple login instance

SpringMVC Development restful API user query code details

Maven Management SpringBoot Profile details

If there is any deficiency, please let me know. Thank you for your support to this site.


Related articles: