jasypt加解密

1. 添加依赖

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

2. 加密秘钥

# 配置 Jasypt 加密密钥  
jasypt:  
  encryptor:  
    password: ${ENCRYPT_KEY:GCIyW8ptQjXU80aG237QzgFiQN39PTQ}

3. 启动类添加注解

import com.ulisesbocchio.jasyptspringboot.annotation.EnableEncryptableProperties;  
import org.mybatis.spring.annotation.MapperScan;  
import org.springframework.boot.SpringApplication;  
import org.springframework.boot.autoconfigure.SpringBootApplication;

@EnableEncryptableProperties
@SpringBootApplication  
public class Application {

4. 添加配置

import org.jasypt.encryption.StringEncryptor;  
import org.jasypt.encryption.pbe.PooledPBEStringEncryptor;  
import org.jasypt.encryption.pbe.config.SimpleStringPBEConfig;  
import org.springframework.beans.factory.annotation.Value;  
import org.springframework.context.annotation.Bean;  
import org.springframework.context.annotation.Configuration;  

/**  
 * Jasypt加密配置  
 *  
 * @author admin  
 */@Configuration  
public class JasyptConfig {  
  
    @Value("${jasypt.encryptor.password}")  
    private String password;  
  
    @Bean("jasyptStringEncryptor")  
    public StringEncryptor stringEncryptor() {
        PooledPBEStringEncryptor encryptor = new PooledPBEStringEncryptor();  
        SimpleStringPBEConfig config = new SimpleStringPBEConfig();  
        // 加密密钥  
        config.setPassword(password);  
        // 加密算法  
        config.setAlgorithm("PBEWithMD5AndDES");  
        // 迭代次数  
        config.setKeyObtentionIterations("1000");  
        // 加密盐  
        config.setSaltGeneratorClassName("org.jasypt.salt.RandomSaltGenerator");  
        // 国际编码  
        config.setStringOutputType("base64");  
        // 池大小  
        config.setPoolSize("1");  
        encryptor.setConfig(config);  
        return encryptor;  
    }  
}

5. 加密

public static void main(String[] args) {  
    StandardPBEStringEncryptor encryptor = new StandardPBEStringEncryptor();  
    encryptor.setPassword("GCIyW8ptQjXU80aG237QzgFiQN39PTQ");  // 加密密钥  
    String encryptedPassword = encryptor.encrypt("Cyhlwdmdb2024");  
    System.out.println("Encrypted Password: ENC(" + encryptedPassword + ")");  
}
本文由博客一文多发平台 OpenWrite 发布!

stic9527
1 声望0 粉丝