org.jasypt.encryption.StringEncryptor Java Examples

The following examples show how to use org.jasypt.encryption.StringEncryptor. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: HistoryServiceImpl.java    From JuniperBot with GNU General Public License v3.0 6 votes vote down vote up
private StringEncryptor getEncryptor(TextChannel channel, String iv) {
    StandardPBEStringEncryptor encryptor = new StandardPBEStringEncryptor();
    encryptor.setAlgorithm("PBEWithHMACSHA512AndAES_256");
    encryptor.setPassword(String.format("%s:%s", channel.getGuild().getId(), channel.getId()));
    encryptor.setIvGenerator(new StringFixedIvGenerator(iv));
    return encryptor;
}
 
Example #2
Source File: PropertyConfigurer.java    From cougar with Apache License 2.0 6 votes vote down vote up
protected PropertyConfigurer(StringEncryptor encryptor) {
	this.propertyPlaceholderConfigurer = encryptor != null ? new EncryptablePropertyPlaceholderConfigurer(encryptor) : new PropertyPlaceholderConfigurer();

	// Ensure that system properties override the spring-set properties.
	propertyPlaceholderConfigurer.setSystemPropertiesMode(PropertyPlaceholderConfigurer.SYSTEM_PROPERTIES_MODE_OVERRIDE);

	PropertiesPersister savingPropertiesPersister = new DefaultPropertiesPersister() {

           @Override
           public void load(Properties props, InputStream is) throws IOException {
               props.put(HOSTNAME_KEY, HOSTNAME);
               CougarNodeId.initialiseNodeId(props);
               super.load(props, is);
               for (String propName: props.stringPropertyNames()) {
                   allLoadedProperties.put(propName, System.getProperty(propName, props.getProperty(propName)));
               }
           }};
       propertyPlaceholderConfigurer.setPropertiesPersister(savingPropertiesPersister);
}
 
Example #3
Source File: JasyptConfig.java    From spring-boot-vue-admin with Apache License 2.0 6 votes vote down vote up
@Bean
public StringEncryptor myStringEncryptor() throws Exception {
  // Base64 + RSA 加密的密码
  final byte[] passwordEncryptedByRSA =
      Base64Utils.decodeFromString(this.passwordEncryptedByBase64AndRSA);
  final String password = new String(this.rsaUtils.decrypt(passwordEncryptedByRSA));
  // 配置
  final SimpleStringPBEConfig config =
      new SimpleStringPBEConfig() {
        {
          this.setPassword(password);
          // 加密算法
          this.setAlgorithm("PBEWithMD5AndDES");
          this.setKeyObtentionIterations("1000");
          this.setPoolSize("1");
          this.setProviderName("SunJCE");
          this.setSaltGeneratorClassName("org.jasypt.salt.RandomSaltGenerator");
          this.setStringOutputType("base64");
        }
      };
  final PooledPBEStringEncryptor encryptor = new PooledPBEStringEncryptor();
  encryptor.setConfig(config);
  return encryptor;
}
 
Example #4
Source File: AbstractJasyptMojo.java    From jasypt-spring-boot with MIT License 6 votes vote down vote up
@Override
public void execute() throws MojoExecutionException {
    Map<String, Object> defaultProperties = new HashMap<>();
    defaultProperties.put("spring.config.location", "file:./src/main/resources/");

    ConfigurableApplicationContext context = new SpringApplicationBuilder()
            .sources(Application.class)
            .bannerMode(Banner.Mode.OFF)
            .properties(defaultProperties)
            .run();

    this.environment = context.getEnvironment();

    String[] activeProfiles = context.getEnvironment().getActiveProfiles();
    String profiles = activeProfiles.length != 0 ? String.join(",", activeProfiles) : "Default";
    log.info("Active Profiles: {}", profiles);
    StringEncryptor encryptor = context.getBean(StringEncryptor.class);
    run(new EncryptionService(encryptor), context, encryptPrefix, encryptSuffix, decryptPrefix, decryptSuffix);
}
 
Example #5
Source File: EncryptableProperties.java    From jasypt with Apache License 2.0 6 votes vote down vote up
private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException {
    
    in.defaultReadObject();
    
    final EncryptablePropertiesEncryptorRegistry registry =
            EncryptablePropertiesEncryptorRegistry.getInstance();
    
    final StringEncryptor registeredStringEncryptor = registry.getStringEncryptor(this);
    if (registeredStringEncryptor != null) {
        this.stringEncryptor = registeredStringEncryptor;
        return;
    }
    
    final TextEncryptor registeredTextEncryptor = registry.getTextEncryptor(this);
    if (registeredTextEncryptor != null) {
        this.textEncryptor = registeredTextEncryptor;
    }
    
}
 
