Java Code Examples for org.jasypt.encryption.StringEncryptor

The following examples show how to use org.jasypt.encryption.StringEncryptor. These examples are extracted from open source projects. 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 Project: jasypt   Source File: EncryptableProperties.java    License: 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 2
Source Project: spring-boot-vue-admin   Source File: JasyptConfig.java    License: 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 3
Source Project: jasypt-spring-boot   Source File: AbstractJasyptMojo.java    License: 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 4
Source Project: cougar   Source File: PropertyConfigurer.java    License: 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 5
Source Project: jasypt   Source File: TestSpringConfiguration.java    License: 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 6
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 7
Source Project: jasypt   Source File: PropertyValueEncryptionUtils.java    License: 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 8
Source Project: jasypt   Source File: TestSpringConfiguration.java    License: 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
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 Project: pig   Source File: PigAdminApplicationTest.java    License: 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 11
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 12
Source Project: jasypt-spring-boot   Source File: AbstractReencryptMojo.java    License: 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 13
Source Project: jasypt-spring-boot   Source File: EncryptionService.java    License: 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 Project: jasypt-spring-boot   Source File: DefaultLazyEncryptor.java    License: 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 15
Source Project: jasypt-spring-boot   Source File: EnvironmentInitializer.java    License: 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 16
Source Project: jasypt-spring-boot   Source File: EnvironmentInitializer.java    License: 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 17
@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 18
@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 19
Source Project: jasypt-spring-boot   Source File: StringEncryptorBuilder.java    License: 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 20
Source Project: jasypt-spring-boot   Source File: StringEncryptorBuilder.java    License: 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 21
Source Project: jasypt-spring-boot   Source File: StringEncryptorBuilder.java    License: 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 22
Source Project: jasypt-spring-boot   Source File: DefaultPropertyResolver.java    License: 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 23
Source Project: jasypt-spring-boot   Source File: DefaultLazyPropertyResolver.java    License: 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 24
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 25
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 26
Source Project: tutorials   Source File: Main.java    License: 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 27
Source Project: jasypt   Source File: TestSpringConfiguration.java    License: Apache License 2.0 4 votes vote down vote up
public void testNamespace() throws Exception {
    
    StandardPBEByteEncryptor standardPBEByteEncryptor = 
           new StandardPBEByteEncryptor();
    standardPBEByteEncryptor.setPassword("jasypt");
    standardPBEByteEncryptor.setAlgorithm("PBEWithMD5AndDES");
       
    ByteEncryptor byteEncryptor = 
           (ByteEncryptor) ctx.getBean(BYTE_ENCRYPTOR_BEAN_NAME);
       assertTrue(ArrayUtils.isEquals(new byte[] {5, 7, 13}, 
               standardPBEByteEncryptor.decrypt(byteEncryptor.encrypt(new byte[] {5, 7, 13}))));
       
       
       
       
    StandardPBEStringEncryptor standardPBEStringEncryptor = 
           new StandardPBEStringEncryptor();
       standardPBEStringEncryptor.setPassword("jasypt");
       standardPBEStringEncryptor.setAlgorithm("PBEWithMD5AndDES");
       standardPBEStringEncryptor.setStringOutputType("hexadecimal");
       
    StringEncryptor stringEncryptor = 
           (StringEncryptor) ctx.getBean(STRING_ENCRYPTOR_BEAN_NAME);
       assertEquals("jasypt", 
               standardPBEStringEncryptor.decrypt(stringEncryptor.encrypt("jasypt")));
       
    
       
       StandardStringDigester standardStringDigester = 
           new StandardStringDigester();
       standardStringDigester.setAlgorithm("SHA-1");
       standardStringDigester.setStringOutputType("hexa");
       
       StringDigester stringDigester = 
           (StringDigester) ctx.getBean(STRING_DIGESTER_BEAN_NAME);
       assertTrue(stringDigester.matches("jasypt", 
               standardStringDigester.digest("jasypt")));
       assertTrue(standardStringDigester.matches("jasypt", 
               stringDigester.digest("jasypt")));
       
}
 
Example 28
public EncryptablePropertiesPropertySource(final String name, final Properties props, final StringEncryptor encryptor) {
    super(name, processProperties(props, encryptor));
}
 
Example 29
Source Project: jasypt   Source File: PropertyValueEncryptionUtils.java    License: Apache License 2.0 4 votes vote down vote up
public static String decrypt(
        final String encodedValue, final StringEncryptor encryptor) {
    return encryptor.decrypt(getInnerEncryptedValue(encodedValue.trim()));
}
 
Example 30
StringEncryptor getStringEncryptor(final EncryptableProperties prop) {
    return (StringEncryptor) this.stringEncryptors.get(prop.getIdent());
}