Java Code Examples for org.springframework.security.crypto.encrypt.TextEncryptor

The following examples show how to use org.springframework.security.crypto.encrypt.TextEncryptor. 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: summerframework   Source File: StringEncryptorHolder.java    License: Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {

        TextEncryptor encryptor =
            Encryptors.delux("pass", new String(Hex.encode("salt".getBytes(Charset.forName("utf-8")))));
        System.out.println(encryptor.encrypt("sadfsadfasfsadf"));
        System.out.println(encryptor.encrypt("sadfsadfasfsadf"));
        System.out.println(encryptor.decrypt(encryptor.encrypt("这是密码")));
    }
 
Example 2
@Override
public void initialize(GenericApplicationContext context) {
	ConditionService conditions = context.getBeanFactory().getBean(ConditionService.class);
	if (conditions.matches(EncryptionBootstrapConfiguration.RsaEncryptionConfiguration.class)) {
		if (context.getBeanFactory().getBeanNamesForType(
				EncryptionBootstrapConfiguration.RsaEncryptionConfiguration.class).length == 0) {
			context.getBeanFactory().getBean(ImportRegistrars.class).add(
					EncryptionBootstrapConfiguration.RsaEncryptionConfiguration.class,
					"org.springframework.boot.context.properties.EnableConfigurationPropertiesRegistrar");
			context.registerBean(EncryptionBootstrapConfiguration.RsaEncryptionConfiguration.class,
					() -> new EncryptionBootstrapConfiguration.RsaEncryptionConfiguration());
			if (conditions.matches(EncryptionBootstrapConfiguration.RsaEncryptionConfiguration.class,
					TextEncryptor.class)) {
				context.registerBean("textEncryptor", TextEncryptor.class,
						() -> context.getBean(EncryptionBootstrapConfiguration.RsaEncryptionConfiguration.class)
								.textEncryptor());
			}
		}
	}
}
 
Example 3
Source Project: syndesis   Source File: EncryptionComponent.java    License: Apache License 2.0 6 votes vote down vote up
public String decrypt(final String value) {
    // value might not be encrypted...
    if( value == null ) {
        return null;
    }
    String result = value;
    if( result.startsWith(ENCRYPTED_PREFIX)) {
        TextEncryptor enc = textEncryptor;
        try {
            result = enc.decrypt(stripPrefix(result, ENCRYPTED_PREFIX));
        } catch (RuntimeException e) {
            // We could fail to decrypt the value..
            throw new KException(e);
        }
    }
    return result;
}
 
Example 4
Source Project: haven-platform   Source File: KvMapperFactory.java    License: Apache License 2.0 6 votes vote down vote up
@Autowired
@SuppressWarnings("unchecked")
public KvMapperFactory(ObjectMapper objectMapper, KeyValueStorage storage, TextEncryptor encryptor, Validator validator) {
    this.objectMapper = objectMapper;
    this.storage = storage;
    this.validator = validator;

    ImmutableMap.Builder<Class<?>, FieldSetter> builder = ImmutableMap.builder();
    builder.put(Map.class, (field, value) -> {
        Map fieldMap = (Map) field;
        fieldMap.clear();
        if (value != null) {
            fieldMap.putAll((Map)value);
        }
    });
    builder.put(Collection.class, (field, value) -> {
        Collection fieldColl = (Collection) field;
        fieldColl.clear();
        fieldColl.addAll((Collection)value);
    });
    setters = builder.build();
    interceptors = ImmutableMap.<Class<?>, PropertyInterceptor>builder()
      .put(PropertyCipher.class, new PropertyCipher(encryptor))
      .build();
}
 
