当前位置:   article > 正文

springboot2+redis集群 redis密码加解密_springboot2.4+redis6配置用户密码

springboot2.4+redis6配置用户密码

创作背景

springboot2 集成redis集群网上的例子已经很多了,但涉及到密码几乎都是明文,这在实际生产环境中,是不允许的,特写此文章。

源码片段

第一步:pom.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  5. <modelVersion>4.0.0</modelVersion>
  6. <parent>
  7. <groupId>org.springframework.boot</groupId>
  8. <artifactId>spring-boot-starter-parent</artifactId>
  9. <version>2.3.3.RELEASE</version>
  10. </parent>
  11. <groupId>com.wu</groupId>
  12. <artifactId>springbootKafka</artifactId>
  13. <version>0.0.1</version>
  14. <name>springbootKafka</name>
  15. <properties>
  16. <java.version>1.8</java.version>
  17. </properties>
  18. <dependencies>
  19. <dependency>
  20. <groupId>org.springframework.boot</groupId>
  21. <artifactId>spring-boot-starter</artifactId>
  22. </dependency>
  23. <dependency>
  24. <groupId>org.springframework.boot</groupId>
  25. <artifactId>spring-boot-starter-aop</artifactId>
  26. </dependency>
  27. <dependency>
  28. <groupId>org.springframework.boot</groupId>
  29. <artifactId>spring-boot-starter-data-redis</artifactId>
  30. </dependency>
  31. <dependency>
  32. <groupId>redis.clients</groupId>
  33. <artifactId>jedis</artifactId>
  34. </dependency>
  35. <dependency>
  36. <groupId>org.projectlombok</groupId>
  37. <artifactId>lombok</artifactId>
  38. </dependency>
  39. <dependency>
  40. <groupId>org.springframework.boot</groupId>
  41. <artifactId>spring-boot-starter-test</artifactId>
  42. <scope>test</scope>
  43. </dependency>
  44. <dependency>
  45. <groupId>cn.hutool</groupId>
  46. <artifactId>hutool-all</artifactId>
  47. <version>5.6.7</version>
  48. </dependency>
  49. <dependency>
  50. <groupId>org.springframework.kafka</groupId>
  51. <artifactId>spring-kafka-test</artifactId>
  52. <scope>test</scope>
  53. </dependency>
  54. </dependencies>
  55. <build>
  56. <plugins>
  57. <plugin>
  58. <groupId>org.springframework.boot</groupId>
  59. <artifactId>spring-boot-maven-plugin</artifactId>
  60. <version>2.3.3.RELEASE</version>
  61. </plugin>
  62. </plugins>
  63. </build>
  64. </project>

第二步:配置 application.yml

  1. spring:
  2. main:
  3. web-application-type: none #去除web,以纯java的模式启动springboot
  4. redis:
  5. cluster:
  6. nodes: 192.168.1.101:8001,192.168.1.101:8002,192.168.1.102:8001,192.168.1.102:8002,192.168.1.103:8001,192.168.1.103:8002
  7. max-redirects: 3 # 获取失败 最大重定向次数
  8. pool:
  9. max-active: 1000 # 连接池最大连接数(使用负值表示没有限制)
  10. max-idle: 10 # 连接池中的最大空闲连接
  11. max-wait: -1 # 连接池最大阻塞等待时间(使用负值表示没有限制)
  12. min-idle: 5 # 连接池中的最小空闲连接
  13. timeout: 6000 # 连接超时时长(毫秒)
  14. password: FC7EF9622A3D2B62 #redis加密密码
  15. logging:
  16. level:
  17. root: info

以上重点是这一句:

password: FC7EF9622A3D2B62

redis密码不是明文的,而是通过des加密过的。

DesUtils.java
  1. package com.wu.kafka.util;
  2. import javax.crypto.Cipher;
  3. import javax.crypto.SecretKey;
  4. import javax.crypto.SecretKeyFactory;
  5. import javax.crypto.spec.DESKeySpec;
  6. import java.security.SecureRandom;
  7. public final class DesUtils {
  8. private static final String DES = "DES";
  9. private static final String KEY = "comwukafka"; //默认密钥
  10. private DesUtils() {}
  11. private static byte[] encrypt(byte[] src, byte[] key) throws Exception {
  12. SecureRandom sr = new SecureRandom();
  13. DESKeySpec dks = new DESKeySpec(key);
  14. SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
  15. SecretKey secretKey = keyFactory.generateSecret(dks);
  16. Cipher cipher = Cipher.getInstance(DES);
  17. cipher.init(Cipher.ENCRYPT_MODE, secretKey, sr);
  18. return cipher.doFinal(src);
  19. }
  20. private static byte[] decrypt(byte[] src, byte[] key) throws Exception {
  21. SecureRandom sr = new SecureRandom();
  22. DESKeySpec dks = new DESKeySpec(key);
  23. SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
  24. SecretKey secretKey = keyFactory.generateSecret(dks);
  25. Cipher cipher = Cipher.getInstance(DES);
  26. cipher.init(Cipher.DECRYPT_MODE, secretKey, sr);
  27. return cipher.doFinal(src);
  28. }
  29. private static String byte2hex(byte[] b) {
  30. String hs = "";
  31. String temp = "";
  32. for (int n = 0; n < b.length; n++) {
  33. temp = (java.lang.Integer.toHexString(b[n] & 0XFF));
  34. if (temp.length() == 1)
  35. hs = hs + "0" + temp;
  36. else
  37. hs = hs + temp;
  38. }
  39. return hs.toUpperCase();
  40. }
  41. private static byte[] hex2byte(byte[] b) {
  42. if ((b.length % 2) != 0)
  43. throw new IllegalArgumentException("length not even");
  44. byte[] b2 = new byte[b.length / 2];
  45. for (int n = 0; n < b.length; n += 2) {
  46. String item = new String(b, n, 2);
  47. b2[n / 2] = (byte) Integer.parseInt(item, 16);
  48. }
  49. return b2;
  50. }
  51. public static String decode(String src, String key) {
  52. String decryptStr = "";
  53. try {
  54. byte[] decrypt = decrypt(hex2byte(src.getBytes()), key.getBytes());
  55. decryptStr = new String(decrypt);
  56. } catch (Exception e) {
  57. e.printStackTrace();
  58. }
  59. return decryptStr;
  60. }
  61. public static String encode(String src, String key){
  62. byte[] bytes = null;
  63. String encryptStr = "";
  64. try {
  65. bytes = encrypt(src.getBytes(), key.getBytes());
  66. } catch (Exception ex) {
  67. ex.printStackTrace();
  68. }
  69. if (bytes != null)
  70. encryptStr = byte2hex(bytes);
  71. return encryptStr;
  72. }
  73. /**
  74. * 解密
  75. */
  76. public static String decode(String src) {
  77. return decode(src, KEY);
  78. }
  79. /**
  80. * 加密
  81. */
  82. public static String encode(String src) {
  83. return encode(src, KEY);
  84. }
  85. }

第三步:自定义 RedisConnectionFactory,不采用默认逻辑

  1. package com.wu.kafka.config;
  2. import com.wu.kafka.util.DesUtils;
  3. import org.springframework.beans.factory.annotation.Autowired;
  4. import org.springframework.beans.factory.annotation.Qualifier;
  5. import org.springframework.context.annotation.Bean;
  6. import org.springframework.context.annotation.Configuration;
  7. import org.springframework.core.env.Environment;
  8. import org.springframework.core.env.MapPropertySource;
  9. import org.springframework.data.redis.connection.RedisClusterConfiguration;
  10. import org.springframework.data.redis.connection.RedisConnectionFactory;
  11. import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
  12. import org.springframework.data.redis.core.RedisTemplate;
  13. import org.springframework.data.redis.core.StringRedisTemplate;
  14. import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
  15. import org.springframework.data.redis.serializer.StringRedisSerializer;
  16. import javax.annotation.Resource;
  17. import java.io.Serializable;
  18. import java.util.HashMap;
  19. import java.util.Map;
  20. @Configuration
  21. public class RedisConfig {
  22. private final Environment environment;
  23. public RedisConfig(Environment environment) {
  24. this.environment = environment;
  25. }
  26. @Bean(name = "myredisConnectionFactory")
  27. public RedisConnectionFactory myLettuceConnectionFactory() {
  28. Map<String, Object> source = new HashMap<String, Object>();
  29. source.put("spring.redis.cluster.nodes", environment.getProperty("spring.redis.cluster.nodes"));
  30. source.put("spring.redis.cluster.timeout", environment.getProperty("spring.redis.cluster.timeout"));
  31. source.put("spring.redis.cluster.max-redirects", environment.getProperty("spring.redis.cluster.max-redirects"));
  32. MapPropertySource mapPropertySource = new MapPropertySource("RedisClusterConfiguration", source);
  33. RedisClusterConfiguration redisClusterConfiguration = new RedisClusterConfiguration(mapPropertySource);
  34. //获取application.yml 中的密码(密文)
  35. String password = environment.getProperty("spring.redis.password");
  36. //解密密码并停驾到配置中
  37. redisClusterConfiguration.setPassword(DesUtils.decode(password));
  38. return new LettuceConnectionFactory(redisClusterConfiguration);
  39. }
  40. @Bean
  41. public RedisTemplate<String, Serializable> redisTemplate(@Qualifier("myredisConnectionFactory") RedisConnectionFactory factory) {
  42. RedisTemplate<String, Serializable> template = new RedisTemplate<>();
  43. template.setKeySerializer(new StringRedisSerializer());
  44. template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
  45. template.setConnectionFactory(factory);
  46. return template;
  47. }
  48. @Bean
  49. public StringRedisTemplate createStringRedisTemplate(@Qualifier("myredisConnectionFactory") RedisConnectionFactory factory){
  50. StringRedisTemplate stringRedisTemplate = new StringRedisTemplate(factory);
  51. stringRedisTemplate.setKeySerializer(new StringRedisSerializer());
  52. stringRedisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
  53. return stringRedisTemplate;
  54. }
  55. }

第四步 使用

  1. @Autowired
  2. private RedisTemplate redisTemplate;
  3. @Autowired
  4. private StringRedisTemplate stringRedisTemplate;
  5. public void test(){
  6. stringRedisTemplate.boundValueOps("name").set("wuchao", 500, TimeUnit.SECONDS);
  7. String name = stringRedisTemplate.boundValueOps("name").get();
  8. System.out.println(name);
  9. }
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小蓝xlanll/article/detail/152214
推荐阅读
相关标签