Example #6
Source File: EncryptablePropertyResolverConfiguration.java    From jasypt-spring-boot with MIT License 5 votes vote down vote up
@Bean(name = ENCRYPTOR_BEAN_NAME)
public StringEncryptor stringEncryptor(
        final EnvCopy envCopy,
        final BeanFactory bf) {
    final String customEncryptorBeanName = envCopy.get().resolveRequiredPlaceholders(ENCRYPTOR_BEAN_PLACEHOLDER);
    final boolean isCustom = envCopy.get().containsProperty(ENCRYPTOR_BEAN_PROPERTY);
    return new DefaultLazyEncryptor(envCopy.get(), customEncryptorBeanName, isCustom, bf);
}
 
Example #7
Source File: PigAdminApplicationTest.java    From pig with MIT License 5 votes vote down vote up
/**
 * jasypt.encryptor.password 对应 配置中心 application-dev.yml 中的密码
 */
@Test
public void testEnvironmentProperties() {
    System.setProperty(JASYPT_ENCRYPTOR_PASSWORD, "lengleng");
    StringEncryptor stringEncryptor = new DefaultLazyEncryptor(new StandardEnvironment());

    //加密方法
    System.out.println(stringEncryptor.encrypt("123456"));
    //解密方法
    System.out.println(stringEncryptor.decrypt("saRv7ZnXsNAfsl3AL9OpCQ=="));
}
 
Example #8
Source File: TestSpringConfiguration.java    From jasypt with Apache License 2.0 5 votes vote down vote up
public void testEncryptedProperties() throws Exception {
	    
    ConfigurationProperties configurationProperties = 
        (ConfigurationProperties) ctx.getBean(CONFIGURATION_PROPERTIES_BEAN_NAME);
    StringEncryptor stringEncryptor = 
           (StringEncryptor) ctx.getBean(CONFIGURATION_ENCRYPTOR_BEAN_NAME);
    	    
    assertEquals(configurationProperties.getLocation(), 
            configurationProperties.getLocatinPlainValue());
   
    assertEquals(stringEncryptor.decrypt(configurationProperties.getLocationEncryptedValue()),
            configurationProperties.getLocation());
      
}
 
Example #9
Source File: EncryptablePropertiesPropertySource.java    From jasypt with Apache License 2.0 5 votes vote down vote up
private static Properties processProperties(final Properties props, final StringEncryptor encryptor) {
    if (props == null) {
        return null;
    }
    if (props instanceof EncryptableProperties) {
        throw new IllegalArgumentException(
                "Properties object already is an " + EncryptableProperties.class.getName() + 
                " object. No encryptor should be specified.");
    }
    final EncryptableProperties encryptableProperties = new EncryptableProperties(encryptor);
    encryptableProperties.putAll(props);
    return encryptableProperties;
}
 
Example #10
Source File: DefaultLazyEncryptor.java    From jasypt-spring-boot with MIT License 5 votes vote down vote up
public DefaultLazyEncryptor(final ConfigurableEnvironment e, final String customEncryptorBeanName, boolean isCustom, final BeanFactory bf) {
    singleton = new Singleton<>(() ->
            Optional.of(customEncryptorBeanName)
                    .filter(bf::containsBean)
                    .map(name -> (StringEncryptor) bf.getBean(name))
                    .map(tap(bean -> log.info("Found Custom Encryptor Bean {} with name: {}", bean, customEncryptorBeanName)))
                    .orElseGet(() -> {
                        if (isCustom) {
                            throw new IllegalStateException(String.format("String Encryptor custom Bean not found with name '%s'", customEncryptorBeanName));
                        }
                        log.info("String Encryptor custom Bean not found with name '{}'. Initializing Default String Encryptor", customEncryptorBeanName);
                        return createDefault(e);
                    }));
}
 
Example #11
Source File: PropertyDecrypter.java    From scheduling with GNU Affero General Public License v3.0 5 votes vote down vote up
public static String decryptData(String data) {
    StringEncryptor encryptor = getDefaultEncryptor();
    if ((encryptor != null) && (data != null) && data.startsWith(ENCRYPTION_PREFIX)) {
        return encryptor.decrypt(data.substring(ENCRYPTION_PREFIX.length(),
                                                data.length() - ENCRYPTION_SUFFIX.length()));
    }
    return data;
}
 
