How to stop jasypt basictextencryptor entity and start again on spring?

Viewed 205

I have an application that have some users and entries of users, entries have userId field as well. When I save an entry, I got the key of the corresponding user and want to encrypt entry text with user key then save it.

I defined jastpy basictextencyrptor as a bean:

@Configuration
public class Encyrptor {
    @Bean
    public BasicTextEncryptor basicTextEncryptor() {
        return new BasicTextEncryptor();
    }
}

And I autowired this bean to my service class. And here is my service codes:

public Entry saveEntry(Entry entry) {
        String key = userService.getUserKeyByUserId(entry.getUserId());
        entry.setText(encyptor(key, entry.getText()));
        return entryRepository.save(entry);
    }
private String encyptor(String key, String inputText) {
        basicTextEncryptor.setPassword(key);
        return basicTextEncryptor.encrypt(inputText);
    }

Whenever I want to save an entry these methods are called. But, first try is good whereas in second try I go error on line:

basicTextEncryptor.setPassword(key);

The error is:

org.jasypt.exceptions.AlreadyInitializedException: Encryption entity already initialized
    at org.jasypt.encryption.pbe.StandardPBEByteEncryptor.setPassword(StandardPBEByteEncryptor.java:298)
    at org.jasypt.encryption.pbe.StandardPBEStringEncryptor.setPassword(StandardPBEStringEncryptor.java:298)
    at org.jasypt.util.text.BasicTextEncryptor.setPassword(BasicTextEncryptor.java:79)

It says this encyrptor is already initialized, so how can I stop it after using it? Or is it better to create a new instance of BasicTextEncyrptor in the method to create different instances for every try instead of defining it as a bean ?

0 Answers
Related