cryptography.adoc 7.8 KB

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