Example #12
Source File: PropertyDecrypter.java    From scheduling with GNU Affero General Public License v3.0 5 votes vote down vote up
public static String encryptData(String data) {
    StringEncryptor encryptor = getDefaultEncryptor();
    if (encryptor == null || data == null || data.isEmpty() || data.startsWith(ENCRYPTION_PREFIX)) {
        return data;
    } else {
        return ENCRYPTION_PREFIX + encryptor.encrypt(data) + ENCRYPTION_SUFFIX;
    }
}
 
Example #13
Source File: EncryptionService.java    From jasypt-spring-boot with MIT License 5 votes vote down vote up
@SuppressWarnings("ReplaceAllDot")
public EncryptionService(final StringEncryptor encryptor) {
    this.encryptor = encryptor;
    String regExSpecialChars = "<([{\\^-=$!|]})?*+.>";
    String regExSpecialCharsRE = regExSpecialChars.replaceAll(".", "\\\\$0");
    this.reCharsREP = Pattern.compile("[" + regExSpecialCharsRE + "]");
}
 
Example #14
Source File: Main.java    From tutorials with MIT License 5 votes vote down vote up
@Bean(name = "encryptorBean")
public StringEncryptor stringEncryptor() {
    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);
    return encryptor;
}
 
Example #15
Source File: AbstractReencryptMojo.java    From jasypt-spring-boot with MIT License 5 votes vote down vote up
private EncryptionService getOldEncryptionService() {
    JasyptEncryptorConfigurationProperties properties = new JasyptEncryptorConfigurationProperties();

    configure(properties);

    StringEncryptor encryptor = new StringEncryptorBuilder(properties, "jasypt.plugin.old").build();
    return new EncryptionService(encryptor);
}
 
Example #16
Source File: DefaultLazyPropertyResolver.java    From jasypt-spring-boot with MIT License 5 votes vote down vote up
public DefaultLazyPropertyResolver(EncryptablePropertyDetector propertyDetector, StringEncryptor encryptor, String customResolverBeanName, boolean isCustom, BeanFactory bf, Environment environment) {
    singleton = new Singleton<>(() ->
            Optional.of(customResolverBeanName)
                    .filter(bf::containsBean)
                    .map(name -> (EncryptablePropertyResolver) bf.getBean(name))
                    .map(tap(bean -> log.info("Found Custom Resolver Bean {} with name: {}", bean, customResolverBeanName)))
                    .orElseGet(() -> {
                        if (isCustom) {
                            throw new IllegalStateException(String.format("Property Resolver custom Bean not found with name '%s'", customResolverBeanName));
                        }
                        log.info("Property Resolver custom Bean not found with name '{}'. Initializing Default Property Resolver", customResolverBeanName);
                        return createDefault(propertyDetector, encryptor, environment);
                    }));
}
 
Example #17
Source File: PropertyValueEncryptionUtils.java    From jasypt with Apache License 2.0 5 votes vote down vote up
public static String encrypt(
        final String decodedValue, final StringEncryptor encryptor) {
    return 
        ENCRYPTED_VALUE_PREFIX + 
        encryptor.encrypt(decodedValue) +
        ENCRYPTED_VALUE_SUFFIX;
}
 
Example #18
Source File: EnvironmentInitializer.java    From jasypt-spring-boot with MIT License 5 votes vote down vote up
public EnvironmentInitializer(ConfigurableEnvironment environment, InterceptionMode interceptionMode, List<Class<PropertySource<?>>> skipPropertySourceClasses, EncryptablePropertyResolver resolver, EncryptablePropertyFilter filter, StringEncryptor encryptor, EncryptablePropertyDetector detector) {

        this.environment = environment;
        this.interceptionMode = interceptionMode;
        this.skipPropertySourceClasses = skipPropertySourceClasses;
        this.resolver = resolver;
        this.filter = filter;
        this.encryptor = encryptor;
        this.detector = detector;
    }
 