Example 5
@Bean
@ConditionalOnMissingBean(TextEncryptor.class)
public TextEncryptor textEncryptor() {
	KeyStore keyStore = this.key.getKeyStore();
	if (keyStore.getLocation() != null) {
		if (keyStore.getLocation().exists()) {
			return new RsaSecretEncryptor(
					new KeyStoreKeyFactory(keyStore.getLocation(),
							keyStore.getPassword().toCharArray()).getKeyPair(
									keyStore.getAlias(),
									keyStore.getSecret().toCharArray()),
					this.rsaProperties.getAlgorithm(),
					this.rsaProperties.getSalt(), this.rsaProperties.isStrong());
		}

		throw new IllegalStateException("Invalid keystore location");
	}

	return new EncryptorFactory(this.key.getSalt()).create(this.key.getKey());
}
 
Example 6
@Test
public void testOnlyDecryptIfNotOverridden() {
	ConfigurableApplicationContext context = new AnnotationConfigApplicationContext();
	TextEncryptor encryptor = mock(TextEncryptor.class);
	when(encryptor.decrypt("bar2")).thenReturn("bar2");
	EnvironmentDecryptApplicationInitializer initializer = new EnvironmentDecryptApplicationInitializer(
			encryptor);
	TestPropertyValues.of("foo: {cipher}bar", "foo2: {cipher}bar2").applyTo(context);
	context.getEnvironment().getPropertySources().addFirst(new MapPropertySource(
			"test_override", Collections.singletonMap("foo", "spam")));
	initializer.initialize(context);
	then(context.getEnvironment().getProperty("foo")).isEqualTo("spam");
	then(context.getEnvironment().getProperty("foo2")).isEqualTo("bar2");
	verify(encryptor).decrypt("bar2");
	verifyNoMoreInteractions(encryptor);
}
 
Example 7
Source Project: spring-cloud-config   Source File: EncryptionController.java    License: Apache License 2.0 6 votes vote down vote up
@RequestMapping(value = "/decrypt/{name}/{profiles}", method = RequestMethod.POST)
public String decrypt(@PathVariable String name, @PathVariable String profiles,
		@RequestBody String data, @RequestHeader("Content-Type") MediaType type) {
	TextEncryptor encryptor = getEncryptor(name, profiles, "");
	checkDecryptionPossible(encryptor);
	validateEncryptionWeakness(encryptor);
	try {
		encryptor = getEncryptor(name, profiles, data);
		String input = stripFormData(helper.stripPrefix(data), type, true);
		String decrypted = encryptor.decrypt(input);
		logger.info("Decrypted cipher data");
		return decrypted;
	}
	catch (IllegalArgumentException | IllegalStateException e) {
		logger.error("Cannot decrypt key:" + name + ", value:" + data, e);
		throw new InvalidCipherException();
	}
}
 
Example 8
@Test
public void addEnvironment() {
	TextEncryptorLocator locator = new TextEncryptorLocator() {

		private RsaSecretEncryptor encryptor = new RsaSecretEncryptor();

		@Override
		public TextEncryptor locate(Map<String, String> keys) {
			return this.encryptor;
		}
	};
	this.controller = new EncryptionController(locator);
	// Add space to input
	String cipher = this.controller.encrypt("app", "default", "foo bar",
			MediaType.TEXT_PLAIN);
	assertThat(cipher.contains("{name:app}")).as("Wrong cipher: " + cipher).isFalse();
	String decrypt = this.controller.decrypt("app", "default", cipher,
			MediaType.TEXT_PLAIN);
	assertThat(decrypt).as("Wrong decrypted plaintext: " + decrypt)
			.isEqualTo("foo bar");
}
 
Example 9
Source Project: flair-engine   Source File: CryptoResource.java    License: Apache License 2.0 5 votes vote down vote up
@PostMapping("/encrypt")
public String encrypt(@RequestBody String data) {
    final SymmetricEncryptionFactory symEncFactory = cryptoAbstractFactory.getSymEncFactory();
    final TextEncryptor textEncryptor = symEncFactory.getSymmetricTextEncryption(keyManager.getDatabaseEncryptionKey());

    return textEncryptor.encrypt(data);
}
 
Example 10
Source Project: flair-engine   Source File: AbstractCryptoConverter.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Converts the value stored in the entity attribute into the
 * data representation to be stored in the database.
 *
 * @param attribute the entity attribute value to be converted
 * @return the converted data to be stored in the database column
 */
