2
0

cryptography.adoc 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  1. [[crypto]]
  2. = Spring Security Crypto Module
  3. [[spring-security-crypto-introduction]]
  4. The Spring Security Crypto module provides support for symmetric encryption, key generation, and password encoding.
  5. The code is distributed as part of the core module but has no dependencies on any other Spring Security (or Spring) code.
  6. [[spring-security-crypto-encryption]]
  7. == Encryptors
  8. The {security-api-url}org/springframework/security/crypto/encrypt/Encryptors.html[`Encryptors`] class provides factory methods for constructing symmetric encryptors.
  9. This class lets you create {security-api-url}org/springframework/security/crypto/encrypt/BytesEncryptor.html[`BytesEncryptor`] instances to encrypt data in raw `byte[]` form.
  10. You can also construct {security-api-url}org/springframework/security/crypto/encrypt/TextEncryptor.html[TextEncryptor] instances to encrypt text strings.
  11. Encryptors are thread-safe.
  12. [NOTE]
  13. ====
  14. Both `BytesEncryptor` and `TextEncryptor` are interfaces. `BytesEncryptor` has multiple implementations.
  15. ====
  16. [[spring-security-crypto-encryption-bytes]]
  17. === BytesEncryptor
  18. You can use the `Encryptors.stronger` factory method to construct a `BytesEncryptor`:
  19. .BytesEncryptor
  20. ====
  21. .Java
  22. [source,java,role="primary"]
  23. ----
  24. Encryptors.stronger("password", "salt");
  25. ----
  26. .Kotlin
  27. [source,kotlin,role="secondary"]
  28. ----
  29. Encryptors.stronger("password", "salt")
  30. ----
  31. ====
  32. The `stronger` encryption method creates an encryptor by using 256-bit AES encryption with
  33. Galois Counter Mode (GCM).
  34. It derives the secret key by using PKCS #5's PBKDF2 (Password-Based Key Derivation Function #2).
  35. This method requires Java 6.
  36. The password used to generate the `SecretKey` should be kept in a secure place and should not be shared.
  37. The salt is used to prevent dictionary attacks against the key in the event that your encrypted data is compromised.
  38. A 16-byte random initialization vector is also applied so that each encrypted message is unique.
  39. The provided salt should be in hex-encoded String form, be random, and be at least 8 bytes in length.
  40. You can generate such a salt by using a `KeyGenerator`:
  41. .Generating a key
  42. ====
  43. .Java
  44. [source,java,role="primary"]
  45. ----
  46. String salt = KeyGenerators.string().generateKey(); // generates a random 8-byte salt that is then hex-encoded
  47. ----
  48. .Kotlin
  49. [source,kotlin,role="secondary"]
  50. ----
  51. val salt = KeyGenerators.string().generateKey() // generates a random 8-byte salt that is then hex-encoded
  52. ----
  53. ====
  54. You can also use the `standard` encryption method, which is 256-bit AES in Cipher Block Chaining (CBC) Mode.
  55. This mode is not https://en.wikipedia.org/wiki/Authenticated_encryption[authenticated] and does not provide any
  56. guarantees about the authenticity of the data.
  57. For a more secure alternative, use `Encryptors.stronger`.
  58. [[spring-security-crypto-encryption-text]]
  59. === TextEncryptor
  60. You can use the `Encryptors.text` factory method to construct a standard TextEncryptor:
  61. .TextEncryptor
  62. ====
  63. .Java
  64. [source,java,role="primary"]
  65. ----
  66. Encryptors.text("password", "salt");
  67. ----
  68. .Kotlin
  69. [source,kotlin,role="secondary"]
  70. ----
  71. Encryptors.text("password", "salt")
  72. ----
  73. ====
  74. A `TextEncryptor` uses a standard `BytesEncryptor` to encrypt text data.
  75. Encrypted results are returned as hex-encoded strings for easy storage on the filesystem or in a database.
  76. [[spring-security-crypto-keygenerators]]
  77. == Key Generators
  78. The {security-api-url}org/springframework/security/crypto/keygen/KeyGenerators.html[`KeyGenerators`] class provides a number of convenience factory methods for constructing different types of key generators.
  79. By using this class, you can create a {security-api-url}org/springframework/security/crypto/keygen/BytesKeyGenerator.html[`BytesKeyGenerator`] to generate `byte[]` keys.
  80. You can also construct a {security-api-url}org/springframework/security/crypto/keygen/StringKeyGenerator.html`[StringKeyGenerator]` to generate string keys.
  81. `KeyGenerators` is a thread-safe class.
  82. === BytesKeyGenerator
  83. You can use the `KeyGenerators.secureRandom` factory methods to generate a `BytesKeyGenerator` backed by a `SecureRandom` instance:
  84. .BytesKeyGenerator
  85. ====
  86. .Java
  87. [source,java,role="primary"]
  88. ----
  89. BytesKeyGenerator generator = KeyGenerators.secureRandom();
  90. byte[] key = generator.generateKey();
  91. ----
  92. .Kotlin
  93. [source,kotlin,role="secondary"]
  94. ----
  95. val generator = KeyGenerators.secureRandom()
  96. val key = generator.generateKey()
  97. ----
  98. ====
  99. The default key length is 8 bytes.
  100. A `KeyGenerators.secureRandom` variant provides control over the key length:
  101. .KeyGenerators.secureRandom
  102. ====
  103. .Java
  104. [source,java,role="primary"]
  105. ----
  106. KeyGenerators.secureRandom(16);
  107. ----
  108. .Kotlin
  109. [source,kotlin,role="secondary"]
  110. ----
  111. KeyGenerators.secureRandom(16)
  112. ----
  113. ====
  114. Use the `KeyGenerators.shared` factory method to construct a BytesKeyGenerator that always returns the same key on every invocation:
  115. .KeyGenerators.shared
  116. ====
  117. .Java
  118. [source,java,role="primary"]
  119. ----
  120. KeyGenerators.shared(16);
  121. ----
  122. .Kotlin
  123. [source,kotlin,role="secondary"]
  124. ----
  125. KeyGenerators.shared(16)
  126. ----
  127. ====
  128. === StringKeyGenerator
  129. You can use the `KeyGenerators.string` factory method to construct an 8-byte, `SecureRandom` `KeyGenerator` that hex-encodes each key as a `String`:
  130. .StringKeyGenerator
  131. ====
  132. .Java
  133. [source,java,role="primary"]
  134. ----
  135. KeyGenerators.string();
  136. ----
  137. .Kotlin
  138. [source,kotlin,role="secondary"]
  139. ----
  140. KeyGenerators.string()
  141. ----
  142. ====
  143. [[spring-security-crypto-passwordencoders]]
  144. == Password Encoding
  145. The password package of the `spring-security-crypto` module provides support for encoding passwords.
  146. `PasswordEncoder` is the central service interface and has the following signature:
  147. ====
  148. [source,java]
  149. ----
  150. public interface PasswordEncoder {
  151. String encode(CharSequence rawPassword);
  152. boolean matches(CharSequence rawPassword, String encodedPassword);
  153. default boolean upgradeEncoding(String encodedPassword) {
  154. return false;
  155. }
  156. }
  157. ----
  158. ====
  159. The `matches` method returns true if the `rawPassword`, once encoded, equals the `encodedPassword`.
  160. This method is designed to support password-based authentication schemes.
  161. The `BCryptPasswordEncoder` implementation uses the widely supported "`bcrypt`" algorithm to hash the passwords.
  162. Bcrypt uses a random 16-byte salt value and is a deliberately slow algorithm, to hinder password crackers.
  163. You can tune the amount of work it does by using the `strength` parameter, which takes a value from 4 to 31.
  164. The higher the value, the more work has to be done to calculate the hash.
  165. The default value is `10`.
  166. You can change this value in your deployed system without affecting existing passwords, as the value is also stored in the encoded hash.
  167. The following example uses the `BCryptPasswordEncoder`:
  168. .BCryptPasswordEncoder
  169. ====
  170. .Java
  171. [source,java,role="primary"]
  172. ----
  173. // Create an encoder with strength 16
  174. BCryptPasswordEncoder encoder = new BCryptPasswordEncoder(16);
  175. String result = encoder.encode("myPassword");
  176. assertTrue(encoder.matches("myPassword", result));
  177. ----
  178. .Kotlin
  179. [source,kotlin,role="secondary"]
  180. ----
  181. // Create an encoder with strength 16
  182. val encoder = BCryptPasswordEncoder(16)
  183. val result: String = encoder.encode("myPassword")
  184. assertTrue(encoder.matches("myPassword", result))
  185. ----
  186. ====
  187. The `Pbkdf2PasswordEncoder` implementation uses PBKDF2 algorithm to hash the passwords.
  188. To defeat password cracking, PBKDF2 is a deliberately slow algorithm and should be tuned to take about .5 seconds to verify a password on your system.
  189. The following system uses the `Pbkdf2PasswordEncoder`:
  190. .Pbkdf2PasswordEncoder
  191. ====
  192. .Java
  193. [source,java,role="primary"]
  194. ----
  195. // Create an encoder with all the defaults
  196. Pbkdf2PasswordEncoder encoder = Pbkdf2PasswordEncoder.defaultsForSpringSecurity_v5_8();
  197. String result = encoder.encode("myPassword");
  198. assertTrue(encoder.matches("myPassword", result));
  199. ----
  200. .Kotlin
  201. [source,kotlin,role="secondary"]
  202. ----
  203. // Create an encoder with all the defaults
  204. val encoder = Pbkdf2PasswordEncoder.defaultsForSpringSecurity_v5_8()
  205. val result: String = encoder.encode("myPassword")
  206. assertTrue(encoder.matches("myPassword", result))
  207. ----
  208. ====