Example #19
Source File: TestSpringConfiguration.java    From jasypt with Apache License 2.0 5 votes vote down vote up
public void testEncryptedProperties() throws Exception {
	    
    ConfigurationProperties configurationProperties = 
        (ConfigurationProperties) ctx.getBean(CONFIGURATION_PROPERTIES_BEAN_NAME);
    StringEncryptor stringEncryptor = 
           (StringEncryptor) ctx.getBean(CONFIGURATION_ENCRYPTOR_BEAN_NAME);
    	    
    assertEquals(configurationProperties.getLocation(), 
            configurationProperties.getLocatinPlainValue());
   
    assertEquals(stringEncryptor.decrypt(configurationProperties.getLocationEncryptedValue()),
            configurationProperties.getLocation());
      
}
 
Example #20
Source File: DefaultPropertyResolver.java    From jasypt-spring-boot with MIT License 5 votes vote down vote up
public DefaultPropertyResolver(StringEncryptor encryptor, EncryptablePropertyDetector detector, Environment environment) {
    this.environment = environment;
    Assert.notNull(encryptor, "String encryptor can't be null");
    Assert.notNull(detector, "Encryptable Property detector can't be null");
    this.encryptor = encryptor;
    this.detector = detector;
}
 
Example #21
Source File: EnvironmentInitializer.java    From jasypt-spring-boot with MIT License 5 votes vote down vote up
MutablePropertySources initialize(MutablePropertySources originalPropertySources) {
    InterceptionMode actualInterceptionMode = Optional.ofNullable(interceptionMode).orElse(InterceptionMode.WRAPPER);
    List<Class<PropertySource<?>>> actualSkipPropertySourceClasses = Optional.ofNullable(skipPropertySourceClasses).orElseGet(Collections::emptyList);
    EnvCopy envCopy = new EnvCopy(environment);
    EncryptablePropertyFilter actualFilter = Optional.ofNullable(filter).orElseGet(() -> new DefaultLazyPropertyFilter(envCopy.get()));
    StringEncryptor actualEncryptor = Optional.ofNullable(encryptor).orElseGet(() -> new DefaultLazyEncryptor(envCopy.get()));
    EncryptablePropertyDetector actualDetector = Optional.ofNullable(detector).orElseGet(() -> new DefaultLazyPropertyDetector(envCopy.get()));
    EncryptablePropertyResolver actualResolver = Optional.ofNullable(resolver).orElseGet(() -> new DefaultLazyPropertyResolver(actualDetector, actualEncryptor, environment));
    EncryptablePropertySourceConverter converter = new EncryptablePropertySourceConverter(actualInterceptionMode, actualSkipPropertySourceClasses, actualResolver, actualFilter);
    converter.convertPropertySources(originalPropertySources);
    return converter.proxyPropertySources(originalPropertySources, envCopy);
}
 
Example #22
Source File: StringEncryptorBuilder.java    From jasypt-spring-boot with MIT License 5 votes vote down vote up
private StringEncryptor createPBEDefault() {
    PooledPBEStringEncryptor encryptor = new PooledPBEStringEncryptor();
    SimpleStringPBEConfig config = new SimpleStringPBEConfig();
    config.setPassword(getRequired(configProps::getPassword, propertyPrefix + ".password"));
    config.setAlgorithm(get(configProps::getAlgorithm, propertyPrefix + ".algorithm", "PBEWITHHMACSHA512ANDAES_256"));
    config.setKeyObtentionIterations(get(configProps::getKeyObtentionIterations, propertyPrefix + ".key-obtention-iterations", "1000"));
    config.setPoolSize(get(configProps::getPoolSize, propertyPrefix + ".pool-size", "1"));
    config.setProviderName(get(configProps::getProviderName, propertyPrefix + ".provider-name", null));
    config.setProviderClassName(get(configProps::getProviderClassName, propertyPrefix + ".provider-class-name", null));
    config.setSaltGeneratorClassName(get(configProps::getSaltGeneratorClassname, propertyPrefix + ".salt-generator-classname", "org.jasypt.salt.RandomSaltGenerator"));
    config.setIvGeneratorClassName(get(configProps::getIvGeneratorClassname, propertyPrefix + ".iv-generator-classname", "org.jasypt.iv.RandomIvGenerator"));
    config.setStringOutputType(get(configProps::getStringOutputType, propertyPrefix + ".string-output-type", "base64"));
    encryptor.setConfig(config);
    return encryptor;
}
 