@Override
public String convertToDatabaseColumn(T attribute) {
    autowire();
    final SymmetricEncryptionFactory symEncFactory = cryptoAbstractFactory.getSymEncFactory();
    TextEncryptor textEncryptor = symEncFactory.getSymmetricTextEncryption(keyManager.getDatabaseEncryptionKey());
    return textEncryptor.encrypt(entityAttributeToString(attribute));
}
 
Example 11
public PreJdbcConnectionRepository(String userId, JdbcTemplate jdbcTemplate, ConnectionFactoryLocator connectionFactoryLocator, TextEncryptor textEncryptor, String tablePrefix) {
    this.userId = userId;
    this.jdbcTemplate = jdbcTemplate;
    this.connectionFactoryLocator = connectionFactoryLocator;
    this.textEncryptor = textEncryptor;
    this.tablePrefix = tablePrefix;
}
 
Example 12
Source Project: blog   Source File: AbstractConverter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public String convertToDatabaseColumn(T attribute) {
    TextEncryptor encryptor = getEncryptor();
    if (encryptor != null && attribute != null)
        return encrypt(encryptor, attribute);
    return entityAttributeToString(attribute);
}
 
Example 13
Source Project: blog   Source File: AbstractConverter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public T convertToEntityAttribute(String dbData) {
    TextEncryptor encryptor = getEncryptor();
    if (encryptor != null && dbData != null)
        return decrypt(encryptor, dbData);
    return stringToEntityAttribute(dbData);
}
 
Example 14
@Override
public void initialize(GenericApplicationContext context) {
  ConditionService conditions = context.getBeanFactory().getBean(ConditionService.class);
  if (conditions.matches(EncryptionBootstrapConfiguration.VanillaEncryptionConfiguration.class)) {
    if (context.getBeanFactory().getBeanNamesForType(EncryptionBootstrapConfiguration.VanillaEncryptionConfiguration.class).length==0) {
      context.registerBean(EncryptionBootstrapConfiguration.VanillaEncryptionConfiguration.class, () -> new EncryptionBootstrapConfiguration.VanillaEncryptionConfiguration());
      if (conditions.matches(EncryptionBootstrapConfiguration.VanillaEncryptionConfiguration.class, TextEncryptor.class)) {
        context.registerBean("textEncryptor", TextEncryptor.class, () -> context.getBean(EncryptionBootstrapConfiguration.VanillaEncryptionConfiguration.class).textEncryptor());
      }
    }
  }
}
 
Example 15
Source Project: zhcet-web   Source File: CryptoUtilsTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testStandardTextEncryptor() {
    TextEncryptor textEncryptor = CryptoUtils.getStandardEncryptor("newPassword");

    String dataToBeEncrypted = "This is a String data to be encrypted";
    String encryptedData = textEncryptor.encrypt(dataToBeEncrypted);

    assertNotNull(encryptedData);

    String decryptedData = textEncryptor.decrypt(encryptedData);

    assertNotNull(decryptedData);
    assertEquals(dataToBeEncrypted, decryptedData);
}
 
Example 16
Source Project: blackduck-alert   Source File: EncryptionUtility.java    License: Apache License 2.0 5 votes vote down vote up
public String encrypt(String value) {
    String password = getPassword();
    String salt = getEncodedSalt();
    if (StringUtils.isNotBlank(value) && StringUtils.isNotBlank(password) && StringUtils.isNotBlank(salt)) {
        TextEncryptor encryptor = Encryptors.delux(password, salt);
        return encryptor.encrypt(value);
    }
    return StringUtils.EMPTY;
}
 
Example 17
Source Project: blackduck-alert   Source File: EncryptionUtility.java    License: Apache License 2.0 5 votes vote down vote up
public String decrypt(String encryptedValue) {
    try {
        String password = getPassword();
        String salt = getEncodedSalt();
        if (StringUtils.isNotBlank(encryptedValue) && StringUtils.isNotBlank(password) && StringUtils.isNotBlank(salt)) {
            TextEncryptor decryptor = Encryptors.delux(password, salt);
            return decryptor.decrypt(encryptedValue);
        }
    } catch (IllegalArgumentException | IllegalStateException | NullPointerException ex) {
        logger.error("Error decrypting value", ex);
    }
    return StringUtils.EMPTY;
}
 
