Java项目 yaml明文密码加密

本文介绍使用jasypt.jar包辅助加密的方式,支持自定义密钥。

引入jar包

  		<dependency>
            <groupId>com.github.ulisesbocchio</groupId>
            <artifactId>jasypt-spring-boot-starter</artifactId>
            <version>2.1.0</version>
        </dependency>
        <dependency>
            <groupId>com.github.ulisesbocchio</groupId>
            <artifactId>jasypt-spring-boot</artifactId>
            <version>2.1.0</version>
        </dependency>
        <dependency>
            <groupId>org.jasypt</groupId>
            <artifactId>jasypt</artifactId>
            <version>1.9.2</version>
        </dependency>

加密

  1. 命令行
java -cp jasypt-1.9.2.jar org.jasypt.intf.cli.JasyptPBEStringEncryptionCLI input="明文" password=自定义的密钥 algorithm=PBEWithMD5AndDES

可以指定其他加密算法,默认算法为PBEWithMD5AndDES

  1. 代码加密
// 默认加密/解密算法是 PBEWithMD5AndDES
StandardPBEStringEncryptor encryptor = new StandardPBEStringEncryptor();
//key为自定义密钥
encryptor.setPassword(KEY);
//text为明文
return encryptor.encrypt(text);

可以指定算法、hash迭代次数、salt生成方式,具体可查看源码。也可用StandardPBEByteEncryptor,不同在于一个对字符串加密,一个对字符数组加密。

解密

对应的解密方式,若加密算法或参数更改,解密也需要进行更改

  1. 命令行
java -cp jasypt-1.9.2.jar org.jasypt.intf.cli.JasyptPBEStringDecryptionCLI input="密文" password=自定义密钥 algorithm=PBEWithMD5AndDES
  1. 代码
StandardPBEStringEncryptor encryptor = new StandardPBEStringEncryptor();
//key为自定义密钥
encryptor.setPassword(KEY);
//ciphertext为密文
return encryptor.decrypt(ciphertext);

使用

在yaml等文件中需在将原明文替换为“ENC(密文)”,例如:

NoneBashCSSCC#GoHTMLJavaJavaScriptJSONPHPPowershellPythonRubySQLTypeScriptYAMLCopy

password: ENC(+IU9dCy7NtbVKpyOpvga0nvt33xmgTSA) 

同时需要在yaml文件中注明自定义秘钥及使用算法,用于服务自动解密

jasypt:
  encryptor:
    password: 自定义密钥
    algorithm: PBEWithMD5AndDES
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值