1、导入依赖
<!-- yml加密 --> <dependency> <groupId>com.github.ulisesbocchio</groupId> <artifactId>jasypt-spring-boot-starter</artifactId> <version>2.1.0</version> </dependency>
2、编写测试类,testEncrypt是加密的方法,testDe是解密方法。
package com.allen.blog; import org.jasypt.encryption.pbe.StandardPBEStringEncryptor; import org.jasypt.encryption.pbe.config.EnvironmentPBEConfig; import org.junit.Test; /** * 加密测试类 * @author allen */ public class JasyptTest { @Test public void testEncrypt() throws Exception { StandardPBEStringEncryptor standardPBEStringEncryptor = new StandardPBEStringEncryptor(); EnvironmentPBEConfig config = new EnvironmentPBEConfig(); config.setAlgorithm("PBEWithMD5AndDES"); // 加密的算法,这个算法是默认的 config.setPassword("password"); // 加密的密钥,随便自己填写,很重要千万不要告诉别人 standardPBEStringEncryptor.setConfig(config); String plainText = "liqinglin"; //自己的密码 String encryptedText = standardPBEStringEncryptor.encrypt(plainText); System.out.println(encryptedText); } @Test public void testDe() throws Exception { StandardPBEStringEncryptor standardPBEStringEncryptor = new StandardPBEStringEncryptor(); EnvironmentPBEConfig config = new EnvironmentPBEConfig(); config.setAlgorithm("PBEWithMD5AndDES"); config.setPassword("password"); standardPBEStringEncryptor.setConfig(config); String encryptedText = "Tf/53o+iZ7J12345cTGXp9wv18YmxzPv"; //加密后的密码 String plainText = standardPBEStringEncryptor.decrypt(encryptedText); System.out.println(plainText); } }
3、在YML配置文件中加入配置
jasypt: encryptor: password: password
4、用ENC()对密码进行加密,加密的密文要放在ENC()括号中间。
url: jdbc:mysql://rm-1234567868rv8j2eeo.mysql.rds.aliyuncs.com:3306/allenblog?useUnicode=true&serverTimezone=GMT%2B8&useSSL=false username: lihaha password: ENC(Tf/12345678+rpcTGXp9wv18YmxzPv)