Example 18
Source Project: SMSC   Source File: EncrypterUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Method to encrypt fields based on {@link Encrypt} annotation.
 *
 * @param obj entity object
 */
public static void encrypt(Object obj) throws IllegalAccessException {
    CharSequence salt = getSalt(obj);

    TextEncryptor encryptor = Encryptors.text(secretKey, salt);
    for (Field field : obj.getClass().getDeclaredFields()) {
        if (field.isAnnotationPresent(Encrypt.class)) {
            field.setAccessible(true);
            field.set(obj, encryptor.encrypt((String) field.get(obj)));
            field.setAccessible(false);
        }
    }
}
 
Example 19
Source Project: SMSC   Source File: EncrypterUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Method to decrypt fields based on {@link Encrypt} annotation.
 *
 * @param obj entity object
 */
public static void decrypt(Object obj) throws IllegalAccessException {
    CharSequence salt = getSalt(obj);

    TextEncryptor encryptor = Encryptors.text(secretKey, salt);
    for (Field field : obj.getClass().getDeclaredFields()) {
        if (field.isAnnotationPresent(Encrypt.class)) {
            field.setAccessible(true);
            field.set(obj, encryptor.decrypt((String) field.get(obj)));
            field.setAccessible(false);
        }
    }
}
 
Example 20
Source Project: haven-platform   Source File: SecurityConfiguration.java    License: Apache License 2.0 5 votes vote down vote up
@Bean
TextEncryptor textEncryptor(@Value("${dm.security.cipher.password}") String password,
                            @Value("${dm.security.cipher.salt}") String salt) {
    // on wrong configuration system will pass prop expressions '${prop}' as value, we need to detect this
    Assert.isTrue(StringUtils.hasText(password) && !password.startsWith("${"), "'dm.security.cipher.password' is invalid.");
    Assert.isTrue(StringUtils.hasText(salt) && !salt.startsWith("${"), "'dm.security.cipher.salt' is invalid.");
    //we use bouncycastle because standard  java does not support keys bigger 128bits
    // but spring also does not provide any way to change key size
    // see also: https://github.com/spring-projects/spring-security/issues/2917
    BytesEncryptor encryptor = new BouncyCastleAesGcmBytesEncryptor(password, salt);
    return new Base64Encryptor(encryptor);
}
 
Example 21
Source Project: haven-platform   Source File: MailServiceTest.java    License: Apache License 2.0 5 votes vote down vote up
@Bean
TextEncryptor textEncryptor() {
    return new TextEncryptor() {
        @Override
        public String encrypt(String text) { return text; }

        @Override
        public String decrypt(String encryptedText) { return encryptedText; }
    };
}
 
Example 22
@Test
public void symmetric() {
	ConfigurableApplicationContext context = new SpringApplicationBuilder(
			EncryptionBootstrapConfiguration.class).web(WebApplicationType.NONE)
					.properties("encrypt.key:pie").run();
	TextEncryptor encryptor = context.getBean(TextEncryptor.class);
	then(encryptor.decrypt(encryptor.encrypt("foo"))).isEqualTo("foo");
	context.close();
}
 
Example 23
@Test
public void rsaKeyStore() {
	ConfigurableApplicationContext context = new SpringApplicationBuilder(
			EncryptionBootstrapConfiguration.class)
					.web(WebApplicationType.NONE)
					.properties("encrypt.keyStore.location:classpath:/server.jks",
							"encrypt.keyStore.password:letmein",
							"encrypt.keyStore.alias:mytestkey",
							"encrypt.keyStore.secret:changeme")
					.run();
	TextEncryptor encryptor = context.getBean(TextEncryptor.class);
	then(encryptor.decrypt(encryptor.encrypt("foo"))).isEqualTo("foo");
	context.close();
}
 
