In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly introduces the springboot project database password how to achieve encryption related knowledge, the content is detailed and easy to understand, the operation is simple and fast, has a certain reference value, I believe that everyone after reading this springboot project database password how to achieve encryption article will have a harvest, let's take a look.
Scheme 1. Encrypt the database password by using druid database connection pool
1. Pom.xml introduces druid package
In order to facilitate other operations, druid's starter is directly introduced here.
Com.alibaba druid-spring-boot-starter ${druid.version}
2. Use com.alibaba.druid.filter.config.ConfigTools to generate public and private keys
Ps: there are two ways to generate it: one is generated from the command line, and the other is generated directly from a tool class. The example in this article is generated directly from the tool class.
The tool class code is as follows
/ * alibaba druid encryption and decryption rules: * plaintext password + private key (privateKey) encryption = encryption password * encryption password + public key (publicKey) decryption = plaintext password * / public final class DruidEncryptorUtils {private static String privateKey; private static String publicKey; static {String [] keyPair = ConfigTools.genKeyPair; privateKey = keyPair [0] System.out.println (String.format ("privateKey-- >% s", privateKey)); publicKey = keyPair [1]; System.out.println ("publicKey-- >% s", publicKey));} catch (NoSuchAlgorithmException e) {e.printStackTrace ();} catch (NoSuchProviderException e) {e.printStackTrace () Plaintext encryption * @ param plaintext * @ return * / @ SneakyThrows public static String encode (String plaintext) {System.out.println ("plaintext string:" + plaintext); String ciphertext = ConfigTools.encrypt (privateKey,plaintext); System.out.println ("encrypted string:" + ciphertext); return ciphertext } / * decrypt * @ param ciphertext * @ return * / @ SneakyThrows public static String decode (String ciphertext) {System.out.println ("encrypted string:" + ciphertext); String plaintext = ConfigTools.decrypt (publicKey,ciphertext); System.out.println ("decrypted string:" + plaintext); return plaintext;}
3. Modify the configuration file content information of the database
A, change the password
Replace the password with the password generated with the utility class DruidEncryptorUtils
Password: ${DATASOURCE_PWD:HB5FmUeAI1U81YJrT/T6awImFg1/Az5o8imy765WkVJouOubC2H80jqmZrr8L9zWKuzS/8aGzuQ4YySAkhywnA==}
B. Filter enable config
Filter: config: enabled: true
C. Configure the connectionProperties attribute
Connection-properties: config.decrypt=true;config.decrypt.key=$ {spring.datasource.publickey}
Ps: the public key generated by spring.datasource.publickey for the utility class
Appendix: complete database configuration
Spring: datasource: type: com.alibaba.druid.pool.DruidDataSource driverClassName: com.mysql.cj.jdbc.Driver url: ${DATASOURCE_URL:jdbc:mysql://localhost:3306/demo?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai} username: ${DATASOURCE_USERNAME:root} password: ${DATASOURCE_PWD:HB5FmUeAI1U81YJrT/T6awImFg1/Az5o8imy765WkVJouOubC2H80jqmZrr8L9zWKuzS/8aGzuQ4YySAkhywnA==} publickey: MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAIvP9xF4RCM4oFiu47NZY15iqNOAB9K2Ml9fiTLa05CWaXK7uFwBImR7xltZM1frl6ahWAXJB6a/FSjtJkTZUJECAwEAAQ== druid: # initial number of connections initialSize: 5 # minimum number of connection pools minIdle: 10 # maximum number of connection pools maxActive: 20 # configuration acquisition connection wait timeout maxWait: 60000 # configuration interval how often is it checked Detect idle connections that need to be closed in milliseconds timeBetweenEvictionRunsMillis: 60000 # configure the minimum survival time of a connection in the pool, in milliseconds minEvictableIdleTimeMillis: 300000 # configure the maximum survival time of a connection in the pool Unit: millisecond maxEvictableIdleTimeMillis: 900000 # configure to detect whether the connection is valid validationQuery: SELECT 1 FROM DUAL testWhileIdle: true testOnBorrow: false testOnReturn: false webStatFilter: enabled: true statViewServlet: enabled: true # set whitelist If left empty, all access to allow: url-pattern: / druid/* # console management username and password login-username: login-password: filter: stat: enabled: true # slow SQL record log-slow-sql: true slow-sql-millis: 1000 merge-sql: true wall: config: multi-statement-allow: true config: enabled: true connection-properties: config.decrypt=true Config.decrypt.key=$ {spring.datasource.publickey} scenario 2: encrypt the database password using jasypt
1. Pom.xml introduces jasypt package
Com.github.ulisesbocchio jasypt-spring-boot-starter ${jasypt.verison}
2. Encrypt the plaintext password by using the tool class provided by jasypt
The encryption tool classes are as follows
Public final class JasyptEncryptorUtils {private static final String salt = "lybgeek"; private static BasicTextEncryptor basicTextEncryptor = new BasicTextEncryptor (); static {basicTextEncryptor.setPassword (salt);} private JasyptEncryptorUtils () {} / * * plaintext encryption * @ param plaintext * @ return * / public static String encode (String plaintext) {System.out.println ("plaintext string:" + plaintext) String ciphertext = basicTextEncryptor.encrypt (plaintext); System.out.println ("encrypted string:" + ciphertext); return ciphertext;} / * * decrypted * @ param ciphertext * @ return * / public static String decode (String ciphertext) {System.out.println ("encrypted string:" + ciphertext); ciphertext = "ENC (" + ciphertext + ")" If (PropertyValueEncryptionUtils.isEncryptedValue (ciphertext)) {String plaintext = PropertyValueEncryptionUtils.decrypt (ciphertext,basicTextEncryptor); System.out.println ("decrypted string:" + plaintext "); return plaintext;} System.out.println (" decryption failed "); return";}}
3. Modify the configuration file content information of the database
A. Use ENC to package the encrypted string generated by JasyptEncryptorUtils
Password: ${DATASOURCE_PWD:ENC (P8m43qmzqN4c07DCTPey4QQ =)}
B. configure the key and specify the encryption and decryption algorithm
Jasypt: encryptor: password: lybgeek algorithm: PBEWithMD5AndDES iv-generator-classname: org.jasypt.iv.NoIvGenerator
Because my tool class uses encryption and decryption tool class is BasicTextEncryptor, its corresponding configuration encryption and decryption is PBEWithMD5AndDES and org.jasypt.iv.NoIvGenerator
Ps: in a production environment, it is recommended to configure keys in the following ways to avoid key disclosure
Java-jar-Djasypt.encryptor.password=lybgeek
Appendix: complete database configuration
Spring: datasource: type: com.alibaba.druid.pool.DruidDataSource driverClassName: com.mysql.cj.jdbc.Driver url: ${DATASOURCE_URL:ENC (kT/gwazwzaFNEp7OCbsgCQN7PHRohaTKJNdGVgLsW2cH67zqBVEq7mN0BTIXAeF4/Fvv4l7myLFx0y6ap4umod7C2VWgyRU5UQtKmdwzQN3hxVxktIkrFPn9DM6+YahM0xP+ppO9HaWqA2ral0ejBCvmor3WScJNHCAhI9kHjYc=)} username: ${DATASOURCE_USERNAME:ENC (rEQLlqM5nphqnsuPj3MlJw==)} password: ${DATASOURCE_PWD:ENC (P8m43qmzqN4c07DCTPey4Qconnections =)} druid: # initial connections initialSize: 5 # minimum number of connection pools minIdle: 10 # maximum number of connection pools maxActive: 20 # configure the time to get connection wait timeout maxWait: 60000 # configure how often is it checked Detect idle connections that need to be closed in milliseconds timeBetweenEvictionRunsMillis: 60000 # configure the minimum survival time of a connection in the pool, in milliseconds minEvictableIdleTimeMillis: 300000 # configure the maximum survival time of a connection in the pool Unit: millisecond maxEvictableIdleTimeMillis: 900000 # configure to detect whether the connection is valid validationQuery: SELECT 1 FROM DUAL testWhileIdle: true testOnBorrow: false testOnReturn: false webStatFilter: enabled: true statViewServlet: enabled: true # set whitelist If left empty, all access to allow: url-pattern: / druid/* # console management username and password login-username: login-password: filter: stat: enabled: true # slow SQL record log-slow-sql: true slow-sql-millis: 1000 merge-sql: true wall: config: multi-statement-allow: truejasypt: encryptor: password: lybgeek algorithm: PBEWithMD5AndDES iv-generator- Classname: org.jasypt.iv.NoIvGenerator scheme 3: custom implementation
Implementation principle: modify DataSource with spring post processor
1. Custom encryption and decryption tool class
/ * using the encryption and decryption tool encapsulated by hutool, take the AES symmetric encryption algorithm as an example * / public final class EncryptorUtils {secretKey = Hex.encodeHexString (SecureUtil.generateKey (SymmetricAlgorithm.AES.getValue ()). GetEncoded ()); System.out.println ("secretKey-- >" + secretKey) System.out.println ("-") } / * * plaintext encryption * @ param plaintext * @ return * / @ SneakyThrows public static String encode (String plaintext) {System.out.println ("plaintext string:" + plaintext); byte [] key = Hex.decodeHex (secretKey.toCharArray ()); String ciphertext = SecureUtil.aes (key) .encryptHex (plaintext) System.out.println ("encrypted string:" + ciphertext); return ciphertext;} / * * decrypt * @ param ciphertext * @ return * / @ SneakyThrows public static String decode (String ciphertext) {System.out.println ("encrypted string:" + ciphertext); byte [] key = Hex.decodeHex (secretKey.toCharArray ()) String plaintext = SecureUtil.aes (key) .decryptStr (ciphertext); System.out.println ("decrypted string:" + plaintext); return plaintext;} / * * plaintext encryption * @ param plaintext * @ return * / @ SneakyThrows public static String encode (String secretKey,String plaintext) {System.out.println ("plaintext string:" + plaintext) Byte [] key = Hex.decodeHex (secretKey.toCharArray ()); String ciphertext = SecureUtil.aes (key) .encryptHex (plaintext); System.out.println ("encrypted string:" + ciphertext); return ciphertext } / * decrypt * @ param ciphertext * @ return * / @ SneakyThrows public static String decode (String secretKey,String ciphertext) {System.out.println ("encrypted string:" + ciphertext); byte [] key = Hex.decodeHex (secretKey.toCharArray ()); String plaintext = SecureUtil.aes (key) .decryptStr (ciphertext) System.out.println ("decrypted string:" + plaintext); return plaintext;}}
2. Write a post processor
Public class DruidDataSourceEncyptBeanPostProcessor implements BeanPostProcessor {private CustomEncryptProperties customEncryptProperties; private DataSourceProperties dataSourceProperties; public DruidDataSourceEncyptBeanPostProcessor (CustomEncryptProperties customEncryptProperties, DataSourceProperties dataSourceProperties) {this.customEncryptProperties = customEncryptProperties; this.dataSourceProperties = dataSourceProperties;} @ Override public Object postProcessBeforeInitialization (Object bean, String beanName) throws BeansException {if (bean instanceof DruidDataSource) {if (customEncryptProperties.isEnabled ()) {DruidDataSource druidDataSource = (DruidDataSource) bean System.out.println ("-"); String username = dataSourceProperties.getUsername () DruidDataSource.setUsername (EncryptorUtils.decode (customEncryptProperties.getSecretKey (), username)); System.out.println ("-") String password = dataSourceProperties.getPassword (); druidDataSource.setPassword (EncryptorUtils.decode (customEncryptProperties.getSecretKey (), password)) System.out.println ("-"); String url = dataSourceProperties.getUrl () DruidDataSource.setUrl (EncryptorUtils.decode (customEncryptProperties.getSecretKey (), url)); System.out.println ("-") }} return bean;}}
3. Modify the configuration file content information of the database
A, change the password
Replace the password with an encrypted password generated with a custom encryption tool class
Password: ${DATASOURCE_PWD:fb31cdd78a5fa2c43f530b849f1135e7}
B. Specify the key and enable the encryption function
Custom: encrypt: enabled: true secret-key: 2f8ba810011e0973728afa3f28a0ecb6
Ps: similarly, secret-key is best not to be directly exposed in the configuration file. You can specify it with-Dcustom.encrypt.secret-key.
Appendix: complete database configuration
Spring: datasource: type: com.alibaba.druid.pool.DruidDataSource driverClassName: com.mysql.cj.jdbc.Driver url: ${DATASOURCE_URL:dcb268cf3a2626381d2bc5c96f94fb3d7f99352e0e392362cb818a321b0ca61f3a8dad3aeb084242b745c61a1d3dc244ed1484bf745c858c44560dde10e60e90ac65f77ce2926676df7af6b35aefd2bb984ff9a868f1f9052ee9cae5572fa015b66a602f32df39fb1bbc36e04cc0f148e4d610a3e5d54f2eb7c57e4729c9d7b4} username: ${DATASOURCE_USERNAME:61db3bf3c6d3fe3ce87549c1af1e9061} password: ${DATASOURCE_PWD:fb31cdd78a5fa2c43f530b849f1135e7} druid: # initial connections initialSize: 5 # minimum number of connection pools MinIdle: 10 # maximum number of connection pools maxActive: 20 # configure the time to get the connection wait timeout maxWait: 60000 # configure how often to detect Detect idle connections that need to be closed in milliseconds timeBetweenEvictionRunsMillis: 60000 # configure the minimum survival time of a connection in the pool, in milliseconds minEvictableIdleTimeMillis: 300000 # configure the maximum survival time of a connection in the pool Unit: millisecond maxEvictableIdleTimeMillis: 900000 # configure to detect whether the connection is valid validationQuery: SELECT 1 FROM DUAL testWhileIdle: true testOnBorrow: false testOnReturn: false webStatFilter: enabled: true statViewServlet: enabled: true # set whitelist If left empty, all access to allow: url-pattern: / druid/* # console management username and password login-username: login-password: filter: stat: enabled: true # slow SQL record log-slow-sql: true slow-sql-millis: 1000 merge-sql: true wall: config: multi-statement-allow: truecustom: encrypt: enabled: true secret-key: 2f8ba810011e0973728afa3f28a0ecb6 about "springboot item" This is the end of the article on how to encrypt the password of the database. Thank you for reading! I believe that everyone has a certain understanding of the knowledge of "how to encrypt the database password of the springboot project". If you want to learn more knowledge, you are welcome to follow the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.