Encryption and decryption support
Spring Cloud built-in support for encryption and decryption, including symmetric encryption and asymmetric encryption. Symmetric encryption is used only by bootstrap.yml file encrypt.key
specified key encryption attributes.
encrypt:
key: ABC
This Spring Cloud will automatically create a org.springframework.security.crypto.encrypt.TextEncryptor
type of bean. TextEncryptor can be used for encryption and decryption.
@SpringBootTest(classes = Application.class)
@RunWith(SpringRunner.class)
public class TextEncryptorTest {
@Autowired
private TextEncryptor textEncryptor;
@Test
public void test() {
for (int i=0; i<10; i++) {
String plainText = "ABCDEFG";
String encryptedText = this.textEncryptor.encrypt(plainText);
String decryptedText = this.textEncryptor.decrypt(encryptedText);
System.out.println(plainText + "----------" + encryptedText + "-----------" + decryptedText);
}
}
}
If you run the above code you will find the results after the result of TextEncryptor encryption 10 times on the same text each time encryption is not the same, but the results are the same decrypt them. This is because the underlying AES encryption algorithm is used AES/CBC/PKCS5Padding
, the IV value using randomly generated again each time, so due to the IV value is different each time, so that out of the encryption result is not the same. For more information please refer to org.springframework.cloud.bootstrap.encrypt.EncryptionBootstrapConfiguration
the source code.
Spring Cloud also built-in support for asymmetric encryption and decryption. Underlying the RSA algorithm is used, which requires us to generate an asymmetric encryption key based on the RSA algorithm, and then store it in a KeyStore. Then specify the information in the KeyStore bootstrap.yml by the following manner.
encrypt:
key-store:
location: server.jks
alias: testkey
password: 123456
secret: key123456
Spring Cloud will then automatically created based on the RSA algorithm TextEncryptor achieve, RsaSecretEncryptor. RsaSecretEncryptor using the public key pair stored inside KeyStore encrypted using a private key to decrypt. It will carry out encrypted content using the AES encryption algorithm by a randomly generated key, then the length of the AES key, the encrypted key and the encrypted ciphertext encrypted with the public key together through. So you can achieve the same result through the contents of each encrypted is not the same. When carrying out the reverse operation as long as the decrypted plaintext to get up. Details can be found RsaSecretEncryptor source.
When both specified
encrypt.key
andencrypt.keyStore.xxx
when relevant information, Spring Cloud will give priority to create RSA-based TextEncryptor.