Jasypt:如何解密存储在Map <String,String>中的属性?

时间:2019-08-07 11:06:56

标签: spring-boot properties-file jasypt

同事,您能否使用Jasypt从属性文件中解密密码(在stmCredentials映射中的值)。

我的属性文件中有下一个字符串:

creds.users={testLogin: 'ENC(w0H***pgsj)'}
user2.login = ENC(9j3fHz5c****cLRCVvLTQmr5)
user2.pass  = ENC(w0HxpKq7V3Lf***g3zs/hpgsj)

我以调试模式运行测试:

@RunWith(SpringRunner.class)
@SpringBootTest
@ActiveProfiles("dev")
@Slf4j
public class CredentialsTest {


    @BeforeClass
    public static void beforeClass(){
        System.setProperty("jasypt.encryptor.password", "C*******L");
    }


    @Autowired
    StmCredentials stmCredentials;


    @Value("${user2.login}")
    private String user2Login;
    @Value("${user2.pass}")
    private String user2Pass;

    @Test
    public void getCredspairs() {
        HashMap<String, String> credspairs = stmCredentials.getCredspairs();
    }
}

运行后,变量中包含下一个值:

credspairs:
  key: "testLogin" 
  value:"ENC(w0HxpKq7V3LfEPsU5mbd0Vg3zs/hpgsj)" //it wasn't decrypt =(

和(注意!

user2Login = testLogin   //it was decrypt
user2Pass = K1212Zrde

我的属性文件creds.users中的属性似乎有问题。我尝试使用“单引号,双引号”,但这无济于事。

StmCredentials bean看起来像:

@Component
@EnableConfigurationProperties
public class StmCredentials {

    @Value("#{${creds.users}}")
    private HashMap<String, String> credspairs;
    public HashMap<String, String> getCredspairs() {
        return credspairs;
    }
    public void setCredspairs(HashMap<String, String> somedata) {
        this.credspairs = somedata;
    }
}

如何解密存储在StmCredentials(值)中的密码? 谢谢您的任何建议。

1 个答案:

答案 0 :(得分:1)

希望这会有所帮助:

我认为Jasypt不能以这种方式(据我所知有限)检测和解密属性文件中的值。如果可以的话,您可以尝试将其放入application.yml文件中。它应该在那里工作。无论如何,这是我们可以做的:

这实际上不是解决方案,而是可能的解决方法。如果Jasypt不会自动为我们做,我们可以创建一个类来自行解密值。

import org.jasypt.encryption.StringEncryptor;
import org.jasypt.encryption.pbe.PooledPBEStringEncryptor;
import org.jasypt.encryption.pbe.config.SimpleStringPBEConfig;

public class MyStringEncryptor {
    private StringEncryptor encryptor;

    public MyStringEncryptor(String password) {
        PooledPBEStringEncryptor encryptor = new PooledPBEStringEncryptor();
       SimpleStringPBEConfig config = new SimpleStringPBEConfig();
       config.setPassword(password);
       config.setAlgorithm("PBEWITHMD5ANDDES");
       config.setKeyObtentionIterations("1000");
       config.setPoolSize("1");
       config.setProviderName("SunJCE");
       config.setSaltGeneratorClassName("org.jasypt.salt.RandomSaltGenerator");
       config.setStringOutputType("base64");
       encryptor.setConfig(config);
       this.encryptor = encryptor;
    }

    public String encrypt(String message) {
        return encryptor.encrypt(message);
    }

    public String decrypt(String message) {
        return encryptor.decrypt(message);
    }
}

现在,我们可以创建MyStringEncryptor类的对象,并使用方法decrypt来解密所需的值。

MyStringEncryptor encryptor = new MyStringEncryptor("mysecretpass"); // You can pass the password from properties file using @Value

String decryptedValue = encryptor.decerypt(encrypted-message);