4.2 More about the spring security Crypto module
4.2.1 Using key generators
two main types of key generators: BytesKeyGenerator and StringKeyGenerator
the definition of the StringKeyGenerator contract in this code snippet:
public interface StringKeyGenerator {String generateKey();}
how to obtain a StringKeyGenerator instance and how to use it to get a salt value:
StringKeyGenerator keyGenerator = KeyGenerators.string();String salt = keyGenerator.generateKey();
BytesKeyGenerator is defined as follows:
public interface BytesKeyGenerator {int getKeyLength();byte[] generateKey();}
A default ByteKeyGenerator generates keys of 8-byte length:
BytesKeyGenerator keyGenerator = KeyGenerators.secureRandom();byte [] key = keyGenerator.generateKey();int keyLength = keyGenerator.getKeyLength();
change the key generator generates keys of 8-byte length
BytesKeyGenerator keyGenerator = KeyGenerators.secureRandom(16);
an implementation that returns the same key value for each call of the same key generator. key1 and key2 have the same value
BytesKeyGenerator keyGenerator = KeyGenerators.shared(16);byte [] key1 = keyGenerator.generateKey();byte [] key2 = keyGenerator.generateKey();
4.2.2 Using encryptors for encryption and decryption operations
There are two types of encryptors defined by the SSCM: BytesEncryptor and TextEncryptor
the definition of the TextEncryptor
public interface TextEncryptor {String encrypt(String text);String decrypt(String encryptedText);}
the definition of the BytesEncryptor
public interface BytesEncryptor {byte[] encrypt(byte[] byteArray);byte[] decrypt(byte[] encryptedByteArray);}
what options we have to build and use an encryptor
String salt = KeyGenerators.string().generateKey();String password = "secret";String valueToEncrypt = "HELLO";BytesEncryptor e = Encryptors.standard(password, salt);byte [] encrypted = e.encrypt(valueToEncrypt.getBytes());byte [] decrypted = e.decrypt(encrypted);
To build a stronger instance of the byte encryptor, you can call the Encryptors.stronger()
BytesEncryptor e = Encryptors.stronger(password, salt);
an example of using a TextEncryptor
String valueToEncrypt = "HELLO";TextEncryptor e = Encryptors.noOpText();String encrypted = e.encrypt(valueToEncrypt);
String salt = KeyGenerators.string().generateKey();String password = "secret";String valueToEncrypt = "HELLO";TextEncryptor e = Encryptors.text(password, salt);String encrypted = e.encrypt(valueToEncrypt);String decrypted = e.decrypt(encrypted);
In the following example, the value of the encrypted1 equals the value of the encrypted2:
String salt = KeyGenerators.string().generateKey();String password = "secret";String valueToEncrypt = "HELLO";TextEncryptor e = Encryptors.queryableText(password, salt);String encrypted1 = e.encrypt(valueToEncrypt);String encrypted2 = e.encrypt(valueToEncrypt);
