8

Jasypt自定义密码加解密算法

 3 years ago
source link: https://mawenjian.net/p/1749.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Jasypt自定义密码加解密算法

2020-09-19

jasypt.png

Jasypt是什么就不用我科普了吧?Jasypt常和Spring Boot/Spring Cloud搭配,用来对应用配置文件中的密码、密钥等敏感信息进行加密存储。

言归正传,我们最近基于Spring Boot开发了一个Web应用,不过因为合规要求,某些配置信息需要使用加密机进行硬件加解密。但是Jasypt默认只支持对称加密和非对称加密两种算法,如果使用其他加解密方式,需要自己进行扩展实现。可是我在网上溜了小半天,发现网上的教程都是教你怎么把Jasypt和Spring Boot框架进行整合的,我的需求并没能找到相应的解决方案。所以我只能自己读Jasypt的源码分析了。

一、Jasypt的工作过程

通过对Jasypt的源码进行阅读,发现Jasypt的工作过程很简单。大概流程是这样子的:

1)事先通过将需要加密的参数使用加密工具得到的密文写入配置文件,并在配置文件中使用ENC()“函数”(本质就是一个标记特征字符)进行标记;

2)应用启动的时候传入解密密钥(对称加密算法的密码、非对称加密算法的私钥),然后应用在读取配置参数键值的时候,如果发现键值中含有ENC标记,就将“ENC()”中的内容抽取出来,然后调用加解密接口(org.jasypt.encryption.StringEncryptor)的实现类进行解密,从而得到明文。加密操作同理。对于我的需求,实现起来并不难,就是重写加解密接口StringEncryptor的实现类,然后把bean注册给Jasypt。

二、解决方案

1、自己实现一个StringEncryptor接口的实现类:

@Component("customStringEncryptor")
public class CustomStringEncryptor implements StringEncryptor {
private static final Logger logger = LoggerFactory.getLogger(CustomStringEncryptor.class);
@Autowired
private KeyManager keyManager;
@Override
public String encrypt(final String message) {
    final String exMsg = String.format("encrypt method is not implemented, original message: '%s'.", message);
    logger.error(exMsg);
    throw new UnsupportedOperationException(exMsg);
}
@Override
public String decrypt(final String encryptedMessage) {
    String decryptedMessage = null;
    try {
        decryptedMessage = keyManager.decrypt(encryptedMessage);
    } catch (ScmException e) {
        logger.error("decrypt failed, key: '{}'.", encryptedMessage, e);
        throw new RuntimeException(e);
    }
    return decryptedMessage;
}
}

2、在application.yml加入如下配置:

jasypt:
  encryptor:
    bean: customStringEncryptor

至此,搞定。


除非特殊说明,本博客文章均为原创,转载请以链接形式标明博文地址。

本文链接地址: Jasypt自定义密码加解密算法

分类:互联网 | 标签: JasyptSpring BootSpring Cloud |

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK