# encryptPropertySource **Repository Path**: hell-hope/encrypt-property-source ## Basic Information - **Project Name**: encryptPropertySource - **Description**: 加密springboot配置文件 - **Primary Language**: Unknown - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2023-07-10 - **Last Updated**: 2023-08-11 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # 加密配置文件 ## 定义一个解密的接口 ```kotlin interface IEncryptPropertySourceLoader { fun decrypt(resource: Resource) : Resource { val key = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDRjQ11x4LOjpUUxamG1T0lQFPXjjQ1YImxalXl7zNSPrAjWc2cAJiq69WNf7Dh6M6/U+p7aFosDxXX76LdyCPkQp3vWUftYSZuXKph0D6WRSVNGHutTKXsGS62/1RGCXV3vhcl/GwQeqYCp3iHsD+Lu9NoDWPgFXa+JJGSPvBuLwIDAQAB" val keyFactory = KeyFactory.getInstance("RSA") val keyArray = Base64.getDecoder().decode(key) val keySpec = X509EncodedKeySpec(keyArray) val keyGenerate = keyFactory.generatePublic(keySpec) //1.创建cipher对象 val cipher = Cipher.getInstance("RSA") //2.初始化cipher cipher.init(Cipher.DECRYPT_MODE, keyGenerate) val decryptMaxSize = 128 //解密:每次最大加密长度 val byteArray = Base64.getDecoder().decode(resource.inputStream.readBytes()) var offset = 0 //当前偏移的位置 val bos = ByteArrayOutputStream() while (offset < byteArray.size) { //没加密完 //每次最大解密128个字节 var temp: ByteArray if (byteArray.size - offset >= decryptMaxSize) { temp = cipher.doFinal(byteArray, offset, decryptMaxSize) //重新计算偏移的位置 offset += decryptMaxSize } else { //加密最后一块 temp = cipher.doFinal(byteArray, offset, byteArray.size - offset) //重新计算偏移的位置 offset = byteArray.size } //存储到临时缓冲区 bos.write(temp) } bos.close() return ByteArrayResource(bos.toByteArray()) } } ``` ## 继承 PropertiesPropertySourceLoader 类重写父类的方法 ```kotlin class PropertiesEncryptPropertySourceLoader : PropertiesPropertySourceLoader(), IEncryptPropertySourceLoader { override fun getFileExtensions(): Array { return arrayOf("properties.encrypt") } @Throws(IOException::class) override fun load(name: String, resource: Resource): List?>? { return super.load(name, decrypt(resource)) } } ``` ## 继承 YamlEncryptPropertySourceLoader 类重写父类的方法 ```kotlin class YamlEncryptPropertySourceLoader : YamlPropertySourceLoader(), IEncryptPropertySourceLoader { override fun getFileExtensions(): Array { return arrayOf("yaml.encrypt", "yml.encrypt") } override fun load(name: String?, resource: Resource): MutableList> { return super.load(name, decrypt(resource)) } } ``` ## 在 resources 文件夹添加文件 META-INF/spring.factories ### 指定PropertySourceLoader类 ```text org.springframework.boot.env.PropertySourceLoader=\ PropertiesEncryptPropertySourceLoader,\ YamlEncryptPropertySourceLoader ```