SpringBoot 配置文件加密
本章将对SpringBoot配置文件中的数据加密做自定义开发. 在SpringBoot开发过程中配置文件是明文存放在application.yml或者application.properties文件中,这种配置方式会带来一定的安全隐患,本章将对这个问题提出一个简单的解决方案。
编辑切换为居中
添加图片注释,不超过 140 字(可选)
编码
首先需要确定一个加密解密方式,本文采用RSA进行加密解密,首先编写加密解密的代码,注意RSA加密解密需要使用到公钥和私钥,公钥私钥的生成代码如下:
public static void generateKey() throws NoSuchAlgorithmException { KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(EncryptionType.RSA); keyPairGen.initialize(1024, new SecureRandom()); KeyPair keyPair = keyPairGen.generateKeyPair(); RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate(); // 得到私钥 RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic(); // 得到公钥 String publicKeyString = new String(Base64.encodeBase64(publicKey.getEncoded())); String privateKeyString = new String(Base64.encodeBase64((privateKey.getEncoded()))); System.out.println("当前生成的公钥= " + publicKeyString); System.out.println("当前生成的私钥= " + privateKeyString); }
加密代码如下:
public static String encrypt(String str, String publicKey) throws NoSuchAlgorithmException, BadPaddingException, IllegalBlockSizeException, NoSuchPaddingException, InvalidKeyException, InvalidKeySpecException { byte[] decoded = Base64.decodeBase64(publicKey); RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance(EncryptionType.RSA).generatePublic(new X509EncodedKeySpec(decoded)); Cipher cipher = Cipher.getInstance(EncryptionType.RSA); cipher.init(Cipher.ENCRYPT_MODE, pubKey); return Base64.encodeBase64String(cipher.doFinal(str.getBytes(StandardCharsets.UTF_8))); }
解密代码如下: