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

The following examples show how to use org.springframework.security.crypto.encrypt.TextEncryptor. 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: EncryptionController.java    From spring-cloud-config with 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 #2
Source File: EnvironmentDecryptApplicationInitializerTests.java    From spring-cloud-commons with Apache License 2.0 6 votes vote down vote up
@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 #3
Source File: StringEncryptorHolder.java    From summerframework with 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 #4
Source File: EncryptionBootstrapConfiguration_RsaEncryptionConfigurationInitializer.java    From spring-init with Apache License 2.0 6 votes vote down vote up
@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 #5
Source File: EncryptionBootstrapConfiguration.java    From spring-cloud-commons with Apache License 2.0 6 votes vote down vote up
@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
Source File: KvMapperFactory.java    From haven-platform with 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 #7
Source File: EncryptionComponent.java    From syndesis with 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 #8
Source File: EncryptionControllerTests.java    From spring-cloud-config with Apache License 2.0 6 votes vote down vote up
@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 File: EncrypterUtil.java    From SMSC with 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 #10
Source File: EncryptCommand.java    From spring-cloud-cli with 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 #11
Source File: MailServiceTest.java    From haven-platform with 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 #12
Source File: EncrypterUtil.java    From SMSC with 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 #13
Source File: EncryptionUtility.java    From blackduck-alert with 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 #14
Source File: EncryptionUtility.java    From blackduck-alert with 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 #15
Source File: EncryptionBootstrapConfigurationTests.java    From spring-cloud-commons with Apache License 2.0 5 votes vote down vote up
@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 #16
Source File: EncryptionBootstrapConfigurationTests.java    From spring-cloud-commons with Apache License 2.0 5 votes vote down vote up
@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 #17
Source File: AbstractConverter.java    From blog with 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 #18
Source File: EncryptorFactoryTests.java    From spring-cloud-commons with Apache License 2.0 5 votes vote down vote up
@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 #19
Source File: SecurityConfiguration.java    From haven-platform with 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 #20
Source File: DecryptCommand.java    From spring-cloud-cli with 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 #21
Source File: KeyStoreTextEncryptorLocator.java    From spring-cloud-config with Apache License 2.0 5 votes vote down vote up
@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 #22
Source File: EncryptionController.java    From spring-cloud-config with 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 #23
Source File: EncryptionController.java    From spring-cloud-config with 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 #24
Source File: EncryptionController.java    From spring-cloud-config with 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;
}
 
Example #25
Source File: MongoConnectionRepositoryImpl.java    From JiwhizBlogWeb with Apache License 2.0 5 votes vote down vote up
public MongoConnectionRepositoryImpl(String userId, UserSocialConnectionRepository userSocialConnectionRepository,
        SocialAuthenticationServiceLocator socialAuthenticationServiceLocator, TextEncryptor textEncryptor) {
    this.userId = userId;
    this.userSocialConnectionRepository = userSocialConnectionRepository;
    this.socialAuthenticationServiceLocator = socialAuthenticationServiceLocator;
    this.textEncryptor = textEncryptor;
}
 
Example #26
Source File: EncryptionAutoConfiguration.java    From spring-cloud-config with Apache License 2.0 5 votes vote down vote up
@Bean
public TextEncryptor defaultTextEncryptor() {
	if (this.locator != null) {
		return new LocatorTextEncryptor(this.locator);
	}
	if (StringUtils.hasText(this.key.getKey())) {
		return new EncryptorFactory(this.key.getSalt()).create(this.key.getKey());
	}
	return Encryptors.noOpText();
}
 
Example #27
Source File: EncryptionControllerTests.java    From spring-cloud-config with Apache License 2.0 5 votes vote down vote up
@Test
public void prefixStrippedBeforeEncrypt() {
	TextEncryptor encryptor = mock(TextEncryptor.class);
	when(encryptor.encrypt(anyString())).thenReturn("myEncryptedValue");

	this.controller = new EncryptionController(
			new SingleTextEncryptorLocator(encryptor));
	this.controller.encrypt("{key:test}foo", MediaType.TEXT_PLAIN);

	ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class);
	verify(encryptor, atLeastOnce()).encrypt(captor.capture());
	assertThat(captor.getValue()).doesNotContain("{key:test}")
			.as("Prefix must be stripped prior to encrypt");
}
 
Example #28
Source File: KeyStoreTextEncryptorLocatorTests.java    From spring-cloud-config with Apache License 2.0 5 votes vote down vote up
@Test
public void testDifferentKeyDefaultSecret() {
	this.locator.setSecretLocator(new SecretLocator() {

		@Override
		public char[] locate(String secret) {
			assertThat(secret).isEqualTo("changeme");
			// The actual secret for "mykey" is the same as the keystore password
			return "letmein".toCharArray();
		}
	});
	TextEncryptor encryptor = this.locator
			.locate(Collections.<String, String>singletonMap("key", "mykey"));
	assertThat(encryptor.decrypt(encryptor.encrypt("foo"))).isEqualTo("foo");
}
 
Example #29
Source File: KeyStoreTextEncryptorLocatorTests.java    From spring-cloud-config with Apache License 2.0 5 votes vote down vote up
@Test
public void testDifferentKeyAndSecret() {
	Map<String, String> map = new HashMap<String, String>();
	map.put("key", "mytestkey");
	map.put("secret", "changeme");
	TextEncryptor encryptor = this.locator.locate(map);
	assertThat(encryptor.decrypt(encryptor.encrypt("foo"))).isEqualTo("foo");
}
 
Example #30
Source File: KeyStoreTextEncryptorLocatorTests.java    From spring-cloud-config with Apache License 2.0 5 votes vote down vote up
@Test
public void testDefaultEncryptor() {
	TextEncryptor encryptor1 = this.locator
			.locate(Collections.<String, String>emptyMap());
	TextEncryptor encryptor2 = this.locator
			.locate(Collections.<String, String>emptyMap());
	assertThat(encryptor1).isEqualTo(encryptor2);
}