Example #23
Source File: StringEncryptorBuilder.java    From jasypt-spring-boot with MIT License 5 votes vote down vote up
private StringEncryptor createAsymmetricDefault() {
    SimpleAsymmetricConfig config = new SimpleAsymmetricConfig();
    config.setPrivateKey(get(configProps::getPrivateKeyString, propertyPrefix + ".private-key-string", null));
    config.setPrivateKeyLocation(get(configProps::getPrivateKeyLocation, propertyPrefix + ".private-key-location", null));
    config.setPrivateKeyFormat(get(configProps::getPrivateKeyFormat, propertyPrefix + ".private-key-format", AsymmetricCryptography.KeyFormat.DER));
    config.setPublicKey(get(configProps::getPublicKeyString, propertyPrefix + ".public-key-string", null));
    config.setPublicKeyLocation(get(configProps::getPublicKeyLocation, propertyPrefix + ".public-key-location", null));
    config.setPublicKeyFormat(get(configProps::getPublicKeyFormat, propertyPrefix + ".public-key-format", AsymmetricCryptography.KeyFormat.DER));
    return new SimpleAsymmetricStringEncryptor(config);
}
 
Example #24
Source File: StringEncryptorBuilder.java    From jasypt-spring-boot with MIT License 5 votes vote down vote up
public StringEncryptor build() {
    if (isPBEConfig()) {
        return createPBEDefault();
    } else if (isAsymmetricConfig()) {
        return createAsymmetricDefault();
    } else {
        throw new IllegalStateException("either '" + propertyPrefix + ".password' or one of ['" + propertyPrefix + ".private-key-string', '" + propertyPrefix + ".private-key-location'] must be provided for Password-based or Asymmetric encryption");
    }
}
 
Example #25
Source File: EncryptablePropertyResolverConfiguration.java    From jasypt-spring-boot with MIT License 5 votes vote down vote up
@Bean(name = RESOLVER_BEAN_NAME)
public EncryptablePropertyResolver encryptablePropertyResolver(
        @Qualifier(DETECTOR_BEAN_NAME) final EncryptablePropertyDetector propertyDetector,
        @Qualifier(ENCRYPTOR_BEAN_NAME) final StringEncryptor encryptor, final BeanFactory bf,
        final EnvCopy envCopy, final ConfigurableEnvironment environment) {
    final String customResolverBeanName = envCopy.get().resolveRequiredPlaceholders(RESOLVER_BEAN_PLACEHOLDER);
    final boolean isCustom = envCopy.get().containsProperty(RESOLVER_BEAN_PROPERTY);
    return new DefaultLazyPropertyResolver(propertyDetector, encryptor, customResolverBeanName, isCustom, bf, environment);
}
 
Example #26
Source File: EncryptablePropertiesPropertySource.java    From jasypt with Apache License 2.0 5 votes vote down vote up
private static Properties processProperties(final Properties props, final StringEncryptor encryptor) {
    if (props == null) {
        return null;
    }
    if (props instanceof EncryptableProperties) {
        throw new IllegalArgumentException(
                "Properties object already is an " + EncryptableProperties.class.getName() + 
                " object. No encryptor should be specified.");
    }
    final EncryptableProperties encryptableProperties = new EncryptableProperties(encryptor);
    encryptableProperties.putAll(props);
    return encryptableProperties;
}
 
Example #27
Source File: EncryptablePropertiesPropertySource.java    From jasypt with Apache License 2.0 4 votes vote down vote up
public EncryptablePropertiesPropertySource(final String name, final Properties props, final StringEncryptor encryptor) {
    super(name, processProperties(props, encryptor));
}
 
Example #28
Source File: JasyptConfiguration.java    From seed with Apache License 2.0 4 votes vote down vote up
EnableEncryptablePropertySourcesPostProcessor(StringEncryptor encryptor){
    this.encryptor = encryptor;
}
 
Example #29
Source File: DefaultLazyEncryptor.java    From jasypt-spring-boot with MIT License 4 votes vote down vote up
private StringEncryptor createDefault(ConfigurableEnvironment e) {
    return new StringEncryptorBuilder(JasyptEncryptorConfigurationProperties.bindConfigProps(e), "jasypt.encryptor").build();
}
 
Example #30
Source File: EncryptablePropertiesEncryptorRegistry.java    From jasypt with Apache License 2.0 4 votes vote down vote up
void setStringEncryptor(final EncryptableProperties prop, final StringEncryptor encryptor) {
    this.stringEncryptors.put(prop.getIdent(), encryptor);
}