├── .gitignore ├── LICENSE ├── README.md ├── pom.xml └── src ├── main ├── java │ └── be │ │ └── cronos │ │ └── keycloak │ │ ├── credential │ │ └── hash │ │ │ ├── Argon2PasswordHashProvider.java │ │ │ └── Argon2PasswordHashProviderFactory.java │ │ ├── enums │ │ └── Argon2Variant.java │ │ ├── exceptions │ │ └── Argon2RuntimeException.java │ │ ├── policy │ │ ├── Argon2GenericPolicyProviderFactory.java │ │ ├── Argon2HashLengthPasswordPolicyProviderFactory.java │ │ ├── Argon2IterationsPasswordPolicyProviderFactory.java │ │ ├── Argon2MaxTimePasswordPolicyProviderFactory.java │ │ ├── Argon2MemoryPasswordPolicyProviderFactory.java │ │ ├── Argon2ParallelismPasswordPolicyProviderFactory.java │ │ ├── Argon2SaltLengthPasswordPolicyProviderFactory.java │ │ ├── Argon2VariantPasswordPolicyProviderFactory.java │ │ └── Argon2VersionPasswordPolicyProviderFactory.java │ │ └── utils │ │ ├── Argon2EncodingUtils.java │ │ └── Argon2Helper.java └── resources │ └── META-INF │ ├── jboss-deployment-structure.xml │ └── services │ ├── org.keycloak.credential.hash.PasswordHashProviderFactory │ └── org.keycloak.policy.PasswordPolicyProviderFactory └── test └── java └── be └── cronos └── keycloak └── utils └── Argon2HelperTest.java /.gitignore: -------------------------------------------------------------------------------- 1 | target/ 2 | ear-module/target/ 3 | jar-module/target/ 4 | *.iml 5 | .idea/ 6 | *.sh -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Introduction 2 | This project introduces Argon2 Password Hashing for Keycloak, there are 2 versions: 3 | * V1.x, which uses `de.mkammerer.argon2` as the library, more can be found on the [GitHub Project](https://github.com/phxql/argon2-jvm). (Compatible with Keycloak V8.x and above) 4 | * V2.x, which inherits Keycloak's [BouncyCastle V1.62](https://www.bouncycastle.org/releasenotes.html#1.61) with native support for Argon2 (Compatible with Keycloak V10.x and above only) 5 | 6 | V1.x is packaged as an EAR due to external dependencies. I will no longer maintain this version. Choose this one if you don't Keycloak V10.x or above. 7 | 8 | V2.x is packaged as a JAR since it uses Keycloak's provided libraries. This will be the **actively maintained** version for now. 9 | 10 | Both are deployed using [Keycloak Deployer](https://www.keycloak.org/docs/latest/server_development/index.html#using-the-keycloak-deployer). 11 | 12 | # Build 13 | Build the project using: 14 | ``` 15 | mvn clean package; 16 | ``` 17 | 18 | This will build the provider JAR: 19 | ``` 20 | [INFO] ----------< be.cronos.keycloak:argon2-password-hash-provider >---------- 21 | [INFO] Building Argon2 Password Hash Provider 2.x.x 22 | [INFO] --------------------------------[ jar ]--------------------------------- 23 | ``` 24 | 25 | # Installation 26 | Simply hot-deploy the module: 27 | ``` 28 | cp target/argon2-password-hash-provider-*.jar /opt/keycloak/standalone/deployments/argon2-password-hash-provider.jar; 29 | ``` 30 | 31 | # Keycloak configuration 32 | Finally, in the Keycloak realm of your choosing, activate the Argon2 password hashing via: 33 | `Authentication > Password Policy` and then selecting the policy `Hashing Algorithm` and name it: `argon2`. 34 | 35 | Further tuning can be done by the other Policy Providers: 36 | * `Argon2 Version` --> you can choose which Argon2 version to use, either: `10` or `13` (default: 13) 37 | * `Argon2 Variant` --> you can choose which Argon2 variant to use, either: `ARGON2i`, `ARGON2d` or `ARGON2id` (default: ARGON2id) 38 | * `Argon2 Iterations` --> tune the number of iterations the provider will perform (default: 1) 39 | * `Argon2 Memory Usage` --> tune the memory limitation (in KB) of the provider (default: 65536) 40 | * `Argon2 Parallelism` --> tune the number of threads and memory lanes (default: 1) 41 | * `Argon2 Salt Length` --> tune the length of the salt (default: 16) 42 | * `Argon2 Hash Length` --> tune the length of the hash (default: 32) 43 | 44 | > I have deprecated use of the `Argon2 Max Time` provider, as I believe it offers no real value. If you still have a use-case for this, let me know. 45 | 46 | For parameter optimization, check the [Argon2 whitepaper recommendations](https://github.com/P-H-C/phc-winner-argon2/blob/master/argon2-specs.pdf#section.9). 47 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 3 | 4.0.0 4 | Argon2 Password Hash Provider 5 | 6 | be.cronos.keycloak 7 | argon2-password-hash-provider 8 | 2.0.1 9 | jar 10 | 11 | 12 | UTF-8 13 | 1.8 14 | 1.8 15 | 10.0.2 16 | 4.13.1 17 | 18 | 19 | 20 | 21 | 22 | org.wildfly.plugins 23 | wildfly-maven-plugin 24 | 2.0.2.Final 25 | 26 | true 27 | 28 | 29 | 30 | 31 | org.sonarsource.scanner.maven 32 | sonar-maven-plugin 33 | 3.7.0.1746 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | org.keycloak 42 | keycloak-core 43 | ${keycloak.version} 44 | provided 45 | 46 | 47 | org.keycloak 48 | keycloak-server-spi 49 | ${keycloak.version} 50 | provided 51 | 52 | 53 | org.keycloak 54 | keycloak-server-spi-private 55 | ${keycloak.version} 56 | provided 57 | 58 | 59 | org.keycloak 60 | keycloak-services 61 | ${keycloak.version} 62 | provided 63 | 64 | 65 | junit 66 | junit 67 | ${junit.version} 68 | test 69 | 70 | 71 | 72 | 73 | -------------------------------------------------------------------------------- /src/main/java/be/cronos/keycloak/credential/hash/Argon2PasswordHashProvider.java: -------------------------------------------------------------------------------- 1 | package be.cronos.keycloak.credential.hash; 2 | 3 | import be.cronos.keycloak.enums.Argon2Variant; 4 | import be.cronos.keycloak.policy.*; 5 | import be.cronos.keycloak.utils.Argon2EncodingUtils; 6 | import be.cronos.keycloak.utils.Argon2Helper; 7 | import org.jboss.logging.Logger; 8 | import org.keycloak.credential.hash.PasswordHashProvider; 9 | import org.keycloak.models.KeycloakSession; 10 | import org.keycloak.models.PasswordPolicy; 11 | import org.keycloak.models.credential.PasswordCredentialModel; 12 | 13 | /** 14 | * @author Dries Eestermans 15 | */ 16 | public class Argon2PasswordHashProvider implements PasswordHashProvider { 17 | private static final Logger LOG = Logger.getLogger(Argon2PasswordHashProvider.class); 18 | 19 | private final String providerId; 20 | private final KeycloakSession session; 21 | 22 | public Argon2PasswordHashProvider(String providerId, KeycloakSession session) { 23 | this.providerId = providerId; 24 | this.session = session; 25 | } 26 | 27 | @Override 28 | public boolean policyCheck(PasswordPolicy policy, PasswordCredentialModel credential) { 29 | LOG.debugf("> policyCheck()"); 30 | // Check it it is an argon2 encoded password. 31 | if (!providerId.equals(credential.getPasswordCredentialData().getAlgorithm())) { 32 | LOG.debugf("< policyCheck() -> Stored password uses a different algorithm and hence does not meet the Realm Password Policy."); 33 | return false; 34 | } 35 | // The stored password is a argon2 hash and hence checking the specific parameters of the policy is required. 36 | 37 | // Get the credential's Argon2 parameters 38 | Argon2EncodingUtils.Argon2Parameters storedArgon2Parameters = Argon2EncodingUtils.extractArgon2ParametersFromEncodedPassword(credential.getPasswordSecretData().getValue()); 39 | // Get the configured Argon2 parameters 40 | Argon2EncodingUtils.Argon2Parameters configuredArgon2Parameters = getConfiguredArgon2Parameters(); 41 | 42 | // Perform a comparison on whether a re-hash is needed 43 | boolean meetsRealmPolicy = storedArgon2Parameters.getArgon2Variant().getArgon2BouncyCastle() == configuredArgon2Parameters.getArgon2Variant().getArgon2BouncyCastle() 44 | && storedArgon2Parameters.getVersion() == configuredArgon2Parameters.getVersion() 45 | && storedArgon2Parameters.getMemory() == configuredArgon2Parameters.getMemory() 46 | && storedArgon2Parameters.getIterations() == configuredArgon2Parameters.getIterations() 47 | && storedArgon2Parameters.getParallelism() == configuredArgon2Parameters.getParallelism(); 48 | 49 | LOG.debugf("< policyCheck() -> Stored password meets Realm Password Policy = '%s'.", String.valueOf(meetsRealmPolicy)); 50 | return meetsRealmPolicy; 51 | } 52 | 53 | @Override 54 | public PasswordCredentialModel encodedCredential(String rawPassword, int iterations) { 55 | LOG.debugf("> encodedCredential()"); 56 | 57 | // Get the configured Argon2 parameters, or default values 58 | Argon2EncodingUtils.Argon2Parameters configuredArgon2Parameters = getConfiguredArgon2Parameters(); 59 | 60 | // Generate a salt 61 | byte[] salt = Argon2Helper.getSalt(configuredArgon2Parameters.getSaltLength()); 62 | 63 | // Retrieve an encoded Argon2 password hash 64 | String hash = Argon2Helper.hashPassword( 65 | rawPassword, 66 | salt, 67 | configuredArgon2Parameters.getArgon2Variant(), 68 | configuredArgon2Parameters.getVersion(), 69 | configuredArgon2Parameters.getIterations(), 70 | configuredArgon2Parameters.getParallelism(), 71 | configuredArgon2Parameters.getMemory(), 72 | configuredArgon2Parameters.getHashLength() 73 | ); 74 | 75 | LOG.debugf("< encodedCredential()"); 76 | return PasswordCredentialModel.createFromValues(providerId, salt, configuredArgon2Parameters.getIterations(), hash); 77 | } 78 | 79 | @Override 80 | public boolean verify(String rawPassword, PasswordCredentialModel credential) { 81 | LOG.debugf("> verify()"); 82 | 83 | // Verify whether the incoming password matches the stored password 84 | boolean passwordsMatch = Argon2Helper.verifyPassword(rawPassword, credential); 85 | 86 | LOG.debugf("< verify()"); 87 | return passwordsMatch; 88 | } 89 | 90 | @Override 91 | public void close() { 92 | // noop 93 | } 94 | 95 | private T getDefaultValue(String providerId, T defaultValue) { 96 | T ret; 97 | try { 98 | ret = this.session.getContext().getRealm().getPasswordPolicy().getPolicyConfig(providerId); 99 | } catch (Exception e) { 100 | ret = defaultValue; 101 | } 102 | if (ret == null) ret = defaultValue; 103 | return ret; 104 | } 105 | 106 | private Argon2EncodingUtils.Argon2Parameters getConfiguredArgon2Parameters() { 107 | return new Argon2EncodingUtils.Argon2Parameters( 108 | Argon2Variant.parseVariant(getDefaultValue(Argon2VariantPasswordPolicyProviderFactory.ID, Argon2VariantPasswordPolicyProviderFactory.DEFAULT_ARGON2_VARIANT)), 109 | getDefaultValue(Argon2VersionPasswordPolicyProviderFactory.ID, Argon2VersionPasswordPolicyProviderFactory.DEFAULT_VERSION), 110 | getDefaultValue(Argon2MemoryPasswordPolicyProviderFactory.ID, Argon2MemoryPasswordPolicyProviderFactory.DEFAULT_MEMORY), 111 | getDefaultValue(Argon2IterationsPasswordPolicyProviderFactory.ID, Argon2IterationsPasswordPolicyProviderFactory.DEFAULT_ITERATIONS), 112 | getDefaultValue(Argon2ParallelismPasswordPolicyProviderFactory.ID, Argon2ParallelismPasswordPolicyProviderFactory.DEFAULT_PARALLELISM), 113 | getDefaultValue(Argon2HashLengthPasswordPolicyProviderFactory.ID, Argon2HashLengthPasswordPolicyProviderFactory.DEFAULT_HASH_LENGTH), 114 | getDefaultValue(Argon2SaltLengthPasswordPolicyProviderFactory.ID, Argon2SaltLengthPasswordPolicyProviderFactory.DEFAULT_SALT_LENGTH) 115 | ); 116 | } 117 | } 118 | -------------------------------------------------------------------------------- /src/main/java/be/cronos/keycloak/credential/hash/Argon2PasswordHashProviderFactory.java: -------------------------------------------------------------------------------- 1 | package be.cronos.keycloak.credential.hash; 2 | 3 | import org.keycloak.Config; 4 | import org.keycloak.credential.hash.PasswordHashProvider; 5 | import org.keycloak.credential.hash.PasswordHashProviderFactory; 6 | import org.keycloak.models.KeycloakSession; 7 | import org.keycloak.models.KeycloakSessionFactory; 8 | 9 | /** 10 | * @author Dries Eestermans 11 | */ 12 | public class Argon2PasswordHashProviderFactory implements PasswordHashProviderFactory { 13 | public static final String ID = "argon2"; 14 | 15 | @Override 16 | public PasswordHashProvider create(KeycloakSession session) { 17 | return new Argon2PasswordHashProvider(ID, session); 18 | } 19 | 20 | @Override 21 | public void init(Config.Scope config) { 22 | // noop 23 | } 24 | 25 | @Override 26 | public void postInit(KeycloakSessionFactory factory) { 27 | // noop 28 | } 29 | 30 | @Override 31 | public String getId() { 32 | return ID; 33 | } 34 | 35 | @Override 36 | public void close() { 37 | // noop 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/main/java/be/cronos/keycloak/enums/Argon2Variant.java: -------------------------------------------------------------------------------- 1 | package be.cronos.keycloak.enums; 2 | 3 | import org.bouncycastle.crypto.params.Argon2Parameters; 4 | 5 | import java.util.Arrays; 6 | 7 | /** 8 | * @author Dries Eestermans 9 | */ 10 | public enum Argon2Variant { 11 | ARGON2I("argon2i", Argon2Parameters.ARGON2_i), 12 | ARGON2D("argon2d", Argon2Parameters.ARGON2_d), 13 | ARGON2ID("argon2id", Argon2Parameters.ARGON2_id); 14 | 15 | private final String argon2VariantStringRepr; 16 | private final int argon2BouncyCastle; 17 | 18 | Argon2Variant(String argon2VariantStringRepr, int argon2BouncyCastle) { 19 | this.argon2VariantStringRepr = argon2VariantStringRepr; 20 | this.argon2BouncyCastle = argon2BouncyCastle; 21 | } 22 | 23 | public String getArgon2VariantStringRepr() { 24 | return argon2VariantStringRepr; 25 | } 26 | 27 | public int getArgon2BouncyCastle() { 28 | return argon2BouncyCastle; 29 | } 30 | 31 | public static boolean isValidVariant(String variant) { 32 | return Arrays 33 | .stream(Argon2Variant.values()) 34 | .anyMatch(v -> v.argon2VariantStringRepr.equalsIgnoreCase(variant)); 35 | } 36 | 37 | public static Argon2Variant parseVariant(String variant) { 38 | if (isValidVariant(variant)) { 39 | return Argon2Variant.valueOf(variant.toUpperCase()); 40 | } 41 | return null; 42 | } 43 | 44 | } 45 | -------------------------------------------------------------------------------- /src/main/java/be/cronos/keycloak/exceptions/Argon2RuntimeException.java: -------------------------------------------------------------------------------- 1 | package be.cronos.keycloak.exceptions; 2 | 3 | /** 4 | * @author Dries Eestermans 5 | */ 6 | public class Argon2RuntimeException extends RuntimeException { 7 | public Argon2RuntimeException() { 8 | } 9 | 10 | public Argon2RuntimeException(String message) { 11 | super(message); 12 | } 13 | 14 | public Argon2RuntimeException(String message, Throwable cause) { 15 | super(message, cause); 16 | } 17 | 18 | public Argon2RuntimeException(Throwable cause) { 19 | super(cause); 20 | } 21 | 22 | public Argon2RuntimeException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { 23 | super(message, cause, enableSuppression, writableStackTrace); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/be/cronos/keycloak/policy/Argon2GenericPolicyProviderFactory.java: -------------------------------------------------------------------------------- 1 | package be.cronos.keycloak.policy; 2 | 3 | import org.keycloak.Config; 4 | import org.keycloak.models.KeycloakSession; 5 | import org.keycloak.models.KeycloakSessionFactory; 6 | import org.keycloak.models.RealmModel; 7 | import org.keycloak.models.UserModel; 8 | import org.keycloak.policy.PasswordPolicyProvider; 9 | import org.keycloak.policy.PasswordPolicyProviderFactory; 10 | import org.keycloak.policy.PolicyError; 11 | 12 | /** 13 | * @author Dries Eestermans 14 | */ 15 | public abstract class Argon2GenericPolicyProviderFactory implements PasswordPolicyProvider, PasswordPolicyProviderFactory { 16 | 17 | @Override 18 | public Argon2GenericPolicyProviderFactory create(KeycloakSession session) { 19 | return this; 20 | } 21 | 22 | @Override 23 | public void init(Config.Scope config) { 24 | // noop 25 | } 26 | 27 | @Override 28 | public void postInit(KeycloakSessionFactory factory) { 29 | // noop 30 | } 31 | 32 | @Override 33 | public PolicyError validate(RealmModel realm, UserModel user, String password) { 34 | return null; 35 | } 36 | 37 | @Override 38 | public PolicyError validate(String user, String password) { 39 | return null; 40 | } 41 | 42 | @Override 43 | public Object parseConfig(String value) { 44 | return parseInteger(value, -1); 45 | } 46 | 47 | @Override 48 | public String getConfigType() { 49 | return PasswordPolicyProvider.INT_CONFIG_TYPE; 50 | } 51 | 52 | @Override 53 | public String getDefaultConfigValue() { 54 | return String.valueOf(1); 55 | } 56 | 57 | @Override 58 | public boolean isMultiplSupported() { 59 | return false; 60 | } 61 | 62 | @Override 63 | public void close() { 64 | // noop 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /src/main/java/be/cronos/keycloak/policy/Argon2HashLengthPasswordPolicyProviderFactory.java: -------------------------------------------------------------------------------- 1 | package be.cronos.keycloak.policy; 2 | 3 | /** 4 | * @author Dries Eestermans 5 | */ 6 | public class Argon2HashLengthPasswordPolicyProviderFactory extends Argon2GenericPolicyProviderFactory { 7 | public static final String ID = "argon2HashLength"; 8 | public static final int DEFAULT_HASH_LENGTH = 32; 9 | 10 | @Override 11 | public String getId() { 12 | return ID; 13 | } 14 | 15 | @Override 16 | public String getDisplayName() { 17 | return "Argon2 Hash Length"; 18 | } 19 | 20 | @Override 21 | public String getDefaultConfigValue() { 22 | return String.valueOf(DEFAULT_HASH_LENGTH); 23 | } 24 | 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/be/cronos/keycloak/policy/Argon2IterationsPasswordPolicyProviderFactory.java: -------------------------------------------------------------------------------- 1 | package be.cronos.keycloak.policy; 2 | 3 | /** 4 | * @author Dries Eestermans 5 | */ 6 | public class Argon2IterationsPasswordPolicyProviderFactory extends Argon2GenericPolicyProviderFactory { 7 | public static final String ID = "argon2Iterations"; 8 | public static final int DEFAULT_ITERATIONS = 1; 9 | 10 | @Override 11 | public String getId() { 12 | return ID; 13 | } 14 | 15 | @Override 16 | public String getDisplayName() { 17 | return "Argon2 Iterations"; 18 | } 19 | 20 | @Override 21 | public String getDefaultConfigValue() { 22 | return String.valueOf(DEFAULT_ITERATIONS); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/be/cronos/keycloak/policy/Argon2MaxTimePasswordPolicyProviderFactory.java: -------------------------------------------------------------------------------- 1 | package be.cronos.keycloak.policy; 2 | 3 | /** 4 | * @author Dries Eestermans 5 | */ 6 | @Deprecated 7 | public class Argon2MaxTimePasswordPolicyProviderFactory extends Argon2GenericPolicyProviderFactory { 8 | public static final String ID = "argon2MaxTime"; 9 | 10 | @Override 11 | public String getId() { 12 | return ID; 13 | } 14 | 15 | @Override 16 | public String getDisplayName() { 17 | return "Argon2 Maximum Time (in ms)"; 18 | } 19 | 20 | @Override 21 | public String getDefaultConfigValue() { 22 | return String.valueOf(1000); 23 | } 24 | 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/be/cronos/keycloak/policy/Argon2MemoryPasswordPolicyProviderFactory.java: -------------------------------------------------------------------------------- 1 | package be.cronos.keycloak.policy; 2 | 3 | /** 4 | * @author Dries Eestermans 5 | */ 6 | public class Argon2MemoryPasswordPolicyProviderFactory extends Argon2GenericPolicyProviderFactory { 7 | public static final String ID = "argon2Memory"; 8 | public static final int DEFAULT_MEMORY = 65536; 9 | 10 | @Override 11 | public String getId() { 12 | return ID; 13 | } 14 | 15 | @Override 16 | public String getDisplayName() { 17 | return "Argon2 Memory Usage (KB)"; 18 | } 19 | 20 | @Override 21 | public String getDefaultConfigValue() { 22 | return String.valueOf(DEFAULT_MEMORY); 23 | } 24 | 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/be/cronos/keycloak/policy/Argon2ParallelismPasswordPolicyProviderFactory.java: -------------------------------------------------------------------------------- 1 | package be.cronos.keycloak.policy; 2 | 3 | /** 4 | * @author Dries Eestermans 5 | */ 6 | public class Argon2ParallelismPasswordPolicyProviderFactory extends Argon2GenericPolicyProviderFactory { 7 | public static final String ID = "argon2Parallelism"; 8 | public static final int DEFAULT_PARALLELISM = 1; 9 | 10 | @Override 11 | public String getId() { 12 | return ID; 13 | } 14 | 15 | @Override 16 | public String getDisplayName() { 17 | return "Argon2 Parallelism"; 18 | } 19 | 20 | @Override 21 | public String getDefaultConfigValue() { 22 | return String.valueOf(DEFAULT_PARALLELISM); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/be/cronos/keycloak/policy/Argon2SaltLengthPasswordPolicyProviderFactory.java: -------------------------------------------------------------------------------- 1 | package be.cronos.keycloak.policy; 2 | 3 | /** 4 | * @author Dries Eestermans 5 | */ 6 | public class Argon2SaltLengthPasswordPolicyProviderFactory extends Argon2GenericPolicyProviderFactory { 7 | public static final String ID = "argon2SaltLength"; 8 | public static final int DEFAULT_SALT_LENGTH = 16; 9 | 10 | @Override 11 | public String getId() { 12 | return ID; 13 | } 14 | 15 | @Override 16 | public String getDisplayName() { 17 | return "Argon2 Salt Length"; 18 | } 19 | 20 | @Override 21 | public String getDefaultConfigValue() { 22 | return String.valueOf(DEFAULT_SALT_LENGTH); 23 | } 24 | 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/be/cronos/keycloak/policy/Argon2VariantPasswordPolicyProviderFactory.java: -------------------------------------------------------------------------------- 1 | package be.cronos.keycloak.policy; 2 | 3 | import be.cronos.keycloak.enums.Argon2Variant; 4 | import org.keycloak.policy.PasswordPolicyConfigException; 5 | 6 | /** 7 | * @author Dries Eestermans 8 | */ 9 | public class Argon2VariantPasswordPolicyProviderFactory extends Argon2GenericPolicyProviderFactory { 10 | public static final String ID = "argon2Variant"; 11 | public static final String DEFAULT_ARGON2_VARIANT = Argon2Variant.ARGON2ID.getArgon2VariantStringRepr(); 12 | 13 | @Override 14 | public String getId() { 15 | return ID; 16 | } 17 | 18 | @Override 19 | public Object parseConfig(String value) { 20 | Argon2Variant argon2Variant = Argon2Variant.parseVariant(value); 21 | if (argon2Variant == null) throw new PasswordPolicyConfigException("Invalid Argon2 variant, valid choices are: ARGON2i, ARGON2id or ARGON2d."); 22 | return argon2Variant.getArgon2VariantStringRepr(); 23 | } 24 | 25 | @Override 26 | public String getDisplayName() { 27 | return "Argon2 Variant"; 28 | } 29 | 30 | @Override 31 | public String getDefaultConfigValue() { 32 | return String.valueOf(DEFAULT_ARGON2_VARIANT); 33 | } 34 | 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/be/cronos/keycloak/policy/Argon2VersionPasswordPolicyProviderFactory.java: -------------------------------------------------------------------------------- 1 | package be.cronos.keycloak.policy; 2 | 3 | import org.bouncycastle.crypto.params.Argon2Parameters; 4 | import org.keycloak.policy.PasswordPolicyConfigException; 5 | 6 | /** 7 | * @author Dries Eestermans 8 | */ 9 | public class Argon2VersionPasswordPolicyProviderFactory extends Argon2GenericPolicyProviderFactory { 10 | public static final String ID = "argon2Version"; 11 | public static final int DEFAULT_VERSION = Argon2Parameters.ARGON2_VERSION_13; 12 | 13 | @Override 14 | public String getId() { 15 | return ID; 16 | } 17 | 18 | @Override 19 | public String getDisplayName() { 20 | return "Argon2 Version"; 21 | } 22 | 23 | @Override 24 | public Object parseConfig(String value) { 25 | int valueAsInt = Integer.parseInt(value, 16); 26 | if (valueAsInt == Argon2Parameters.ARGON2_VERSION_10 || valueAsInt == Argon2Parameters.ARGON2_VERSION_13) { 27 | return valueAsInt; 28 | } else { 29 | throw new PasswordPolicyConfigException(String.format("Invalid Argon2 version, valid choices are: '%h' or '%h'.", Argon2Parameters.ARGON2_VERSION_10, Argon2Parameters.ARGON2_VERSION_13)); 30 | } 31 | } 32 | 33 | @Override 34 | public String getDefaultConfigValue() { 35 | return String.format("%h", DEFAULT_VERSION); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/be/cronos/keycloak/utils/Argon2EncodingUtils.java: -------------------------------------------------------------------------------- 1 | package be.cronos.keycloak.utils; 2 | 3 | import be.cronos.keycloak.enums.Argon2Variant; 4 | import be.cronos.keycloak.exceptions.Argon2RuntimeException; 5 | import be.cronos.keycloak.policy.Argon2HashLengthPasswordPolicyProviderFactory; 6 | import be.cronos.keycloak.policy.Argon2SaltLengthPasswordPolicyProviderFactory; 7 | import org.jboss.logging.Logger; 8 | 9 | import java.util.Base64; 10 | 11 | /** 12 | * @author Dries Eestermans 13 | */ 14 | public class Argon2EncodingUtils { 15 | private static final Logger LOG = Logger.getLogger(Argon2EncodingUtils.class); 16 | 17 | private Argon2EncodingUtils() { 18 | // noop 19 | } 20 | 21 | public static String extractDigest(String encodedPassword) { 22 | String[] explodedEncodedPassword = encodedPassword.split("\\$"); 23 | if (explodedEncodedPassword.length == 0) return null; 24 | // Digest is always the last value in the split 25 | return explodedEncodedPassword[explodedEncodedPassword.length-1]; 26 | } 27 | 28 | public static Argon2EncodingUtils.Argon2Parameters extractArgon2ParametersFromEncodedPassword(String encodedPassword) { 29 | // Declare separate fields which are contained within the encoded password hash 30 | Argon2Variant storedArgon2Variant; 31 | int version; 32 | int memory; 33 | int iterations; 34 | int parallelism; 35 | int hashLength; 36 | // Now attempt to extract all the parameters 37 | try { 38 | storedArgon2Variant = Argon2Variant.parseVariant(encodedPassword.split("\\$")[1]); 39 | version = extractVersion(encodedPassword); 40 | memory = extractMemory(encodedPassword); 41 | iterations = extractIterations(encodedPassword); 42 | parallelism = extractParallelism(encodedPassword); 43 | hashLength = getDigestLength(extractDigest(encodedPassword)); 44 | if (storedArgon2Variant == null) throw new Argon2RuntimeException("Unknown stored Argon2 variant"); 45 | } catch (Exception e) { 46 | throw new Argon2RuntimeException(e.getMessage()); 47 | } 48 | // If we reach this point, all parameters were found and we return the Argon2Parameters carry object 49 | return new Argon2EncodingUtils.Argon2Parameters(storedArgon2Variant, version, memory, iterations, parallelism, hashLength); 50 | } 51 | 52 | public static int extractVersion(String encodedPassword) { 53 | int version; 54 | try { 55 | String[] exploded = encodedPassword.split("\\$"); 56 | String versionPart = exploded[2]; 57 | version = Integer.parseInt(versionPart.split("=")[1]); 58 | } catch (Exception e) { 59 | LOG.errorf("Error parsing version from encoded hash: %s", e.getMessage()); 60 | throw new Argon2RuntimeException("Could not extract version from encoded hash."); 61 | } 62 | return version; 63 | } 64 | 65 | public static int extractMemory(String encodedPassword) { 66 | return Integer.parseInt(extractValue( 67 | extractParameter(encodedPassword, 0) 68 | )); 69 | } 70 | 71 | public static int extractIterations(String encodedPassword) { 72 | return Integer.parseInt(extractValue( 73 | extractParameter(encodedPassword, 1) 74 | )); 75 | } 76 | 77 | public static int extractParallelism(String encodedPassword) { 78 | return Integer.parseInt(extractValue( 79 | extractParameter(encodedPassword, 2) 80 | )); 81 | } 82 | 83 | public static int getDigestLength(String base64EncodedString) { 84 | return Base64.getDecoder().decode(base64EncodedString).length; 85 | } 86 | 87 | private static String extractParameter(String encodedPassword, int index) { 88 | String parameters = extractParameters(encodedPassword); 89 | String[] explodedParameters = parameters.split(","); 90 | if (explodedParameters.length != 3) throw new Argon2RuntimeException("Encoded hash parameters did not split in 3."); 91 | return explodedParameters[index]; 92 | } 93 | 94 | private static String extractParameters(String encodedPassword) { 95 | try { 96 | return encodedPassword.split("\\$")[3]; 97 | } catch (Exception e) { 98 | LOG.errorf("Failed to extract parameters from encoded hash."); 99 | throw new Argon2RuntimeException("Failed to extract parameters from encoded hash."); 100 | } 101 | } 102 | 103 | private static String extractValue(String parameter) { 104 | String[] explodedParameter = parameter.split("="); 105 | if (explodedParameter.length != 2) throw new Argon2RuntimeException(String.format("'%s' is not a valid 'key=value' parameter.", parameter)); 106 | return explodedParameter[1]; 107 | } 108 | 109 | public static class Argon2Parameters { 110 | private final Argon2Variant argon2Variant; 111 | private final int version; 112 | private final int memory; 113 | private final int iterations; 114 | private final int parallelism; 115 | private final int hashLength; 116 | private final int saltLength; 117 | 118 | public Argon2Parameters(Argon2Variant argon2Variant, int version, int memory, int iterations, int parallelism) { 119 | this(argon2Variant, version, memory, iterations, parallelism, Argon2HashLengthPasswordPolicyProviderFactory.DEFAULT_HASH_LENGTH, Argon2SaltLengthPasswordPolicyProviderFactory.DEFAULT_SALT_LENGTH); 120 | } 121 | 122 | public Argon2Parameters(Argon2Variant argon2Variant, int version, int memory, int iterations, int parallelism, int hashLength) { 123 | this(argon2Variant, version, memory, iterations, parallelism, hashLength, Argon2SaltLengthPasswordPolicyProviderFactory.DEFAULT_SALT_LENGTH); 124 | } 125 | 126 | public Argon2Parameters(Argon2Variant argon2Variant, int version, int memory, int iterations, int parallelism, int hashLength, int saltLength) { 127 | this.argon2Variant = argon2Variant; 128 | this.version = version; 129 | this.memory = memory; 130 | this.iterations = iterations; 131 | this.parallelism = parallelism; 132 | this.hashLength = hashLength; 133 | this.saltLength = saltLength; 134 | } 135 | 136 | public Argon2Variant getArgon2Variant() { 137 | return argon2Variant; 138 | } 139 | 140 | public int getVersion() { 141 | return version; 142 | } 143 | 144 | public int getMemory() { 145 | return memory; 146 | } 147 | 148 | public int getIterations() { 149 | return iterations; 150 | } 151 | 152 | public int getParallelism() { 153 | return parallelism; 154 | } 155 | 156 | public int getHashLength() { 157 | return hashLength; 158 | } 159 | 160 | public int getSaltLength() { 161 | return saltLength; 162 | } 163 | } 164 | } 165 | -------------------------------------------------------------------------------- /src/main/java/be/cronos/keycloak/utils/Argon2Helper.java: -------------------------------------------------------------------------------- 1 | package be.cronos.keycloak.utils; 2 | 3 | import be.cronos.keycloak.enums.Argon2Variant; 4 | import be.cronos.keycloak.exceptions.Argon2RuntimeException; 5 | import org.bouncycastle.crypto.generators.Argon2BytesGenerator; 6 | import org.bouncycastle.crypto.params.Argon2Parameters; 7 | import org.bouncycastle.util.Strings; 8 | import org.jboss.logging.Logger; 9 | import org.keycloak.models.credential.PasswordCredentialModel; 10 | 11 | import java.security.MessageDigest; 12 | import java.security.SecureRandom; 13 | import java.util.Base64; 14 | 15 | /** 16 | * @author Dries Eestermans 17 | */ 18 | public class Argon2Helper { 19 | private static final Logger LOG = Logger.getLogger(Argon2Helper.class); 20 | 21 | private Argon2Helper() { 22 | throw new IllegalStateException("Helper class"); 23 | } 24 | 25 | public static String hashPassword(String rawPassword, byte[] salt, Argon2Variant argon2Variant, int version, 26 | int iterations, int parallelism, int memoryLimit, int hashLength) { 27 | 28 | if (rawPassword == null) throw new Argon2RuntimeException("Password can't be empty"); 29 | 30 | // Validate whether the version is valid 31 | if (version != org.bouncycastle.crypto.params.Argon2Parameters.ARGON2_VERSION_10 && version != org.bouncycastle.crypto.params.Argon2Parameters.ARGON2_VERSION_13) 32 | throw new Argon2RuntimeException("Invalid version"); 33 | 34 | LOG.debugf("Using the following Argon2 settings:"); 35 | LOG.debugf("\tArgon2 Variant: %s", argon2Variant.getArgon2VariantStringRepr()); 36 | LOG.debugf("\tIterations: %d", iterations); 37 | LOG.debugf("\tVersion: %h", version); 38 | LOG.debugf("\tParallelism: %d", parallelism); 39 | LOG.debugf("\tMemory limit: %d", memoryLimit); 40 | LOG.debugf("\tHash Length: %d", hashLength); 41 | LOG.debugf("\tSalt Length: %d", salt.length); 42 | 43 | try { 44 | // Construct the Argon2 Parameters Builder 45 | Argon2Parameters.Builder builder = new Argon2Parameters.Builder(argon2Variant.getArgon2BouncyCastle()) 46 | .withSalt(salt) 47 | .withVersion(version) 48 | .withIterations(iterations) 49 | .withParallelism(parallelism) 50 | .withMemoryAsKB(memoryLimit); 51 | 52 | // Initialize BouncyCastle's Argon2 generator 53 | Argon2BytesGenerator generator = new Argon2BytesGenerator(); 54 | 55 | // Initialize the digest generator 56 | generator.init(builder.build()); 57 | 58 | // Digest bytes result output 59 | byte[] result = new byte[hashLength]; 60 | 61 | // Keep track of hashing runtime 62 | long start = System.currentTimeMillis(); 63 | 64 | // Perform the hashing 65 | generator.generateBytes(rawPassword.toCharArray(), result, 0, result.length); 66 | 67 | // Stop timing 68 | long end = System.currentTimeMillis(); 69 | 70 | // Print the hashing runtime for debug purposes 71 | LOG.debugf("Hashing runtime was %d milliseconds (%d seconds).", end-start, (end-start)/1000); 72 | 73 | // Return an encoded representation of the argon2 password hash 74 | return String.format("$%s$v=%d$m=%d,t=%d,p=%d$%s$%s", 75 | argon2Variant.getArgon2VariantStringRepr(), 76 | version, 77 | memoryLimit, 78 | iterations, 79 | parallelism, 80 | Base64.getEncoder().withoutPadding().encodeToString(salt), 81 | Base64.getEncoder().withoutPadding().encodeToString(result) 82 | ); 83 | } catch (Exception e) { 84 | LOG.errorf("Something went wrong while hashing the password, message = '%s'", e.getMessage()); 85 | } 86 | throw new Argon2RuntimeException("Something went wrong while securing the password."); 87 | } 88 | 89 | public static boolean verifyPassword(String rawPassword, PasswordCredentialModel credential) { 90 | // Get the Argon2 parameters of the credential, should be something like: 91 | // $argon2i$v=19$m=65535,t=30,p=4$JQUxqirAz7+Em0yM1ZiDFA$LhqtL0XPGESfeHb4lI2XnV4mSZacWGQWANKtvIVVpy4 92 | // Retrieve the stored encoded password 93 | String storedEncodedPassword = credential.getPasswordSecretData().getValue(); 94 | // Retrieved the salt 95 | byte[] salt = credential.getPasswordSecretData().getSalt(); 96 | // Extract all the stored parameters 97 | Argon2EncodingUtils.Argon2Parameters argon2Parameters = Argon2EncodingUtils.extractArgon2ParametersFromEncodedPassword(storedEncodedPassword); 98 | 99 | // Extract the digest 100 | String storedPasswordDigest = Argon2EncodingUtils.extractDigest(storedEncodedPassword); 101 | if (storedPasswordDigest == null) { 102 | LOG.errorf("There's something wrong with the stored password encoding, couldn't find the actual hash."); 103 | throw new Argon2RuntimeException("Something went wrong."); 104 | } 105 | 106 | // Hash the incoming password (according to stored password's parameters) 107 | String attemptedEncodedPassword = hashPassword( 108 | rawPassword, 109 | salt, 110 | argon2Parameters.getArgon2Variant(), 111 | argon2Parameters.getVersion(), 112 | argon2Parameters.getIterations(), 113 | argon2Parameters.getParallelism(), 114 | argon2Parameters.getMemory(), 115 | argon2Parameters.getHashLength() 116 | ); 117 | 118 | // Extract the digest of the attempted hashed password 119 | String attemptedPasswordDigest = Argon2EncodingUtils.extractDigest(attemptedEncodedPassword); 120 | if (attemptedPasswordDigest == null) { 121 | LOG.errorf("There's something wrong with the attempted password encoding, couldn't find the actual hash."); 122 | throw new Argon2RuntimeException("Something went wrong."); 123 | } 124 | 125 | // Compare the 2 digests using constant-time comparison 126 | boolean samePassword = MessageDigest.isEqual(Strings.toByteArray(storedPasswordDigest), Strings.toByteArray(attemptedPasswordDigest)); 127 | 128 | LOG.debugf("Password match = %s", String.valueOf(samePassword)); 129 | 130 | return samePassword; 131 | } 132 | 133 | public static byte[] getSalt(int saltLength) { 134 | LOG.debugf("Generating salt with length '%d'.", saltLength); 135 | byte[] buffer = new byte[saltLength]; 136 | SecureRandom secureRandom = new SecureRandom(); 137 | secureRandom.nextBytes(buffer); 138 | return buffer; 139 | } 140 | } 141 | -------------------------------------------------------------------------------- /src/main/resources/META-INF/jboss-deployment-structure.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /src/main/resources/META-INF/services/org.keycloak.credential.hash.PasswordHashProviderFactory: -------------------------------------------------------------------------------- 1 | be.cronos.keycloak.credential.hash.Argon2PasswordHashProviderFactory 2 | -------------------------------------------------------------------------------- /src/main/resources/META-INF/services/org.keycloak.policy.PasswordPolicyProviderFactory: -------------------------------------------------------------------------------- 1 | be.cronos.keycloak.policy.Argon2MemoryPasswordPolicyProviderFactory 2 | be.cronos.keycloak.policy.Argon2ParallelismPasswordPolicyProviderFactory 3 | be.cronos.keycloak.policy.Argon2VariantPasswordPolicyProviderFactory 4 | be.cronos.keycloak.policy.Argon2IterationsPasswordPolicyProviderFactory 5 | be.cronos.keycloak.policy.Argon2SaltLengthPasswordPolicyProviderFactory 6 | be.cronos.keycloak.policy.Argon2HashLengthPasswordPolicyProviderFactory 7 | be.cronos.keycloak.policy.Argon2MaxTimePasswordPolicyProviderFactory 8 | be.cronos.keycloak.policy.Argon2VersionPasswordPolicyProviderFactory -------------------------------------------------------------------------------- /src/test/java/be/cronos/keycloak/utils/Argon2HelperTest.java: -------------------------------------------------------------------------------- 1 | package be.cronos.keycloak.utils; 2 | 3 | import be.cronos.keycloak.credential.hash.Argon2PasswordHashProviderFactory; 4 | import be.cronos.keycloak.enums.Argon2Variant; 5 | import be.cronos.keycloak.policy.Argon2HashLengthPasswordPolicyProviderFactory; 6 | import org.bouncycastle.crypto.params.Argon2Parameters; 7 | import org.junit.Assert; 8 | import org.junit.Before; 9 | import org.junit.Test; 10 | import org.keycloak.models.credential.PasswordCredentialModel; 11 | 12 | import java.util.Base64; 13 | 14 | /** 15 | * @author Dries Eestermans 16 | */ 17 | public class Argon2HelperTest { 18 | private static final String ALGORITHM = Argon2PasswordHashProviderFactory.ID; 19 | private static final int DEFAULT_ITERATIONS = 1; 20 | 21 | private static final int DEFAULT_MEMORY = 65536; 22 | 23 | private static final int DEFAULT_PARALLELISM = 1; 24 | 25 | private static byte[] salt; 26 | 27 | @Before 28 | public void generateSalt() { 29 | salt = Argon2Helper.getSalt(16); 30 | } 31 | 32 | // region: argon2d 33 | @Test 34 | public void testArgon2dHashAndVerifySamePassword() { 35 | Argon2Variant argon2Variant = Argon2Variant.ARGON2D; 36 | int iterations = DEFAULT_ITERATIONS; 37 | String rawPassword = "testargon2d"; 38 | String hash = Argon2Helper.hashPassword(rawPassword, salt, argon2Variant, Argon2Parameters.ARGON2_VERSION_13, iterations, DEFAULT_PARALLELISM, DEFAULT_MEMORY, Argon2HashLengthPasswordPolicyProviderFactory.DEFAULT_HASH_LENGTH); 39 | PasswordCredentialModel passwordCredentialModel = PasswordCredentialModel.createFromValues(ALGORITHM, salt, iterations, hash); 40 | passwordCredentialModel.setSecretData(hash); 41 | boolean verified = Argon2Helper.verifyPassword(rawPassword, passwordCredentialModel); 42 | Assert.assertTrue(verified); 43 | } 44 | 45 | @Test 46 | public void testArgon2dHashAndVerifyDifferentPassword() { 47 | Argon2Variant argon2Variant = Argon2Variant.ARGON2D; 48 | int iterations = DEFAULT_ITERATIONS; 49 | String rawPassword = "testargon2d"; 50 | String hash = Argon2Helper.hashPassword(rawPassword, salt, argon2Variant, Argon2Parameters.ARGON2_VERSION_13, iterations, DEFAULT_PARALLELISM, DEFAULT_MEMORY, Argon2HashLengthPasswordPolicyProviderFactory.DEFAULT_HASH_LENGTH); 51 | PasswordCredentialModel passwordCredentialModel = PasswordCredentialModel.createFromValues(ALGORITHM, salt, iterations, hash); 52 | passwordCredentialModel.setSecretData(hash); 53 | boolean verified = Argon2Helper.verifyPassword("different", passwordCredentialModel); 54 | Assert.assertFalse(verified); 55 | } 56 | 57 | @Test 58 | public void testArgon2dVerifyPredefinedHash() { 59 | String rawPassword = "testargon2d"; 60 | String hash = "$argon2d$v=19$m=65536,t=1,p=1$v3evK1HhIHKHRnRNWqEfZA$T7G+ujnDpZN+kYuMngOb/2+/mIDpOn0VyLIh7B6LJiY"; 61 | PasswordCredentialModel passwordCredentialModel = PasswordCredentialModel.createFromValues(ALGORITHM, Base64.getDecoder().decode("v3evK1HhIHKHRnRNWqEfZA"), DEFAULT_ITERATIONS, hash); 62 | passwordCredentialModel.setSecretData(hash); 63 | boolean verified = Argon2Helper.verifyPassword(rawPassword, passwordCredentialModel); 64 | Assert.assertTrue(verified); 65 | } 66 | 67 | @Test 68 | public void testArgon2dVerifyPredefinedWrongHash() { 69 | String rawPassword = "wrongpassword"; 70 | String hash = "$argon2d$v=19$m=65536,t=1,p=1$v3evK1HhIHKHRnRNWqEfZA$T7G+ujnDpZN+kYuMngOb/2+/mIDpOn0VyLIh7B6LJiY"; 71 | PasswordCredentialModel passwordCredentialModel = PasswordCredentialModel.createFromValues(ALGORITHM, "".getBytes(), DEFAULT_ITERATIONS, hash); 72 | passwordCredentialModel.setSecretData(hash); 73 | boolean verified = Argon2Helper.verifyPassword(rawPassword, passwordCredentialModel); 74 | Assert.assertFalse(verified); 75 | } 76 | 77 | @Test 78 | public void testArgon2dVerifyPredefinedWrongSalt() { 79 | String rawPassword = "testargon2d"; 80 | String hash = "$argon2d$v=19$m=65536,t=1,p=1$v3evK1HhIHKHRnRNWqEfZA$T7G+ujnDpZN+kYuMngOb/2+/mIDpOn0VyLIh7B6LJiY"; 81 | PasswordCredentialModel passwordCredentialModel = PasswordCredentialModel.createFromValues(ALGORITHM, salt, DEFAULT_ITERATIONS, hash); 82 | passwordCredentialModel.setSecretData(hash); 83 | boolean verified = Argon2Helper.verifyPassword(rawPassword, passwordCredentialModel); 84 | Assert.assertFalse(verified); 85 | } 86 | 87 | // endregion: argon2d 88 | 89 | // region: argon2i 90 | @Test 91 | public void testArgon2iHashAndVerifySamePassword() { 92 | Argon2Variant argon2Variant = Argon2Variant.ARGON2I; 93 | String rawPassword = "testargon2i"; 94 | String hash = Argon2Helper.hashPassword(rawPassword, salt, argon2Variant, Argon2Parameters.ARGON2_VERSION_13, DEFAULT_ITERATIONS, DEFAULT_PARALLELISM, DEFAULT_MEMORY, Argon2HashLengthPasswordPolicyProviderFactory.DEFAULT_HASH_LENGTH); 95 | PasswordCredentialModel passwordCredentialModel = PasswordCredentialModel.createFromValues(ALGORITHM, salt, DEFAULT_ITERATIONS, hash); 96 | passwordCredentialModel.setSecretData(hash); 97 | boolean verified = Argon2Helper.verifyPassword(rawPassword, passwordCredentialModel); 98 | Assert.assertTrue(verified); 99 | } 100 | 101 | @Test 102 | public void testArgon2iHashAndVerifyDifferentPassword() { 103 | Argon2Variant argon2Variant = Argon2Variant.ARGON2I; 104 | String rawPassword = "testargon2i"; 105 | String hash = Argon2Helper.hashPassword(rawPassword, salt, argon2Variant, Argon2Parameters.ARGON2_VERSION_13, DEFAULT_ITERATIONS, DEFAULT_PARALLELISM, DEFAULT_MEMORY, Argon2HashLengthPasswordPolicyProviderFactory.DEFAULT_HASH_LENGTH); 106 | PasswordCredentialModel passwordCredentialModel = PasswordCredentialModel.createFromValues(ALGORITHM, salt, DEFAULT_ITERATIONS, hash); 107 | passwordCredentialModel.setSecretData(hash); 108 | boolean verified = Argon2Helper.verifyPassword("different", passwordCredentialModel); 109 | Assert.assertFalse(verified); 110 | } 111 | 112 | @Test 113 | public void testArgon2iVerifyPredefinedHash() { 114 | String rawPassword = "testargon2i"; 115 | String hash = "$argon2i$v=19$m=65536,t=1,p=1$81E/xOo/2OUX15UAJgI3Eg$0Z83Ag5oE9MCEEVGL9NJNg6oFIVbU/FhpQkyyX+RNz0"; 116 | PasswordCredentialModel passwordCredentialModel = PasswordCredentialModel.createFromValues(ALGORITHM, Base64.getDecoder().decode("81E/xOo/2OUX15UAJgI3Eg"), DEFAULT_ITERATIONS, hash); 117 | passwordCredentialModel.setSecretData(hash); 118 | boolean verified = Argon2Helper.verifyPassword(rawPassword, passwordCredentialModel); 119 | Assert.assertTrue(verified); 120 | } 121 | 122 | @Test 123 | public void testArgon2iVerifyPredefinedWrongHash() { 124 | String rawPassword = "wrongpassword"; 125 | String hash = "$argon2i$v=19$m=65536,t=1,p=1$81E/xOo/2OUX15UAJgI3Eg$0Z83Ag5oE9MCEEVGL9NJNg6oFIVbU/FhpQkyyX+RNz0"; 126 | PasswordCredentialModel passwordCredentialModel = PasswordCredentialModel.createFromValues(ALGORITHM, Base64.getDecoder().decode("81E/xOo/2OUX15UAJgI3Eg"), DEFAULT_ITERATIONS, hash); 127 | passwordCredentialModel.setSecretData(hash); 128 | boolean verified = Argon2Helper.verifyPassword(rawPassword, passwordCredentialModel); 129 | Assert.assertFalse(verified); 130 | } 131 | 132 | @Test 133 | public void testArgon2iVerifyPredefinedWrongSalt() { 134 | String rawPassword = "testargon2i"; 135 | String hash = "$argon2i$v=19$m=65536,t=1,p=1$81E/xOo/2OUX15UAJgI3Eg$0Z83Ag5oE9MCEEVGL9NJNg6oFIVbU/FhpQkyyX+RNz0"; 136 | PasswordCredentialModel passwordCredentialModel = PasswordCredentialModel.createFromValues(ALGORITHM, salt, DEFAULT_ITERATIONS, hash); 137 | passwordCredentialModel.setSecretData(hash); 138 | boolean verified = Argon2Helper.verifyPassword(rawPassword, passwordCredentialModel); 139 | Assert.assertFalse(verified); 140 | } 141 | // endregion: argon2i 142 | 143 | // region: argon2id 144 | @Test 145 | public void testArgon2idHashAndVerifySamePassword() { 146 | Argon2Variant argon2Variant = Argon2Variant.ARGON2ID; 147 | String rawPassword = "testargon2id"; 148 | String hash = Argon2Helper.hashPassword(rawPassword, salt, argon2Variant, Argon2Parameters.ARGON2_VERSION_13, DEFAULT_ITERATIONS, DEFAULT_PARALLELISM, DEFAULT_MEMORY, Argon2HashLengthPasswordPolicyProviderFactory.DEFAULT_HASH_LENGTH); 149 | PasswordCredentialModel passwordCredentialModel = PasswordCredentialModel.createFromValues(ALGORITHM, salt, DEFAULT_ITERATIONS, hash); 150 | passwordCredentialModel.setSecretData(hash); 151 | boolean verified = Argon2Helper.verifyPassword(rawPassword, passwordCredentialModel); 152 | Assert.assertTrue(verified); 153 | } 154 | 155 | @Test 156 | public void testArgon2idHashAndVerifyDifferentPassword() { 157 | Argon2Variant argon2Variant = Argon2Variant.ARGON2ID; 158 | String rawPassword = "testargon2id"; 159 | String hash = Argon2Helper.hashPassword(rawPassword, salt, argon2Variant, Argon2Parameters.ARGON2_VERSION_13, DEFAULT_ITERATIONS, DEFAULT_PARALLELISM, DEFAULT_MEMORY, Argon2HashLengthPasswordPolicyProviderFactory.DEFAULT_HASH_LENGTH); 160 | PasswordCredentialModel passwordCredentialModel = PasswordCredentialModel.createFromValues(ALGORITHM, salt, DEFAULT_ITERATIONS, hash); 161 | passwordCredentialModel.setSecretData(hash); 162 | boolean verified = Argon2Helper.verifyPassword("different", passwordCredentialModel); 163 | Assert.assertFalse(verified); 164 | } 165 | 166 | @Test 167 | public void testArgon2idVerifyPredefinedHash() { 168 | String rawPassword = "testargon2id"; 169 | String hash = "$argon2id$v=19$m=65536,t=1,p=1$zGFM95kyhWZyZv1Hhvjuog$G78Vd4nXEqN0DKbF+qGj1pUNyEpEZmOWqEqlHFDllJY"; 170 | PasswordCredentialModel passwordCredentialModel = PasswordCredentialModel.createFromValues(ALGORITHM, Base64.getDecoder().decode("zGFM95kyhWZyZv1Hhvjuog"), DEFAULT_ITERATIONS, hash); 171 | passwordCredentialModel.setSecretData(hash); 172 | boolean verified = Argon2Helper.verifyPassword(rawPassword, passwordCredentialModel); 173 | Assert.assertTrue(verified); 174 | } 175 | 176 | @Test 177 | public void testArgon2idVerifyPredefinedWrongHash() { 178 | String rawPassword = "wrongpassword"; 179 | String hash = "$argon2i$v=19$m=65536,t=1,p=1$81E/xOo/2OUX15UAJgI3Eg$0Z83Ag5oE9MCEEVGL9NJNg6oFIVbU/FhpQkyyX+RNz0"; 180 | PasswordCredentialModel passwordCredentialModel = PasswordCredentialModel.createFromValues(ALGORITHM, Base64.getDecoder().decode("81E/xOo/2OUX15UAJgI3Eg"), DEFAULT_ITERATIONS, hash); 181 | passwordCredentialModel.setSecretData(hash); 182 | boolean verified = Argon2Helper.verifyPassword(rawPassword, passwordCredentialModel); 183 | Assert.assertFalse(verified); 184 | } 185 | 186 | @Test 187 | public void testArgon2idVerifyPredefinedWrongSalt() { 188 | String rawPassword = "testargon2id"; 189 | String hash = "$argon2id$v=19$m=65536,t=1,p=1$zGFM95kyhWZyZv1Hhvjuog$G78Vd4nXEqN0DKbF+qGj1pUNyEpEZmOWqEqlHFDllJY"; 190 | PasswordCredentialModel passwordCredentialModel = PasswordCredentialModel.createFromValues(ALGORITHM, salt, DEFAULT_ITERATIONS, hash); 191 | passwordCredentialModel.setSecretData(hash); 192 | boolean verified = Argon2Helper.verifyPassword(rawPassword, passwordCredentialModel); 193 | Assert.assertFalse(verified); 194 | } 195 | // endregion: argon2id 196 | 197 | // region: runtime exceptions 198 | @Test(expected = RuntimeException.class) 199 | public void testHashPasswordHashEmptyPassword() { 200 | Argon2Variant argon2Variant = Argon2Variant.ARGON2ID; 201 | String rawPassword = null; 202 | String hash = Argon2Helper.hashPassword(rawPassword, salt, argon2Variant, Argon2Parameters.ARGON2_VERSION_13, DEFAULT_ITERATIONS, DEFAULT_PARALLELISM, DEFAULT_MEMORY, Argon2HashLengthPasswordPolicyProviderFactory.DEFAULT_HASH_LENGTH); 203 | } 204 | 205 | @Test(expected = RuntimeException.class) 206 | public void testHashPasswordNoAlgorithm() { 207 | String rawPassword = "novariantdefined"; 208 | String tamperedHash = "$$v=19$m=65536,t=1,p=1$zGFM95kyhWZyZv1Hhvjuog$G78Vd4nXEqN0DKbF+qGj1pUNyEpEZmOWqEqlHFDllJY"; 209 | PasswordCredentialModel passwordCredentialModel = PasswordCredentialModel.createFromValues(ALGORITHM, salt, DEFAULT_ITERATIONS, tamperedHash); 210 | passwordCredentialModel.setSecretData(tamperedHash); 211 | Argon2Helper.verifyPassword(rawPassword, passwordCredentialModel); 212 | } 213 | 214 | @Test(expected = RuntimeException.class) 215 | public void testHashPasswordNegativeIterations() { 216 | Argon2Variant argon2Variant = Argon2Variant.ARGON2ID; 217 | int iterations = -1; 218 | String rawPassword = "novariantdefined"; 219 | String hash = Argon2Helper.hashPassword(rawPassword, salt, argon2Variant, Argon2Parameters.ARGON2_VERSION_13, iterations, DEFAULT_PARALLELISM, DEFAULT_MEMORY, Argon2HashLengthPasswordPolicyProviderFactory.DEFAULT_HASH_LENGTH); 220 | } 221 | 222 | @Test(expected = RuntimeException.class) 223 | public void testHashPasswordInvalidVersion() { 224 | Argon2Variant argon2Variant = Argon2Variant.ARGON2ID; 225 | int version = 0x16; 226 | String rawPassword = "invalidversion"; 227 | String hash = Argon2Helper.hashPassword(rawPassword, salt, argon2Variant, version, DEFAULT_ITERATIONS, DEFAULT_PARALLELISM, DEFAULT_MEMORY, Argon2HashLengthPasswordPolicyProviderFactory.DEFAULT_HASH_LENGTH); 228 | } 229 | 230 | @Test(expected = RuntimeException.class) 231 | public void testHashPasswordNoParallelism() { 232 | Argon2Variant argon2Variant = Argon2Variant.ARGON2ID; 233 | int parallelism = 0; 234 | String rawPassword = "novariantdefined"; 235 | String hash = Argon2Helper.hashPassword(rawPassword, salt, argon2Variant, Argon2Parameters.ARGON2_VERSION_13, DEFAULT_ITERATIONS, parallelism, DEFAULT_MEMORY, Argon2HashLengthPasswordPolicyProviderFactory.DEFAULT_HASH_LENGTH); 236 | } 237 | 238 | @Test(expected = RuntimeException.class) 239 | public void testHashPasswordNoMemory() { 240 | Argon2Variant argon2Variant = Argon2Variant.ARGON2ID; 241 | int memory = 0; 242 | String rawPassword = "novariantdefined"; 243 | String hash = Argon2Helper.hashPassword(rawPassword, salt, argon2Variant, Argon2Parameters.ARGON2_VERSION_13, DEFAULT_ITERATIONS, DEFAULT_PARALLELISM, memory, Argon2HashLengthPasswordPolicyProviderFactory.DEFAULT_HASH_LENGTH); 244 | } 245 | 246 | @Test(expected = RuntimeException.class) 247 | public void testVerifyPasswordInvalidAlgorithm() { 248 | String rawPassword = "testargon2id"; 249 | String hash = "$argon2idd$v=19$m=65536,t=1,p=1$zGFM95kyhWZyZv1Hhvjuog$G78Vd4nXEqN0DKbF+qGj1pUNyEpEZmOWqEqlHFDllJY"; 250 | PasswordCredentialModel passwordCredentialModel = PasswordCredentialModel.createFromValues(ALGORITHM, "".getBytes(), DEFAULT_ITERATIONS, hash); 251 | passwordCredentialModel.setSecretData(hash); 252 | boolean verified = Argon2Helper.verifyPassword(rawPassword, passwordCredentialModel); 253 | } 254 | 255 | @Test(expected = RuntimeException.class) 256 | public void testVerifyPasswordNonsenseData() { 257 | String rawPassword = "testargon2id"; 258 | String hash = "nonsense"; 259 | PasswordCredentialModel passwordCredentialModel = PasswordCredentialModel.createFromValues(ALGORITHM, "".getBytes(), DEFAULT_ITERATIONS, hash); 260 | passwordCredentialModel.setSecretData(hash); 261 | boolean verified = Argon2Helper.verifyPassword(rawPassword, passwordCredentialModel); 262 | } 263 | // endregion: runtime exceptions 264 | 265 | // region: wrong algorithm in hash 266 | 267 | @Test() 268 | public void testVerifyPasswordIncorrectAlgorithm() { 269 | String rawPassword = "testargon2id"; 270 | // it should argon2id 271 | String hash = "$argon2i$v=19$m=65536,t=1,p=1$zGFM95kyhWZyZv1Hhvjuog$G78Vd4nXEqN0DKbF+qGj1pUNyEpEZmOWqEqlHFDllJY"; 272 | PasswordCredentialModel passwordCredentialModel = PasswordCredentialModel.createFromValues(ALGORITHM, Base64.getDecoder().decode("zGFM95kyhWZyZv1Hhvjuog"), DEFAULT_ITERATIONS, hash); 273 | passwordCredentialModel.setSecretData(hash); 274 | boolean verified = Argon2Helper.verifyPassword(rawPassword, passwordCredentialModel); 275 | Assert.assertFalse(verified); 276 | } 277 | 278 | // endregion: wrong algorithm in hash 279 | 280 | } 281 | --------------------------------------------------------------------------------