Example 24
@Test
public void testWithRsaPrivateKey() throws Exception {
	String key = StreamUtils.copyToString(
			new ClassPathResource("/example-test-rsa-private-key").getInputStream(),
			Charset.forName("ASCII"));

	TextEncryptor encryptor = new EncryptorFactory().create(key);
	String toEncrypt = "sample text to encrypt";
	String encrypted = encryptor.encrypt(toEncrypt);

	then(encryptor.decrypt(encrypted)).isEqualTo(toEncrypt);
}
 
Example 25
Source Project: spring-cloud-cli   Source File: EncryptCommand.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected synchronized ExitStatus run(OptionSet options) throws Exception {
	TextEncryptor encryptor = createEncryptor(options);
	String text = StringUtils.collectionToDelimitedString(
			options.nonOptionArguments(), " ");
	System.out.println(formatCipher(options, encryptor.encrypt(text)));
	return ExitStatus.OK;
}
 
Example 26
Source Project: spring-cloud-cli   Source File: DecryptCommand.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected synchronized ExitStatus run(OptionSet options) throws Exception {
	TextEncryptor encryptor = createEncryptor(options);
	String text = StringUtils.collectionToDelimitedString(
			options.nonOptionArguments(), " ");
	if (text.startsWith("{cipher}")) {
		text = text.substring("{cipher}".length());
	}
	System.out.println(encryptor.decrypt(text));
	return ExitStatus.OK;
}
 
Example 27
@Override
public TextEncryptor locate(Map<String, String> keys) {
	String alias = keys.containsKey(KEY) ? keys.get(KEY) : this.defaultAlias;
	String secret = keys.containsKey(SECRET) ? keys.get(SECRET) : this.defaultSecret;
	if (alias.equals(this.defaultAlias) && secret.equals(this.defaultSecret)) {
		if (this.defaultEncryptor == null) {
			this.defaultEncryptor = rsaSecretEncryptor(alias, secret);
		}
		return this.defaultEncryptor;
	}
	else {
		return rsaSecretEncryptor(alias, secret);
	}
}
 
Example 28
Source Project: spring-cloud-config   Source File: EncryptionController.java    License: Apache License 2.0 5 votes vote down vote up
@RequestMapping(value = "/key/{name}/{profiles}", method = RequestMethod.GET)
public String getPublicKey(@PathVariable String name, @PathVariable String profiles) {
	TextEncryptor encryptor = getEncryptor(name, profiles, "");
	if (!(encryptor instanceof RsaKeyHolder)) {
		throw new KeyNotAvailableException();
	}
	return ((RsaKeyHolder) encryptor).getPublicKey();
}
 
Example 29
Source Project: spring-cloud-config   Source File: EncryptionController.java    License: Apache License 2.0 5 votes vote down vote up
@RequestMapping(value = "encrypt/status", method = RequestMethod.GET)
public Map<String, Object> status() {
	TextEncryptor encryptor = getEncryptor(defaultApplicationName, defaultProfile,
			"");
	validateEncryptionWeakness(encryptor);
	return Collections.singletonMap("status", "OK");
}
 
Example 30
Source Project: spring-cloud-config   Source File: EncryptionController.java    License: Apache License 2.0 5 votes vote down vote up
@RequestMapping(value = "/encrypt/{name}/{profiles}", method = RequestMethod.POST)
public String encrypt(@PathVariable String name, @PathVariable String profiles,
		@RequestBody String data, @RequestHeader("Content-Type") MediaType type) {
	TextEncryptor encryptor = getEncryptor(name, profiles, "");
	validateEncryptionWeakness(encryptor);
	String input = stripFormData(data, type, false);
	Map<String, String> keys = helper.getEncryptorKeys(name, profiles, input);
	String textToEncrypt = helper.stripPrefix(input);
	String encrypted = helper.addPrefix(keys,
			encryptorLocator.locate(keys).encrypt(textToEncrypt));
	logger.info("Encrypted data");
	return encrypted;
}