org.springframework.cloud.bootstrap.encrypt.KeySpecProperties Maven / Gradle / Ivy
package org.springframework.cloud.bootstrap.encrypt;
import java.lang.reflect.Field;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.context.encrypt.EncryptorFactory;
import org.springframework.cloud.context.encrypt.KeyFormatException;
import org.springframework.security.crypto.encrypt.EncryptorsCustom;
import org.springframework.security.crypto.encrypt.TextEncryptor;
import org.springframework.security.rsa.crypto.RsaSecretEncryptor;
import org.springframework.util.Assert;
import org.springframework.util.ReflectionUtils;
import org.springframework.util.StringUtils;
/**
*
public enum AES {
V1(128), V2(256);
private int value;
private AES(int value) {
this.value = value;
}
public int getValue() {
return this.value;
}
}
*
*/
@ConfigurationProperties("key-spec")
public class KeySpecProperties {
private String salt;
private int iterationCount = 1024;
private int keyLength = 256;
private String algorithm = "PBKDF2WithHmacSHA1";
private String cipherAlgorithm = "CBC";
public int getIterationCount() {
return iterationCount;
}
public void setIterationCount(int iterationCount) {
this.iterationCount = iterationCount;
}
public int getKeyLength() {
return keyLength;
}
public void setKeyLength(int keyLength) {
this.keyLength = keyLength;
}
public void setSalt(String salt) {
this.salt = salt;
}
public String getAlgorithm() {
return algorithm;
}
public void setAlgorithm(String algorithm) {
this.algorithm = algorithm;
}
public String getCipherAlgorithm() {
return cipherAlgorithm;
}
public void setCipherAlgorithm(String cipherAlgorithm) {
this.cipherAlgorithm = cipherAlgorithm;
}
public TextEncryptor getTextEncryptor(String data) {
TextEncryptor encryptor;
if (data.contains("RSA PRIVATE KEY")) {
try {
encryptor = new RsaSecretEncryptor(data);
}
catch (IllegalArgumentException e) {
throw new KeyFormatException();
}
}
else if (data.startsWith("ssh-rsa") || data.contains("RSA PUBLIC KEY")) {
throw new KeyFormatException();
}
else {
encryptor = EncryptorsCustom.text(data, getSalt(), this.cipherAlgorithm, this.iterationCount, this.keyLength, algorithm);
}
return encryptor;
}
/**
*
* new String(org.springframework.security.crypto.codec.Hex.encode(password.getBytes(charset))
*
* @see java.nio.charset.StandardCharsets#UTF_8
*/
public String getSalt() {
if (StringUtils.hasText(this.salt)) {
return this.salt;
}
Field field = ReflectionUtils.findField(EncryptorFactory.class, "SALT");
ReflectionUtils.makeAccessible(field);
Object salt = ReflectionUtils.getField(field, null);
Assert.isInstanceOf(String.class, salt, "SALT expected");
return (String) salt;
}
}