本文介绍使用jasypt.jar包辅助加密的方式,支持自定义密钥。
引入jar包加密com.github.ulisesbocchio >jasypt-spring-boot-starter2.1.0 com.github.ulisesbocchio >jasypt-spring-boot2.1.0 org.jasypt >jasypt1.9.2
- 命令行
java -cp jasypt-1.9.2.jar org.jasypt.intf.cli.JasyptPBEStringEncryptionCLI input="明文" password=自定义的密钥 algorithm=PBEWithMD5AndDES
可以指定其他加密算法,默认算法为PBEWithMD5AndDES
- 代码加密
// 默认加密/解密算法是 PBEWithMD5AndDES StandardPBEStringEncryptor encryptor = new StandardPBEStringEncryptor(); //key为自定义密钥 encryptor.setPassword(KEY); //text为明文 return encryptor.encrypt(text);
可以指定算法、hash迭代次数、salt生成方式,具体可查看源码。也可用StandardPBEByteEncryptor,不同在于一个对字符串加密,一个对字符数组加密。
解密对应的解密方式,若加密算法或参数更改,解密也需要进行更改
- 命令行
java -cp jasypt-1.9.2.jar org.jasypt.intf.cli.JasyptPBEStringDecryptionCLI input="密文" password=自定义密钥 algorithm=PBEWithMD5AndDES
- 代码
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



