├── .gitignore ├── lib ├── settings.gradle ├── gradle │ └── wrapper │ │ ├── gradle-wrapper.jar │ │ └── gradle-wrapper.properties ├── bintray-config.gradle ├── .gitignore ├── src │ └── main │ │ └── java │ │ └── com │ │ └── bolyartech │ │ └── scram_sasl │ │ ├── common │ │ ├── ScramException.java │ │ ├── Normalizer.java │ │ ├── ScramUtils.java │ │ └── StringPrep.java │ │ ├── client │ │ ├── ScramSha1SaslClientProcessor.java │ │ ├── ScramSha256SaslClientProcessor.java │ │ ├── ScramSha512SaslClientProcessor.java │ │ ├── ScramSaslClientProcessor.java │ │ ├── ScramClientFunctionality.java │ │ ├── AbstractScramSaslClientProcessor.java │ │ └── ScramClientFunctionalityImpl.java │ │ └── server │ │ ├── ScramSha1SaslServerProcessor.java │ │ ├── ScramSha256SaslServerProcessor.java │ │ ├── ScramSha512SaslServerProcessor.java │ │ ├── UserData.java │ │ ├── ScramServerFunctionality.java │ │ ├── ScramSaslServerProcessor.java │ │ ├── ScramServerFunctionalityImpl.java │ │ └── AbstractScramSaslServerProcessor.java ├── gradlew.bat ├── build.gradle └── gradlew ├── examples ├── gradle │ └── wrapper │ │ ├── gradle-wrapper.jar │ │ └── gradle-wrapper.properties ├── settings.gradle ├── .gitignore ├── build.gradle ├── gradlew.bat ├── src │ └── main │ │ └── java │ │ └── com │ │ └── bolyartech │ │ └── scram_sasl │ │ └── examples │ │ ├── ScramSha1Example.java │ │ └── ScramSha256Example.java └── gradlew ├── LICENSE └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | .idea 2 | -------------------------------------------------------------------------------- /lib/settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'scram_sasl' 2 | 3 | -------------------------------------------------------------------------------- /lib/gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ogrebgr/scram-sasl/HEAD/lib/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /examples/gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ogrebgr/scram-sasl/HEAD/examples/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /examples/settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'SCRAM SASL Examples' 2 | 3 | include ':scram_sasl' 4 | project(':scram_sasl').projectDir=new File("$settingsDir/../lib") 5 | -------------------------------------------------------------------------------- /lib/bintray-config.gradle: -------------------------------------------------------------------------------- 1 | def fileBc = new File( '/home/ogre/.signing/bintray-config.gradle' ) 2 | 3 | if (fileBc.exists()) { 4 | apply from: '/home/ogre/.signing/bintray-config.gradle' 5 | } 6 | -------------------------------------------------------------------------------- /lib/.gitignore: -------------------------------------------------------------------------------- 1 | .gradle 2 | /local.properties 3 | /.idea/workspace.xml 4 | /.idea/libraries 5 | .DS_Store 6 | /build 7 | /captures 8 | logs 9 | .idea 10 | *.iml 11 | /src/main/resources/logback.xml 12 | /src/main/resources/server.conf 13 | /src/main/resources/keystore 14 | conf/ 15 | -------------------------------------------------------------------------------- /examples/.gitignore: -------------------------------------------------------------------------------- 1 | .gradle 2 | /local.properties 3 | /.idea/workspace.xml 4 | /.idea/libraries 5 | .DS_Store 6 | /build 7 | /captures 8 | logs 9 | .idea 10 | *.iml 11 | /src/main/resources/logback.xml 12 | /src/main/resources/server.conf 13 | /src/main/resources/keystore 14 | conf/ 15 | -------------------------------------------------------------------------------- /lib/gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Sat Apr 17 12:31:36 EEST 2021 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | distributionUrl=https\://services.gradle.org/distributions/gradle-6.7-bin.zip 7 | -------------------------------------------------------------------------------- /examples/gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Wed Sep 21 13:16:49 EEST 2016 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | distributionUrl=https\://services.gradle.org/distributions/gradle-2.14.1-all.zip 7 | -------------------------------------------------------------------------------- /examples/build.gradle: -------------------------------------------------------------------------------- 1 | group 'com.bolyartech.scram_sasl' 2 | version '1.0-SNAPSHOT' 3 | 4 | apply plugin: 'java' 5 | 6 | 7 | repositories { 8 | mavenCentral() 9 | } 10 | 11 | dependencies { 12 | compile project(':scram_sasl') 13 | testCompile group: 'junit', name: 'junit', version: '4.11' 14 | } 15 | -------------------------------------------------------------------------------- /lib/src/main/java/com/bolyartech/scram_sasl/common/ScramException.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 Ognyan Bankov 3 | *
4 | * All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | *
10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | 18 | package com.bolyartech.scram_sasl.common; 19 | 20 | 21 | /** 22 | * Indicates error while processing SCRAM sequence 23 | */ 24 | @SuppressWarnings("unused") 25 | public class ScramException extends Exception { 26 | /** 27 | * Creates new ScramException 28 | * @param message Exception message 29 | */ 30 | public ScramException(String message) { 31 | super(message); 32 | } 33 | 34 | 35 | /** 36 | * Creates new ScramException 37 | * @param cause Throwable 38 | */ 39 | public ScramException(Throwable cause) { 40 | super(cause); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /lib/src/main/java/com/bolyartech/scram_sasl/client/ScramSha1SaslClientProcessor.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 Ognyan Bankov 3 | *
4 | * All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | *
10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | 18 | package com.bolyartech.scram_sasl.client; 19 | 20 | 21 | /** 22 | * Provides client side processing of the SCRAM-SHA1 SASL authentication 23 | */ 24 | @SuppressWarnings("unused") 25 | public class ScramSha1SaslClientProcessor extends AbstractScramSaslClientProcessor { 26 | /** 27 | * Creates new ScramSha1SaslClientProcessor 28 | * @param listener Listener of the client processor (this object) 29 | * @param sender Sender used to send messages to the server 30 | */ 31 | public ScramSha1SaslClientProcessor(Listener listener, Sender sender) { 32 | super(listener, sender, "SHA-1", "HmacSHA1"); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /lib/src/main/java/com/bolyartech/scram_sasl/client/ScramSha256SaslClientProcessor.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 Ognyan Bankov 3 | *
4 | * All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | *
10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | 18 | package com.bolyartech.scram_sasl.client; 19 | 20 | 21 | /** 22 | * Provides client side processing of the SCRAM-SHA256 SASL authentication 23 | */ 24 | @SuppressWarnings("unused") 25 | public class ScramSha256SaslClientProcessor extends AbstractScramSaslClientProcessor { 26 | /** 27 | * Creates new ScramSha256SaslClientProcessor 28 | * @param listener Listener of the client processor (this object) 29 | * @param sender Sender used to send messages to the server 30 | */ 31 | public ScramSha256SaslClientProcessor(ScramSaslClientProcessor.Listener listener, ScramSaslClientProcessor.Sender sender) { 32 | super(listener, sender, "SHA-256", "HmacSHA256"); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /lib/src/main/java/com/bolyartech/scram_sasl/client/ScramSha512SaslClientProcessor.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 Ognyan Bankov 3 | *
4 | * All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | *
10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | 18 | package com.bolyartech.scram_sasl.client; 19 | 20 | 21 | /** 22 | * Provides client side processing of the SCRAM-SHA512 SASL authentication 23 | */ 24 | @SuppressWarnings("unused") 25 | public class ScramSha512SaslClientProcessor extends AbstractScramSaslClientProcessor { 26 | /** 27 | * Creates new ScramSha512SaslClientProcessor 28 | * @param listener Listener of the client processor (this object) 29 | * @param sender Sender used to send messages to the server 30 | */ 31 | public ScramSha512SaslClientProcessor(ScramSaslClientProcessor.Listener listener, ScramSaslClientProcessor.Sender sender) { 32 | super(listener, sender, "SHA-512", "HmacSHA512"); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /lib/src/main/java/com/bolyartech/scram_sasl/server/ScramSha1SaslServerProcessor.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 Ognyan Bankov 3 | *
4 | * All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | *
10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | 18 | package com.bolyartech.scram_sasl.server; 19 | 20 | 21 | /** 22 | * Provides server side processing of the SCRAM-SHA1 SASL authentication 23 | */ 24 | @SuppressWarnings("unused") 25 | public class ScramSha1SaslServerProcessor extends AbstractScramSaslServerProcessor { 26 | /** 27 | * Creates new ScramSha1SaslServerProcessor 28 | * @param connectionId ID of the client connection 29 | * @param listener Listener 30 | * @param userDataLoader loader for user data 31 | * @param sender Sender used to send messages to the clients 32 | */ 33 | public ScramSha1SaslServerProcessor(long connectionId, 34 | Listener listener, 35 | UserDataLoader userDataLoader, 36 | Sender sender) { 37 | 38 | super(connectionId, listener, userDataLoader, sender, "SHA-1", "HmacSHA1"); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /lib/src/main/java/com/bolyartech/scram_sasl/server/ScramSha256SaslServerProcessor.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 Ognyan Bankov 3 | *
4 | * All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | *
10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | 18 | package com.bolyartech.scram_sasl.server; 19 | 20 | /** 21 | * Provides server side processing of the SCRAM-SHA256 SASL authentication 22 | */ 23 | @SuppressWarnings("unused") 24 | public class ScramSha256SaslServerProcessor extends AbstractScramSaslServerProcessor { 25 | /** 26 | * Creates new ScramSha256SaslServerProcessor 27 | * @param connectionId ID of the client connection 28 | * @param listener Listener 29 | * @param userDataLoader loader for user data 30 | * @param sender Sender used to send messages to the clients 31 | */ 32 | public ScramSha256SaslServerProcessor(long connectionId, 33 | Listener listener, 34 | UserDataLoader userDataLoader, 35 | Sender sender) { 36 | 37 | super(connectionId, listener, userDataLoader, sender, "SHA-256", "HmacSHA256"); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /lib/src/main/java/com/bolyartech/scram_sasl/server/ScramSha512SaslServerProcessor.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 Ognyan Bankov 3 | *
4 | * All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | *
10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.bolyartech.scram_sasl.server; 18 | 19 | 20 | /** 21 | * Provides server side processing of the SCRAM-SHA256 SASL authentication 22 | */ 23 | @SuppressWarnings("unused") 24 | public class ScramSha512SaslServerProcessor extends AbstractScramSaslServerProcessor { 25 | /** 26 | * Creates new ScramSha512SaslServerProcessor 27 | * @param connectionId ID of the client connection 28 | * @param listener Listener 29 | * @param userDataLoader loader for user data 30 | * @param sender Sender used to send messages to the clients 31 | */ 32 | public ScramSha512SaslServerProcessor(long connectionId, 33 | Listener listener, 34 | UserDataLoader userDataLoader, 35 | Sender sender) { 36 | 37 | super(connectionId, listener, userDataLoader, sender, "SHA-512", "HmacSHA512"); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /lib/src/main/java/com/bolyartech/scram_sasl/server/UserData.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 Ognyan Bankov 3 | *
4 | * All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | *
10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | 18 | package com.bolyartech.scram_sasl.server; 19 | 20 | 21 | /** 22 | * Wrapper for user data needed for the SCRAM authentication 23 | */ 24 | public class UserData { 25 | /** 26 | * Salt 27 | */ 28 | public final String salt; 29 | /** 30 | * Iterations used to salt the password 31 | */ 32 | public final int iterations; 33 | /** 34 | * Server key 35 | */ 36 | public final String serverKey; 37 | /** 38 | * Stored key 39 | */ 40 | public final String storedKey; 41 | 42 | 43 | /** 44 | * Creates new UserData 45 | * @param salt Salt 46 | * @param iterations Iterations for salting 47 | * @param serverKey Server key 48 | * @param storedKey Stored key 49 | */ 50 | public UserData(String salt, int iterations, String serverKey, String storedKey) { 51 | this.salt = salt; 52 | this.iterations = iterations; 53 | this.serverKey = serverKey; 54 | this.storedKey = storedKey; 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /lib/gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | set DIRNAME=%~dp0 12 | if "%DIRNAME%" == "" set DIRNAME=. 13 | set APP_BASE_NAME=%~n0 14 | set APP_HOME=%DIRNAME% 15 | 16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 17 | set DEFAULT_JVM_OPTS= 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windows variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | if "%@eval[2+2]" == "4" goto 4NT_args 53 | 54 | :win9xME_args 55 | @rem Slurp the command line arguments. 56 | set CMD_LINE_ARGS= 57 | set _SKIP=2 58 | 59 | :win9xME_args_slurp 60 | if "x%~1" == "x" goto execute 61 | 62 | set CMD_LINE_ARGS=%* 63 | goto execute 64 | 65 | :4NT_args 66 | @rem Get arguments from the 4NT Shell from JP Software 67 | set CMD_LINE_ARGS=%$ 68 | 69 | :execute 70 | @rem Setup the command line 71 | 72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 73 | 74 | @rem Execute Gradle 75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 76 | 77 | :end 78 | @rem End local scope for the variables with windows NT shell 79 | if "%ERRORLEVEL%"=="0" goto mainEnd 80 | 81 | :fail 82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 83 | rem the _cmd.exe /c_ return code! 84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 85 | exit /b 1 86 | 87 | :mainEnd 88 | if "%OS%"=="Windows_NT" endlocal 89 | 90 | :omega 91 | -------------------------------------------------------------------------------- /examples/gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 12 | set DEFAULT_JVM_OPTS= 13 | 14 | set DIRNAME=%~dp0 15 | if "%DIRNAME%" == "" set DIRNAME=. 16 | set APP_BASE_NAME=%~n0 17 | set APP_HOME=%DIRNAME% 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windowz variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | if "%@eval[2+2]" == "4" goto 4NT_args 53 | 54 | :win9xME_args 55 | @rem Slurp the command line arguments. 56 | set CMD_LINE_ARGS= 57 | set _SKIP=2 58 | 59 | :win9xME_args_slurp 60 | if "x%~1" == "x" goto execute 61 | 62 | set CMD_LINE_ARGS=%* 63 | goto execute 64 | 65 | :4NT_args 66 | @rem Get arguments from the 4NT Shell from JP Software 67 | set CMD_LINE_ARGS=%$ 68 | 69 | :execute 70 | @rem Setup the command line 71 | 72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 73 | 74 | @rem Execute Gradle 75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 76 | 77 | :end 78 | @rem End local scope for the variables with windows NT shell 79 | if "%ERRORLEVEL%"=="0" goto mainEnd 80 | 81 | :fail 82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 83 | rem the _cmd.exe /c_ return code! 84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 85 | exit /b 1 86 | 87 | :mainEnd 88 | if "%OS%"=="Windows_NT" endlocal 89 | 90 | :omega 91 | -------------------------------------------------------------------------------- /lib/src/main/java/com/bolyartech/scram_sasl/client/ScramSaslClientProcessor.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 Ognyan Bankov 3 | *
4 | * All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | *
10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.bolyartech.scram_sasl.client; 18 | 19 | import com.bolyartech.scram_sasl.common.ScramException; 20 | 21 | 22 | /** 23 | * Provides client side processing of the SCRAM SASL authentication 24 | */ 25 | @SuppressWarnings("unused") 26 | public interface ScramSaslClientProcessor { 27 | /** 28 | * Initiates the SCRAM sequence by preparing and sending the first client message 29 | * @param username username of the user 30 | * @param password password of the user 31 | * @throws ScramException if username contains forbidden characters (@see https://tools.ietf.org/html/rfc4013) 32 | */ 33 | void start(String username, String password) throws ScramException; 34 | 35 | /** 36 | * Called when message from server is received 37 | * @param message Message 38 | * @throws ScramException if there is a unrecoverable error during internal processing of the message 39 | */ 40 | void onMessage(String message) throws ScramException; 41 | 42 | /** 43 | * Aborts the procedure 44 | */ 45 | void abort(); 46 | /** 47 | * Checks if authentication sequence has ended 48 | * @return true if authentication has ended, false otherwise 49 | */ 50 | boolean isEnded(); 51 | /** 52 | * Checks if authentication sequence has ended successfully (i.e. user is authenticated) 53 | * @return true if authentication sequence has ended successfully, false otherwise 54 | */ 55 | boolean isSuccess(); 56 | /** 57 | * Checks if the sequence has been aborted 58 | * @return true if aborted, false otherwise 59 | */ 60 | boolean isAborted(); 61 | 62 | 63 | /** 64 | * Listener for success or failure of the SCRAM SASL authentication 65 | */ 66 | interface Listener { 67 | /** 68 | * Called if the authentication completed successfully 69 | */ 70 | void onSuccess(); 71 | 72 | /** 73 | * Called if the authentication failed 74 | */ 75 | void onFailure(); 76 | } 77 | 78 | 79 | /** 80 | * Provides functionality for sending message to the server 81 | */ 82 | interface Sender { 83 | /** 84 | * Sends message to the server 85 | * @param msg Message 86 | */ 87 | void sendMessage(String msg); 88 | } 89 | } 90 | -------------------------------------------------------------------------------- /lib/src/main/java/com/bolyartech/scram_sasl/server/ScramServerFunctionality.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 Ognyan Bankov 3 | *
4 | * All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | *
10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | 18 | package com.bolyartech.scram_sasl.server; 19 | 20 | 21 | import com.bolyartech.scram_sasl.common.ScramException; 22 | 23 | 24 | /** 25 | * Provides building blocks for creating SCRAM authentication server 26 | */ 27 | @SuppressWarnings("unused") 28 | public interface ScramServerFunctionality { 29 | /** 30 | * Handles client's first message 31 | * @param message Client's first message 32 | * @return username extracted from the client message 33 | */ 34 | String handleClientFirstMessage(String message); 35 | 36 | /** 37 | * Prepares server's first message 38 | * @param userData user data needed to prepare the message 39 | * @return Server's first message 40 | */ 41 | String prepareFirstMessage(UserData userData); 42 | 43 | /** 44 | * Prepares server's final message 45 | * @param clientFinalMessage Client's final message 46 | * @return Server's final message 47 | * @throws ScramException if there is an error processing clients message 48 | */ 49 | String prepareFinalMessage(String clientFinalMessage) throws ScramException; 50 | 51 | /** 52 | * Checks if authentication is completed, either successfully or not. 53 | * Authentication is completed if {@link #getState()} returns ENDED. 54 | * @return true if authentication has ended 55 | */ 56 | boolean isSuccessful(); 57 | 58 | 59 | /** 60 | * Checks if authentication is completed, either successfully or not. 61 | * Authentication is completed if {@link #getState()} returns ENDED. 62 | * @return true if authentication has ended 63 | */ 64 | boolean isEnded(); 65 | 66 | /** 67 | * Gets the state of the authentication procedure 68 | * @return Current state 69 | */ 70 | State getState(); 71 | 72 | 73 | /** 74 | * State of the authentication procedure 75 | */ 76 | enum State { 77 | /** 78 | * Initial state 79 | */ 80 | INITIAL, 81 | /** 82 | * First client message is handled (username is extracted) 83 | */ 84 | FIRST_CLIENT_MESSAGE_HANDLED, 85 | /** 86 | * First server message is prepared 87 | */ 88 | PREPARED_FIRST, 89 | /** 90 | * Authentication is completes, either successfully or not 91 | */ 92 | ENDED 93 | } 94 | } 95 | -------------------------------------------------------------------------------- /lib/build.gradle: -------------------------------------------------------------------------------- 1 | group 'com.bolyartech.scram_sasl' 2 | version '2.0.2' 3 | 4 | apply plugin: 'java-library' 5 | apply plugin: 'maven' 6 | apply plugin: 'maven-publish' 7 | apply plugin: 'signing' 8 | 9 | targetCompatibility = '1.8' 10 | sourceCompatibility = '1.8' 11 | 12 | 13 | repositories { 14 | mavenCentral() 15 | } 16 | 17 | buildscript { 18 | repositories { 19 | jcenter() 20 | mavenCentral() 21 | } 22 | } 23 | 24 | dependencies { 25 | testCompile group: 'junit', name: 'junit', version: '4.11' 26 | } 27 | 28 | 29 | task javadocJar(type: Jar) { 30 | classifier = 'javadoc' 31 | from javadoc 32 | } 33 | 34 | task sourcesJar(type: Jar) { 35 | classifier = 'sources' 36 | from sourceSets.main.allSource 37 | } 38 | 39 | artifacts { 40 | archives javadocJar, sourcesJar 41 | } 42 | 43 | 44 | signing { 45 | sign configurations.archives 46 | } 47 | 48 | 49 | publishing { 50 | publications { 51 | MyPublication(MavenPublication) { 52 | from components.java 53 | groupId 'com.bolyartech.scram_sasl' 54 | artifactId 'scram_sasl' 55 | version '2.0.1' 56 | artifact sourcesJar 57 | } 58 | } 59 | } 60 | 61 | uploadArchives { 62 | repositories { 63 | mavenDeployer { 64 | beforeDeployment { MavenDeployment deployment -> signing.signPom(deployment) } 65 | 66 | repository(url: "https://s01.oss.sonatype.org/service/local/staging/deploy/maven2/") { 67 | authentication(userName: ossrhUsername, password: ossrhPassword) 68 | } 69 | 70 | snapshotRepository(url: "https://s01.oss.sonatype.org/content/repositories/snapshots/") { 71 | authentication(userName: ossrhUsername, password: ossrhPassword) 72 | } 73 | 74 | pom.project { 75 | name 'SCRAM SASL library for Java' 76 | packaging 'jar' 77 | // optionally artifactId can be defined here 78 | description 'SCRAM SASL authentication for Java' 79 | url 'https://github.com/ogrebgr/scram-sasl' 80 | 81 | scm { 82 | connection 'scm:git:https://github.com/ogrebgr/scram-sasl.git' 83 | developerConnection 'scm:git:https://github.com/ogrebgr/scram-sasl.git' 84 | url 'https://github.com/ogrebgr/scram-sasl' 85 | } 86 | 87 | licenses { 88 | license { 89 | name 'The Apache License, Version 2.0' 90 | url 'http://www.apache.org/licenses/LICENSE-2.0.txt' 91 | } 92 | } 93 | 94 | developers { 95 | developer { 96 | id 'ogremir' 97 | name 'Ognyan Bankov' 98 | email 'bankov@bolyartech.com' 99 | } 100 | } 101 | } 102 | } 103 | } 104 | } 105 | 106 | 107 | archivesBaseName = "scram_sasl" 108 | 109 | 110 | 111 | -------------------------------------------------------------------------------- /lib/src/main/java/com/bolyartech/scram_sasl/client/ScramClientFunctionality.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 Ognyan Bankov 3 | *
4 | * All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | *
10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.bolyartech.scram_sasl.client; 18 | 19 | import com.bolyartech.scram_sasl.common.ScramException; 20 | 21 | 22 | /** 23 | * Provides building blocks for creating SCRAM authentication client 24 | * 25 | */ 26 | @SuppressWarnings("unused") 27 | public interface ScramClientFunctionality { 28 | /** 29 | * Prepares the first client message 30 | * @param username Username of the user 31 | * @return First client message 32 | * @throws ScramException if username contains prohibited characters 33 | */ 34 | String prepareFirstMessage(String username) throws ScramException; 35 | 36 | /** 37 | * Prepares client's final message 38 | * @param password User password 39 | * @param serverFirstMessage Server's first message 40 | * @return Client's final message 41 | * @throws ScramException if there is an error processing server's message, i.e. it violates the protocol 42 | */ 43 | String prepareFinalMessage(String password, String serverFirstMessage) throws ScramException; 44 | 45 | /** 46 | * Checks if the server's final message is valid 47 | * @param serverFinalMessage Server's final message 48 | * @return true if the server's message is valid, false otherwise 49 | */ 50 | boolean checkServerFinalMessage(String serverFinalMessage) throws ScramException; 51 | 52 | /** 53 | * Checks if authentication is successful. 54 | * You can call this method only if authentication is completed. Ensure that using {@link #isEnded()} 55 | * @return true if successful, false otherwise 56 | */ 57 | boolean isSuccessful(); 58 | 59 | /** 60 | * Checks if authentication is completed, either successfully or not. 61 | * Authentication is completed if {@link #getState()} returns ENDED. 62 | * @return true if authentication has ended 63 | */ 64 | boolean isEnded(); 65 | 66 | /** 67 | * Gets the state of the authentication procedure 68 | * @return Current state 69 | */ 70 | State getState(); 71 | 72 | /** 73 | * State of the authentication procedure 74 | */ 75 | enum State { 76 | /** 77 | * Initial state 78 | */ 79 | INITIAL, 80 | /** 81 | * State after first message is prepared 82 | */ 83 | FIRST_PREPARED, 84 | /** 85 | * State after final message is prepared 86 | */ 87 | FINAL_PREPARED, 88 | /** 89 | * Authentication is completes, either successfully or not 90 | */ 91 | ENDED 92 | } 93 | } 94 | -------------------------------------------------------------------------------- /lib/src/main/java/com/bolyartech/scram_sasl/common/Normalizer.java: -------------------------------------------------------------------------------- 1 | package com.bolyartech.scram_sasl.common; 2 | 3 | /** 4 | * Copyright 2011 Glenn Maynard 5 | *
6 | * All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); 7 | * you may not use this file except in compliance with the License. 8 | * You may obtain a copy of the License at 9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | *
12 | * Unless required by applicable law or agreed to in writing, software 13 | * distributed under the License is distributed on an "AS IS" BASIS, 14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | * See the License for the specific language governing permissions and 16 | * limitations under the License. 17 | */ 18 | 19 | 20 | import java.lang.reflect.InvocationTargetException; 21 | import java.lang.reflect.Method; 22 | 23 | 24 | /** Dynamically-loaded interface for java.text.Normalizer(NFKC); it's missing 25 | * in non-bleeding-edge versions of Android and we can get by without it. */ 26 | @SuppressWarnings({"SpellCheckingInspection", "JavaDoc"}) 27 | class Normalizer { 28 | private static boolean initialized = false; 29 | private static Method normalize; // java.text.Normalizer.normalize 30 | private static Object nfkc; // java.text.Normalizer.Form.NFKC 31 | private static final Object lock = new Object(); 32 | 33 | 34 | /** Equivalent to {@link java.text.Normalizer#normalize}(seq, Normalizer.Form.NFKC). 35 | * If Normalizer is unavailable, returns the sequence unchanged. */ 36 | public static String normalize(CharSequence seq) { 37 | synchronized (lock) { 38 | if (!initialized) { 39 | initialized = true; 40 | initialize("java.text.Normalizer"); 41 | } 42 | } 43 | 44 | if (normalize == null) 45 | return seq.toString(); 46 | 47 | try { 48 | return (String) normalize.invoke(null, seq, nfkc); 49 | } catch (IllegalAccessException | InvocationTargetException e) { 50 | throw new RuntimeException(e); 51 | } 52 | } 53 | 54 | 55 | @SuppressWarnings("SameParameterValue") 56 | private static void initialize(String classPath) { 57 | try { 58 | Class> normalizerClass = Class.forName(classPath); 59 | Class> normalizerFormClass = findSubclassByName(normalizerClass); 60 | Object[] normalizerConstants = normalizerFormClass.getEnumConstants(); 61 | 62 | nfkc = findObjectByValue(normalizerConstants, "NFKC"); 63 | normalize = normalizerClass.getMethod("normalize", CharSequence.class, normalizerFormClass); 64 | } catch (SecurityException | ClassNotFoundException | NoSuchMethodException e) { 65 | throw new IllegalStateException("Couldn't load java.text.Normalizer", e); 66 | } 67 | } 68 | 69 | 70 | private static Class> findSubclassByName(Class> parentClass) throws ClassNotFoundException { 71 | Class>[] subClasses = parentClass.getClasses(); 72 | String searchForName = parentClass.getName() + "$Form"; 73 | for (Class> memberClass : subClasses) { 74 | String s = memberClass.getName(); 75 | if (s.equals(searchForName)) 76 | return memberClass; 77 | } 78 | throw new ClassNotFoundException(); 79 | } 80 | 81 | 82 | @SuppressWarnings("SameParameterValue") 83 | private static Object findObjectByValue(Object[] objects, String s) throws ClassNotFoundException { 84 | for (Object e : objects) { 85 | if (e.toString().equals(s)) 86 | return e; 87 | } 88 | throw new ClassNotFoundException(); 89 | } 90 | } 91 | -------------------------------------------------------------------------------- /examples/src/main/java/com/bolyartech/scram_sasl/examples/ScramSha1Example.java: -------------------------------------------------------------------------------- 1 | package com.bolyartech.scram_sasl.examples; 2 | 3 | 4 | import com.bolyartech.scram_sasl.client.ScramSaslClientProcessor; 5 | import com.bolyartech.scram_sasl.client.ScramSha1SaslClientProcessor; 6 | import com.bolyartech.scram_sasl.common.ScramException; 7 | import com.bolyartech.scram_sasl.server.ScramSaslServerProcessor; 8 | import com.bolyartech.scram_sasl.server.ScramSha1SaslServerProcessor; 9 | import com.bolyartech.scram_sasl.server.UserData; 10 | 11 | 12 | /** 13 | * Shows how to use both client and server with SCRAM SHA-1 14 | */ 15 | public class ScramSha1Example { 16 | public static void main(String[] args) { 17 | ScramSha1SaslServerProcessor.Listener serverListener = new ScramSha1SaslServerProcessor.Listener() { 18 | 19 | @Override 20 | public void onSuccess(long connectionId) { 21 | System.out.println("Server success"); 22 | } 23 | 24 | 25 | @Override 26 | public void onFailure(long connectionId) { 27 | System.out.println("Server fail"); 28 | } 29 | }; 30 | 31 | 32 | ScramSaslClientProcessor.Listener clientListener = new ScramSaslClientProcessor.Listener() { 33 | @Override 34 | public void onSuccess() { 35 | System.out.println("Client success"); 36 | } 37 | 38 | 39 | @Override 40 | public void onFailure() { 41 | System.out.println("Client fail"); 42 | } 43 | }; 44 | 45 | 46 | @SuppressWarnings("Convert2Lambda") 47 | ScramSaslServerProcessor.UserDataLoader loader = new ScramSaslServerProcessor.UserDataLoader() { 48 | @Override 49 | public void loadUserData(String username, long connectionId, ScramSaslServerProcessor interested) { 50 | //noinspection SpellCheckingInspection 51 | interested.onUserDataLoaded( 52 | new UserData("TWLQ7cNG4uHZn38AlBSE7XacApO76SjN", 53 | 4096, 54 | "bEBbN+QCeFi1rtCQPn/15+mvuNg=", 55 | "pxF02K1QQ/t5PcweqxjzZwPOolU=" 56 | )); 57 | } 58 | }; 59 | 60 | MyToServerSender toServerSender = new MyToServerSender(); 61 | ScramSha1SaslClientProcessor client = new ScramSha1SaslClientProcessor(clientListener, toServerSender); 62 | 63 | MyToClientSender toClientSender = new MyToClientSender(client); 64 | ScramSha1SaslServerProcessor server = new ScramSha1SaslServerProcessor(1, serverListener, loader, 65 | toClientSender); 66 | 67 | toServerSender.setServer(server); 68 | 69 | try { 70 | client.start("ogre", "ogre1234"); 71 | } catch (ScramException e) { 72 | e.printStackTrace(); 73 | } 74 | 75 | } 76 | 77 | 78 | private static class MyToClientSender implements ScramSaslServerProcessor.Sender { 79 | private final ScramSaslClientProcessor client; 80 | 81 | 82 | public MyToClientSender(ScramSaslClientProcessor client) { 83 | this.client = client; 84 | } 85 | 86 | 87 | @Override 88 | public void sendMessage(long connectionId, String msg) { 89 | try { 90 | client.onMessage(msg); 91 | } catch (ScramException e) { 92 | e.printStackTrace(); 93 | } 94 | } 95 | } 96 | 97 | 98 | private static class MyToServerSender implements ScramSaslClientProcessor.Sender { 99 | private ScramSaslServerProcessor mServer; 100 | 101 | @Override 102 | public void sendMessage(String msg) { 103 | try { 104 | mServer.onMessage(msg); 105 | } catch (ScramException e) { 106 | e.printStackTrace(); 107 | } 108 | } 109 | 110 | 111 | public void setServer(ScramSaslServerProcessor server) { 112 | mServer = server; 113 | } 114 | } 115 | } 116 | -------------------------------------------------------------------------------- /lib/src/main/java/com/bolyartech/scram_sasl/server/ScramSaslServerProcessor.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 Ognyan Bankov 3 | *
4 | * All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | *
10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | 18 | package com.bolyartech.scram_sasl.server; 19 | 20 | import com.bolyartech.scram_sasl.common.ScramException; 21 | 22 | 23 | /** 24 | * Provides server side processing of the SCRAM SASL authentication 25 | */ 26 | @SuppressWarnings("unused") 27 | public interface ScramSaslServerProcessor { 28 | /** 29 | * Called when there is message from the client 30 | * 31 | * @param message Message 32 | * @throws ScramException if there is a unrecoverable problem during processing 33 | */ 34 | void onMessage(String message) throws ScramException; 35 | 36 | /** 37 | * Called when {@link UserData} is loaded by {@link UserDataLoader} 38 | * 39 | * @param data User data 40 | */ 41 | void onUserDataLoaded(UserData data); 42 | 43 | /** 44 | * Aborts the procedure 45 | */ 46 | void abort(); 47 | 48 | /** 49 | * Client connection's ID 50 | * 51 | * @return connection ID 52 | */ 53 | long getConnectionId(); 54 | 55 | /** 56 | * Checks if authentication sequence has ended 57 | * 58 | * @return true if authentication has ended, false otherwise 59 | */ 60 | boolean isEnded(); 61 | 62 | /** 63 | * Checks if authentication sequence has ended successfully (i.e. user is authenticated) 64 | * 65 | * @return true if authentication sequence has ended successfully, false otherwise 66 | */ 67 | boolean isSuccess(); 68 | 69 | /** 70 | * Checks if the sequence has been aborted 71 | * 72 | * @return true if aborted, false otherwise 73 | */ 74 | boolean isAborted(); 75 | 76 | 77 | /** 78 | * Returns the authorized username (you must ensure that procedure is completed and successful before calling 79 | * this method) 80 | * 81 | * @return Username of authorized user 82 | */ 83 | String getAuthorizationID(); 84 | 85 | 86 | /** 87 | * Loads user data 88 | * Implementations will usually load the user data from a DB 89 | */ 90 | interface UserDataLoader { 91 | /** 92 | * Called when user data is loaded 93 | * 94 | * @param username Username 95 | * @param connectionId ID of the connection 96 | * @param processor The client SCRAM processor 97 | */ 98 | void loadUserData(String username, long connectionId, ScramSaslServerProcessor processor); 99 | } 100 | 101 | /** 102 | * Listener for success or failure of the SCRAM SASL authentication 103 | */ 104 | interface Listener { 105 | /** 106 | * Called if the authentication completed successfully 107 | * 108 | * @param connectionId ID of the connection 109 | */ 110 | void onSuccess(long connectionId); 111 | 112 | /** 113 | * Called if the authentication failed 114 | * 115 | * @param connectionId ID of the connection 116 | */ 117 | void onFailure(long connectionId); 118 | } 119 | 120 | 121 | /** 122 | * Provides functionality for sending message to the client 123 | */ 124 | interface Sender { 125 | /** 126 | * Sends message to the client identified by connectionId 127 | * 128 | * @param connectionId ID of the client connection 129 | * @param msg Message 130 | */ 131 | void sendMessage(long connectionId, String msg); 132 | } 133 | } 134 | -------------------------------------------------------------------------------- /examples/src/main/java/com/bolyartech/scram_sasl/examples/ScramSha256Example.java: -------------------------------------------------------------------------------- 1 | package com.bolyartech.scram_sasl.examples; 2 | 3 | import com.bolyartech.scram_sasl.client.ScramSaslClientProcessor; 4 | import com.bolyartech.scram_sasl.client.ScramSha256SaslClientProcessor; 5 | import com.bolyartech.scram_sasl.common.ScramException; 6 | import com.bolyartech.scram_sasl.common.ScramUtils; 7 | import com.bolyartech.scram_sasl.server.ScramSaslServerProcessor; 8 | import com.bolyartech.scram_sasl.server.ScramSha256SaslServerProcessor; 9 | import com.bolyartech.scram_sasl.server.UserData; 10 | 11 | import java.security.InvalidKeyException; 12 | import java.security.NoSuchAlgorithmException; 13 | import java.security.SecureRandom; 14 | 15 | 16 | public class ScramSha256Example { 17 | 18 | /** 19 | * Shows how to use both client and server with SCRAM SHA-256 20 | */ 21 | public static void main(String[] args) { 22 | ScramSha256SaslServerProcessor.Listener serverListener = new ScramSha256SaslServerProcessor.Listener() { 23 | 24 | @Override 25 | public void onSuccess(long connectionId) { 26 | System.out.println("Server success"); 27 | } 28 | 29 | 30 | @Override 31 | public void onFailure(long connectionId) { 32 | System.out.println("Server fail"); 33 | } 34 | }; 35 | 36 | 37 | ScramSaslClientProcessor.Listener clientListener = new ScramSaslClientProcessor.Listener() { 38 | @Override 39 | public void onSuccess() { 40 | System.out.println("Client success"); 41 | } 42 | 43 | 44 | @Override 45 | public void onFailure() { 46 | System.out.println("Client fail"); 47 | } 48 | }; 49 | 50 | 51 | @SuppressWarnings("Convert2Lambda") 52 | ScramSaslServerProcessor.UserDataLoader loader = new ScramSaslServerProcessor.UserDataLoader() { 53 | @Override 54 | public void loadUserData(String username, long connectionId, ScramSaslServerProcessor processor) { 55 | // we fake the loading by simply generating new user data 56 | SecureRandom random = new SecureRandom(); 57 | byte[] salt = new byte[24]; 58 | random.nextBytes(salt); 59 | 60 | 61 | try { 62 | ScramUtils.NewPasswordStringData data = ScramUtils.byteArrayToStringData( 63 | ScramUtils.newPassword("ogre1234", salt, 4096, "SHA-256", "HmacSHA256") 64 | ); 65 | 66 | // we notify the processor 67 | processor.onUserDataLoaded( 68 | new UserData(data.salt, 69 | data.iterations, 70 | data.serverKey, 71 | data.storedKey)); 72 | 73 | } catch (NoSuchAlgorithmException | InvalidKeyException e) { 74 | e.printStackTrace(); 75 | } 76 | } 77 | }; 78 | 79 | MyToServerSender toServerSender = new MyToServerSender(); 80 | ScramSha256SaslClientProcessor client = new ScramSha256SaslClientProcessor(clientListener, toServerSender); 81 | 82 | MyToClientSender toClientSender = new MyToClientSender(client); 83 | ScramSha256SaslServerProcessor server = new ScramSha256SaslServerProcessor(1, serverListener, loader, 84 | toClientSender); 85 | 86 | toServerSender.setServer(server); 87 | 88 | try { 89 | client.start("ogre", "ogre1234"); 90 | } catch (ScramException e) { 91 | e.printStackTrace(); 92 | } 93 | 94 | } 95 | 96 | 97 | private static class MyToClientSender implements ScramSaslServerProcessor.Sender { 98 | private final ScramSaslClientProcessor client; 99 | 100 | 101 | public MyToClientSender(ScramSaslClientProcessor client) { 102 | this.client = client; 103 | } 104 | 105 | 106 | @Override 107 | public void sendMessage(long connectionId, String msg) { 108 | try { 109 | client.onMessage(msg); 110 | } catch (ScramException e) { 111 | e.printStackTrace(); 112 | } 113 | } 114 | } 115 | 116 | 117 | private static class MyToServerSender implements ScramSaslClientProcessor.Sender { 118 | private ScramSaslServerProcessor mServer; 119 | 120 | 121 | @Override 122 | public void sendMessage(String msg) { 123 | try { 124 | mServer.onMessage(msg); 125 | } catch (ScramException e) { 126 | e.printStackTrace(); 127 | } 128 | } 129 | 130 | 131 | public void setServer(ScramSaslServerProcessor server) { 132 | mServer = server; 133 | } 134 | } 135 | } 136 | -------------------------------------------------------------------------------- /lib/gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Attempt to set APP_HOME 10 | # Resolve links: $0 may be a link 11 | PRG="$0" 12 | # Need this for relative symlinks. 13 | while [ -h "$PRG" ] ; do 14 | ls=`ls -ld "$PRG"` 15 | link=`expr "$ls" : '.*-> \(.*\)$'` 16 | if expr "$link" : '/.*' > /dev/null; then 17 | PRG="$link" 18 | else 19 | PRG=`dirname "$PRG"`"/$link" 20 | fi 21 | done 22 | SAVED="`pwd`" 23 | cd "`dirname \"$PRG\"`/" >/dev/null 24 | APP_HOME="`pwd -P`" 25 | cd "$SAVED" >/dev/null 26 | 27 | APP_NAME="Gradle" 28 | APP_BASE_NAME=`basename "$0"` 29 | 30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 31 | DEFAULT_JVM_OPTS="" 32 | 33 | # Use the maximum available, or set MAX_FD != -1 to use that value. 34 | MAX_FD="maximum" 35 | 36 | warn ( ) { 37 | echo "$*" 38 | } 39 | 40 | die ( ) { 41 | echo 42 | echo "$*" 43 | echo 44 | exit 1 45 | } 46 | 47 | # OS specific support (must be 'true' or 'false'). 48 | cygwin=false 49 | msys=false 50 | darwin=false 51 | nonstop=false 52 | case "`uname`" in 53 | CYGWIN* ) 54 | cygwin=true 55 | ;; 56 | Darwin* ) 57 | darwin=true 58 | ;; 59 | MINGW* ) 60 | msys=true 61 | ;; 62 | NONSTOP* ) 63 | nonstop=true 64 | ;; 65 | esac 66 | 67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 68 | 69 | # Determine the Java command to use to start the JVM. 70 | if [ -n "$JAVA_HOME" ] ; then 71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 72 | # IBM's JDK on AIX uses strange locations for the executables 73 | JAVACMD="$JAVA_HOME/jre/sh/java" 74 | else 75 | JAVACMD="$JAVA_HOME/bin/java" 76 | fi 77 | if [ ! -x "$JAVACMD" ] ; then 78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 79 | 80 | Please set the JAVA_HOME variable in your environment to match the 81 | location of your Java installation." 82 | fi 83 | else 84 | JAVACMD="java" 85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 86 | 87 | Please set the JAVA_HOME variable in your environment to match the 88 | location of your Java installation." 89 | fi 90 | 91 | # Increase the maximum file descriptors if we can. 92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 93 | MAX_FD_LIMIT=`ulimit -H -n` 94 | if [ $? -eq 0 ] ; then 95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 96 | MAX_FD="$MAX_FD_LIMIT" 97 | fi 98 | ulimit -n $MAX_FD 99 | if [ $? -ne 0 ] ; then 100 | warn "Could not set maximum file descriptor limit: $MAX_FD" 101 | fi 102 | else 103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 104 | fi 105 | fi 106 | 107 | # For Darwin, add options to specify how the application appears in the dock 108 | if $darwin; then 109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 110 | fi 111 | 112 | # For Cygwin, switch paths to Windows format before running java 113 | if $cygwin ; then 114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 116 | JAVACMD=`cygpath --unix "$JAVACMD"` 117 | 118 | # We build the pattern for arguments to be converted via cygpath 119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 120 | SEP="" 121 | for dir in $ROOTDIRSRAW ; do 122 | ROOTDIRS="$ROOTDIRS$SEP$dir" 123 | SEP="|" 124 | done 125 | OURCYGPATTERN="(^($ROOTDIRS))" 126 | # Add a user-defined pattern to the cygpath arguments 127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 129 | fi 130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 131 | i=0 132 | for arg in "$@" ; do 133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 135 | 136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 138 | else 139 | eval `echo args$i`="\"$arg\"" 140 | fi 141 | i=$((i+1)) 142 | done 143 | case $i in 144 | (0) set -- ;; 145 | (1) set -- "$args0" ;; 146 | (2) set -- "$args0" "$args1" ;; 147 | (3) set -- "$args0" "$args1" "$args2" ;; 148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 154 | esac 155 | fi 156 | 157 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules 158 | function splitJvmOpts() { 159 | JVM_OPTS=("$@") 160 | } 161 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS 162 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" 163 | 164 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" 165 | -------------------------------------------------------------------------------- /examples/gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 10 | DEFAULT_JVM_OPTS="" 11 | 12 | APP_NAME="Gradle" 13 | APP_BASE_NAME=`basename "$0"` 14 | 15 | # Use the maximum available, or set MAX_FD != -1 to use that value. 16 | MAX_FD="maximum" 17 | 18 | warn ( ) { 19 | echo "$*" 20 | } 21 | 22 | die ( ) { 23 | echo 24 | echo "$*" 25 | echo 26 | exit 1 27 | } 28 | 29 | # OS specific support (must be 'true' or 'false'). 30 | cygwin=false 31 | msys=false 32 | darwin=false 33 | case "`uname`" in 34 | CYGWIN* ) 35 | cygwin=true 36 | ;; 37 | Darwin* ) 38 | darwin=true 39 | ;; 40 | MINGW* ) 41 | msys=true 42 | ;; 43 | esac 44 | 45 | # For Cygwin, ensure paths are in UNIX format before anything is touched. 46 | if $cygwin ; then 47 | [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"` 48 | fi 49 | 50 | # Attempt to set APP_HOME 51 | # Resolve links: $0 may be a link 52 | PRG="$0" 53 | # Need this for relative symlinks. 54 | while [ -h "$PRG" ] ; do 55 | ls=`ls -ld "$PRG"` 56 | link=`expr "$ls" : '.*-> \(.*\)$'` 57 | if expr "$link" : '/.*' > /dev/null; then 58 | PRG="$link" 59 | else 60 | PRG=`dirname "$PRG"`"/$link" 61 | fi 62 | done 63 | SAVED="`pwd`" 64 | cd "`dirname \"$PRG\"`/" >&- 65 | APP_HOME="`pwd -P`" 66 | cd "$SAVED" >&- 67 | 68 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 69 | 70 | # Determine the Java command to use to start the JVM. 71 | if [ -n "$JAVA_HOME" ] ; then 72 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 73 | # IBM's JDK on AIX uses strange locations for the executables 74 | JAVACMD="$JAVA_HOME/jre/sh/java" 75 | else 76 | JAVACMD="$JAVA_HOME/bin/java" 77 | fi 78 | if [ ! -x "$JAVACMD" ] ; then 79 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 80 | 81 | Please set the JAVA_HOME variable in your environment to match the 82 | location of your Java installation." 83 | fi 84 | else 85 | JAVACMD="java" 86 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 87 | 88 | Please set the JAVA_HOME variable in your environment to match the 89 | location of your Java installation." 90 | fi 91 | 92 | # Increase the maximum file descriptors if we can. 93 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then 94 | MAX_FD_LIMIT=`ulimit -H -n` 95 | if [ $? -eq 0 ] ; then 96 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 97 | MAX_FD="$MAX_FD_LIMIT" 98 | fi 99 | ulimit -n $MAX_FD 100 | if [ $? -ne 0 ] ; then 101 | warn "Could not set maximum file descriptor limit: $MAX_FD" 102 | fi 103 | else 104 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 105 | fi 106 | fi 107 | 108 | # For Darwin, add options to specify how the application appears in the dock 109 | if $darwin; then 110 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 111 | fi 112 | 113 | # For Cygwin, switch paths to Windows format before running java 114 | if $cygwin ; then 115 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 116 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 117 | 118 | # We build the pattern for arguments to be converted via cygpath 119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 120 | SEP="" 121 | for dir in $ROOTDIRSRAW ; do 122 | ROOTDIRS="$ROOTDIRS$SEP$dir" 123 | SEP="|" 124 | done 125 | OURCYGPATTERN="(^($ROOTDIRS))" 126 | # Add a user-defined pattern to the cygpath arguments 127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 129 | fi 130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 131 | i=0 132 | for arg in "$@" ; do 133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 135 | 136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 138 | else 139 | eval `echo args$i`="\"$arg\"" 140 | fi 141 | i=$((i+1)) 142 | done 143 | case $i in 144 | (0) set -- ;; 145 | (1) set -- "$args0" ;; 146 | (2) set -- "$args0" "$args1" ;; 147 | (3) set -- "$args0" "$args1" "$args2" ;; 148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 154 | esac 155 | fi 156 | 157 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules 158 | function splitJvmOpts() { 159 | JVM_OPTS=("$@") 160 | } 161 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS 162 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" 163 | 164 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" 165 | -------------------------------------------------------------------------------- /lib/src/main/java/com/bolyartech/scram_sasl/client/AbstractScramSaslClientProcessor.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 Ognyan Bankov 3 | *
4 | * All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | *
10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.bolyartech.scram_sasl.client; 18 | 19 | import com.bolyartech.scram_sasl.common.ScramException; 20 | import com.bolyartech.scram_sasl.common.ScramUtils; 21 | 22 | import java.util.UUID; 23 | 24 | 25 | /** 26 | * Provides client side processing of the SCRAM SASL authentication 27 | * Skeleton implementation of ScramSaslClientProcessor 28 | */ 29 | @SuppressWarnings("WeakerAccess") 30 | abstract public class AbstractScramSaslClientProcessor implements ScramSaslClientProcessor { 31 | private final ScramSaslClientProcessor.Listener mListener; 32 | private final Sender mSender; 33 | private String mPassword; 34 | private State mState = State.INITIAL; 35 | 36 | private volatile boolean mIsSuccess = false; 37 | private volatile boolean mAborted = false; 38 | 39 | private ScramClientFunctionality mScramClientFunctionality; 40 | 41 | 42 | /** 43 | * Creates new AbstractScramSaslClientProcessor 44 | * @param listener Listener of the client processor (this object) 45 | * @param sender Sender used to send messages to the server 46 | * @param digestName Digest to be used 47 | * @param hmacName HMAC to be used 48 | */ 49 | @SuppressWarnings("SameParameterValue") 50 | public AbstractScramSaslClientProcessor(Listener listener, Sender sender, String digestName, String hmacName) { 51 | this(listener, sender, digestName, hmacName, UUID.randomUUID().toString()); 52 | } 53 | 54 | 55 | /** 56 | * Creates new AbstractScramSaslClientProcessor 57 | * Intended to be used in unit test (with a predefined clientNonce in order to have repeatability) 58 | * @param listener Listener of the client processor (this object) 59 | * @param sender Sender used to send messages to the server 60 | * @param digestName Digest to be used 61 | * @param hmacName HMAC to be used 62 | * @param clientNonce Client nonce 63 | */ 64 | AbstractScramSaslClientProcessor(Listener listener, 65 | Sender sender, 66 | String digestName, 67 | String hmacName, 68 | String clientNonce) { 69 | 70 | if (listener == null) { 71 | throw new NullPointerException("Parameter listener cannot be null"); 72 | } 73 | if (sender == null) { 74 | throw new NullPointerException("Parameter sender cannot be null"); 75 | } 76 | if (ScramUtils.isNullOrEmpty(digestName)) { 77 | throw new NullPointerException("digestName cannot be null or empty"); 78 | } 79 | if (ScramUtils.isNullOrEmpty(hmacName)) { 80 | throw new NullPointerException("hmacName cannot be null or empty"); 81 | } 82 | if (ScramUtils.isNullOrEmpty(clientNonce)) { 83 | throw new NullPointerException("clientNonce cannot be null or empty"); 84 | } 85 | 86 | mScramClientFunctionality = new ScramClientFunctionalityImpl(digestName, hmacName, clientNonce); 87 | 88 | mListener = listener; 89 | mSender = sender; 90 | } 91 | 92 | 93 | @Override 94 | public synchronized void onMessage(String message) throws ScramException { 95 | if (mState != State.ENDED) { 96 | switch (mState) { 97 | case INITIAL: 98 | notifyFail(); 99 | case CLIENT_FIRST_SENT: 100 | String msg = handleServerFirst(message); 101 | if (msg != null) { 102 | mState = State.CLIENT_FINAL_SENT; 103 | mSender.sendMessage(msg); 104 | } else { 105 | mState = State.ENDED; 106 | notifyFail(); 107 | } 108 | break; 109 | case CLIENT_FINAL_SENT: 110 | if (handleServerFinal(message)) { 111 | mIsSuccess = true; 112 | notifySuccess(); 113 | } else { 114 | notifyFail(); 115 | } 116 | mState = State.ENDED; 117 | break; 118 | } 119 | } 120 | } 121 | 122 | 123 | @Override 124 | public synchronized void abort() { 125 | mAborted = true; 126 | mState = State.ENDED; 127 | } 128 | 129 | 130 | @Override 131 | public synchronized boolean isEnded() { 132 | return mState == State.ENDED; 133 | } 134 | 135 | 136 | @Override 137 | public boolean isSuccess() { 138 | return mIsSuccess; 139 | } 140 | 141 | 142 | @Override 143 | public synchronized void start(String username, String password) throws ScramException { 144 | mPassword = password; 145 | 146 | mState = State.CLIENT_FIRST_SENT; 147 | mSender.sendMessage(mScramClientFunctionality.prepareFirstMessage(username)); 148 | } 149 | 150 | 151 | @Override 152 | public boolean isAborted() { 153 | return mAborted; 154 | } 155 | 156 | 157 | private boolean handleServerFinal(String message) throws ScramException { 158 | return mScramClientFunctionality.checkServerFinalMessage(message); 159 | } 160 | 161 | 162 | private String handleServerFirst(String message) throws ScramException { 163 | return mScramClientFunctionality.prepareFinalMessage(mPassword, message); 164 | } 165 | 166 | 167 | private void notifySuccess() { 168 | mListener.onSuccess(); 169 | } 170 | 171 | 172 | private void notifyFail() { 173 | mListener.onFailure(); 174 | } 175 | 176 | 177 | enum State { 178 | INITIAL, 179 | CLIENT_FIRST_SENT, 180 | CLIENT_FINAL_SENT, 181 | ENDED 182 | } 183 | } 184 | -------------------------------------------------------------------------------- /lib/src/main/java/com/bolyartech/scram_sasl/server/ScramServerFunctionalityImpl.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 Ognyan Bankov 3 | *
4 | * All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | *
10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | 18 | package com.bolyartech.scram_sasl.server; 19 | 20 | 21 | import com.bolyartech.scram_sasl.common.Base64; 22 | import com.bolyartech.scram_sasl.common.ScramException; 23 | import com.bolyartech.scram_sasl.common.ScramUtils; 24 | 25 | import java.security.InvalidKeyException; 26 | import java.security.MessageDigest; 27 | import java.security.NoSuchAlgorithmException; 28 | import java.util.Arrays; 29 | import java.util.UUID; 30 | import java.util.regex.Matcher; 31 | import java.util.regex.Pattern; 32 | 33 | 34 | /** 35 | * Provides building blocks for creating SCRAM authentication server 36 | */ 37 | @SuppressWarnings("unused") 38 | public class ScramServerFunctionalityImpl implements ScramServerFunctionality { 39 | private static final Pattern 40 | CLIENT_FIRST_MESSAGE = Pattern.compile("^(([pny])=?([^,]*),([^,]*),)(m?=?[^,]*,?n=([^,]*),r=([^,]*),?.*)$"); 41 | private static final Pattern 42 | CLIENT_FINAL_MESSAGE = Pattern.compile("(c=([^,]*),r=([^,]*)),p=(.*)$"); 43 | 44 | 45 | private final String mDigestName; 46 | private final String mHmacName; 47 | private final String mServerPartNonce; 48 | 49 | private boolean mIsSuccessful = false; 50 | private State mState = State.INITIAL; 51 | private String mClientFirstMessageBare; 52 | private String mNonce; 53 | private String mServerFirstMessage; 54 | private UserData mUserData; 55 | 56 | 57 | /** 58 | * Creates new ScramServerFunctionalityImpl 59 | * @param digestName Digest to be used 60 | * @param hmacName HMAC to be used 61 | */ 62 | public ScramServerFunctionalityImpl(String digestName, String hmacName) { 63 | this(digestName, hmacName, UUID.randomUUID().toString()); 64 | } 65 | 66 | 67 | /** 68 | /** 69 | * Creates new ScramServerFunctionalityImpl 70 | * @param digestName Digest to be used 71 | * @param hmacName HMAC to be used 72 | * @param serverPartNonce Server's part of the nonce 73 | */ 74 | public ScramServerFunctionalityImpl(String digestName, String hmacName, String serverPartNonce) { 75 | if (ScramUtils.isNullOrEmpty(digestName)) { 76 | throw new NullPointerException("digestName cannot be null or empty"); 77 | } 78 | if (ScramUtils.isNullOrEmpty(hmacName)) { 79 | throw new NullPointerException("hmacName cannot be null or empty"); 80 | } 81 | if (ScramUtils.isNullOrEmpty(serverPartNonce)) { 82 | throw new NullPointerException("serverPartNonce cannot be null or empty"); 83 | } 84 | 85 | mDigestName = digestName; 86 | mHmacName = hmacName; 87 | mServerPartNonce = serverPartNonce; 88 | } 89 | 90 | 91 | /** 92 | * Handles client's first message 93 | * @param message Client's first message 94 | * @return username extracted from the client message 95 | */ 96 | @Override 97 | public String handleClientFirstMessage(String message) { 98 | Matcher m = CLIENT_FIRST_MESSAGE.matcher(message); 99 | if (!m.matches()) { 100 | return null; 101 | } 102 | 103 | mClientFirstMessageBare = m.group(5); 104 | String username = m.group(6); 105 | String clientNonce = m.group(7); 106 | mNonce = clientNonce + mServerPartNonce; 107 | 108 | mState = State.FIRST_CLIENT_MESSAGE_HANDLED; 109 | 110 | return username; 111 | } 112 | 113 | 114 | @Override 115 | public String prepareFirstMessage(UserData userData) { 116 | mUserData = userData; 117 | mState = State.PREPARED_FIRST; 118 | mServerFirstMessage = String.format("r=%s,s=%s,i=%d", 119 | mNonce, 120 | userData.salt, 121 | userData.iterations); 122 | 123 | return mServerFirstMessage; 124 | } 125 | 126 | 127 | @Override 128 | public String prepareFinalMessage(String clientFinalMessage) throws ScramException { 129 | Matcher m = CLIENT_FINAL_MESSAGE.matcher(clientFinalMessage); 130 | if (!m.matches()) { 131 | mState = State.ENDED; 132 | return null; 133 | } 134 | 135 | String clientFinalMessageWithoutProof = m.group(1); 136 | String clientNonce = m.group(3); 137 | String proof = m.group(4); 138 | 139 | if (!mNonce.equals(clientNonce)) { 140 | mState = State.ENDED; 141 | return null; 142 | } 143 | 144 | 145 | String authMessage = mClientFirstMessageBare + "," + mServerFirstMessage + "," + clientFinalMessageWithoutProof; 146 | 147 | byte[] storedKeyArr = Base64.decode(mUserData.storedKey); 148 | 149 | try { 150 | byte[] clientSignature = ScramUtils.computeHmac(storedKeyArr, mHmacName, authMessage); 151 | byte[] serverSignature = ScramUtils.computeHmac(Base64.decode(mUserData.serverKey), mHmacName, authMessage); 152 | byte[] clientKey = clientSignature.clone(); 153 | byte[] decodedProof = Base64.decode(proof); 154 | for (int i = 0; i < clientKey.length; i++) { 155 | clientKey[i] ^= decodedProof[i]; 156 | } 157 | 158 | byte[] resultKey = MessageDigest.getInstance(mDigestName).digest(clientKey); 159 | if (!Arrays.equals(storedKeyArr, resultKey)) { 160 | return null; 161 | } 162 | 163 | 164 | mIsSuccessful = true; 165 | mState = State.ENDED; 166 | return "v=" + Base64.encodeBytes(serverSignature, Base64.DONT_BREAK_LINES); 167 | } catch (NoSuchAlgorithmException | InvalidKeyException e) { 168 | mState = State.ENDED; 169 | throw new ScramException(e); 170 | } 171 | } 172 | 173 | 174 | @Override 175 | public boolean isSuccessful() { 176 | if (mState == State.ENDED) { 177 | return mIsSuccessful; 178 | } else { 179 | throw new IllegalStateException("You cannot call this method before authentication is ended. " + 180 | "Use isEnded() to check that"); 181 | } 182 | } 183 | 184 | 185 | @Override 186 | public boolean isEnded() { 187 | return mState == State.ENDED; 188 | } 189 | 190 | 191 | @Override 192 | public State getState() { 193 | return mState; 194 | } 195 | } 196 | -------------------------------------------------------------------------------- /lib/src/main/java/com/bolyartech/scram_sasl/server/AbstractScramSaslServerProcessor.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 Ognyan Bankov 3 | *
4 | * All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | *
10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | 18 | package com.bolyartech.scram_sasl.server; 19 | 20 | 21 | import com.bolyartech.scram_sasl.common.ScramException; 22 | import com.bolyartech.scram_sasl.common.ScramUtils; 23 | 24 | import java.util.UUID; 25 | 26 | 27 | /** 28 | * Provides server side processing of the SCRAM SASL authentication 29 | * Skeleton implementation of ScramSaslServerProcessor 30 | */ 31 | @SuppressWarnings({"WeakerAccess", "unused"}) 32 | abstract class AbstractScramSaslServerProcessor implements ScramSaslServerProcessor { 33 | 34 | private final long mConnectionId; 35 | private final Listener mListener; 36 | private final UserDataLoader mUserDataLoader; 37 | private final Sender mSender; 38 | 39 | private State mState = State.INITIAL; 40 | 41 | private volatile boolean mIsSuccess = false; 42 | private volatile boolean mAborted = false; 43 | private String mUsername; 44 | private ScramServerFunctionality mScramServerFunctionality; 45 | 46 | 47 | /** 48 | * Creates new AbstractScramSaslServerProcessor 49 | * @param connectionId ID of the client connection 50 | * @param listener Listener 51 | * @param userDataLoader loader for user data 52 | * @param sender Sender used to send messages to the clients 53 | * @param digestName Digest to be used 54 | * @param hmacName HMAC to be used 55 | */ 56 | public AbstractScramSaslServerProcessor(final long connectionId, 57 | final Listener listener, 58 | final UserDataLoader userDataLoader, 59 | final Sender sender, 60 | final String digestName, 61 | final String hmacName) { 62 | 63 | this(connectionId, listener, userDataLoader, sender, digestName, hmacName, UUID.randomUUID().toString()); 64 | } 65 | 66 | 67 | /** 68 | * Creates new AbstractScramSaslServerProcessor. 69 | * Intended to be used in unit test (with a predefined serverPartNonce in order to have repeatability) 70 | * @param connectionId ID of the client connection 71 | * @param listener Listener 72 | * @param userDataLoader loader for user data 73 | * @param sender Sender used to send messages to the clients 74 | * @param digestName Digest to be used 75 | * @param hmacName HMAC to be used 76 | * @param serverPartNonce In its first message server sends a nonce which contains the client nonce and server part nonce 77 | */ 78 | AbstractScramSaslServerProcessor(final long connectionId, 79 | final Listener listener, 80 | final UserDataLoader userDataLoader, 81 | final Sender sender, 82 | final String digestName, 83 | final String hmacName, 84 | final String serverPartNonce) { 85 | 86 | if (listener == null) { 87 | throw new NullPointerException("listener cannot be null"); 88 | } 89 | if (userDataLoader == null) { 90 | throw new NullPointerException("userDataLoader cannot be null"); 91 | } 92 | if (sender == null) { 93 | throw new NullPointerException("sender cannot be null"); 94 | } 95 | if (ScramUtils.isNullOrEmpty(digestName)) { 96 | throw new NullPointerException("digestName cannot be null or empty"); 97 | } 98 | if (ScramUtils.isNullOrEmpty(hmacName)) { 99 | throw new NullPointerException("hmacName cannot be null or empty"); 100 | } 101 | if (ScramUtils.isNullOrEmpty(serverPartNonce)) { 102 | throw new NullPointerException("serverPartNonce cannot be null or empty"); 103 | } 104 | mScramServerFunctionality = new ScramServerFunctionalityImpl(digestName, hmacName, serverPartNonce); 105 | 106 | mConnectionId = connectionId; 107 | mListener = listener; 108 | mUserDataLoader = userDataLoader; 109 | mSender = sender; 110 | } 111 | 112 | 113 | public synchronized void onMessage(String message) throws ScramException { 114 | if (mState != State.ENDED) { 115 | switch (mState) { 116 | case INITIAL: 117 | if (handleClientFirst(message)) { 118 | mState = State.WAITING_FOR_USER_DATA; 119 | } else { 120 | mState = State.ENDED; 121 | notifyFail(); 122 | } 123 | break; 124 | case WAITING_FOR_USER_DATA: 125 | mState = State.ENDED; 126 | notifyFail(); 127 | break; 128 | case SERVER_FIRST_SENT: 129 | mState = State.ENDED; 130 | String msg = handleClientFinal(message); 131 | if (msg != null) { 132 | mSender.sendMessage(mConnectionId, msg); 133 | mIsSuccess = true; 134 | mListener.onSuccess(mConnectionId); 135 | } else { 136 | mListener.onFailure(mConnectionId); 137 | } 138 | break; 139 | } 140 | } 141 | } 142 | 143 | 144 | @Override 145 | public synchronized void onUserDataLoaded(UserData data) { 146 | String serverFirstMessage = mScramServerFunctionality.prepareFirstMessage(data); 147 | mState = State.SERVER_FIRST_SENT; 148 | mSender.sendMessage(mConnectionId, serverFirstMessage); 149 | } 150 | 151 | 152 | @Override 153 | public synchronized void abort() { 154 | mAborted = true; 155 | mState = State.ENDED; 156 | } 157 | 158 | 159 | @Override 160 | public long getConnectionId() { 161 | return mConnectionId; 162 | } 163 | 164 | 165 | @Override 166 | public synchronized String getAuthorizationID() { 167 | if (mState == State.ENDED && mIsSuccess) { 168 | return mUsername; 169 | } else { 170 | throw new IllegalStateException("Don't call this method before the successful end"); 171 | } 172 | } 173 | 174 | 175 | @Override 176 | public synchronized boolean isEnded() { 177 | return mState == State.ENDED; 178 | } 179 | 180 | 181 | @Override 182 | public boolean isAborted() { 183 | return mAborted; 184 | } 185 | 186 | 187 | @Override 188 | public boolean isSuccess() { 189 | if (mState == State.ENDED && mIsSuccess) { 190 | return mIsSuccess; 191 | } else { 192 | throw new IllegalStateException("Don't call this method before the end"); 193 | } 194 | } 195 | 196 | 197 | private String handleClientFinal(String message) throws ScramException { 198 | mState = State.ENDED; 199 | String finalMessage = mScramServerFunctionality.prepareFinalMessage(message); 200 | if (finalMessage != null) { 201 | mIsSuccess = true; 202 | mState = State.ENDED; 203 | return finalMessage; 204 | } else { 205 | return null; 206 | } 207 | } 208 | 209 | 210 | private boolean handleClientFirst(String message) { 211 | mUsername = mScramServerFunctionality.handleClientFirstMessage(message); 212 | 213 | if (mUsername != null) { 214 | mUserDataLoader.loadUserData(mUsername, mConnectionId, this); 215 | return true; 216 | } else { 217 | return false; 218 | } 219 | } 220 | 221 | 222 | private void notifySuccess() { 223 | mListener.onSuccess(mConnectionId); 224 | } 225 | 226 | 227 | private void notifyFail() { 228 | mListener.onFailure(mConnectionId); 229 | } 230 | 231 | 232 | private enum State { 233 | INITIAL, 234 | WAITING_FOR_USER_DATA, 235 | SERVER_FIRST_SENT, 236 | ENDED 237 | } 238 | } 239 | -------------------------------------------------------------------------------- /lib/src/main/java/com/bolyartech/scram_sasl/client/ScramClientFunctionalityImpl.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 Ognyan Bankov 3 | *
4 | * All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package com.bolyartech.scram_sasl.client;
18 |
19 |
20 | import com.bolyartech.scram_sasl.common.Base64;
21 | import com.bolyartech.scram_sasl.common.ScramException;
22 | import com.bolyartech.scram_sasl.common.ScramUtils;
23 | import com.bolyartech.scram_sasl.common.StringPrep;
24 |
25 | import java.nio.charset.Charset;
26 | import java.security.InvalidKeyException;
27 | import java.security.MessageDigest;
28 | import java.security.NoSuchAlgorithmException;
29 | import java.util.Arrays;
30 | import java.util.UUID;
31 | import java.util.regex.Matcher;
32 | import java.util.regex.Pattern;
33 |
34 |
35 | /**
36 | * Provides building blocks for creating SCRAM authentication client
37 | */
38 | @SuppressWarnings("unused")
39 | public class ScramClientFunctionalityImpl implements ScramClientFunctionality {
40 | private static final Pattern SERVER_FIRST_MESSAGE = Pattern.compile("r=([^,]*),s=([^,]*),i=(.*)$");
41 | private static final Pattern SERVER_FINAL_MESSAGE = Pattern.compile("v=([^,]*)$");
42 |
43 | private static final String GS2_HEADER = "n,,";
44 | private static final Charset ASCII = Charset.forName("ASCII");
45 |
46 | private final String mDigestName;
47 | private final String mHmacName;
48 | private final String mClientNonce;
49 | private String mClientFirstMessageBare;
50 |
51 | private boolean mIsSuccessful = false;
52 | private byte[] mSaltedPassword;
53 | private String mAuthMessage;
54 |
55 | private State mState = State.INITIAL;
56 |
57 |
58 | /**
59 | * Create new ScramClientFunctionalityImpl
60 | * @param digestName Digest to be used
61 | * @param hmacName HMAC to be used
62 | */
63 | public ScramClientFunctionalityImpl(String digestName, String hmacName) {
64 | this(digestName, hmacName, UUID.randomUUID().toString());
65 | }
66 |
67 |
68 | /**
69 | * Create new ScramClientFunctionalityImpl
70 | * @param digestName Digest to be used
71 | * @param hmacName HMAC to be used
72 | * @param clientNonce Client nonce to be used
73 | */
74 | public ScramClientFunctionalityImpl(String digestName, String hmacName, String clientNonce) {
75 | if (ScramUtils.isNullOrEmpty(digestName)) {
76 | throw new NullPointerException("digestName cannot be null or empty");
77 | }
78 | if (ScramUtils.isNullOrEmpty(hmacName)) {
79 | throw new NullPointerException("hmacName cannot be null or empty");
80 | }
81 | if (ScramUtils.isNullOrEmpty(clientNonce)) {
82 | throw new NullPointerException("clientNonce cannot be null or empty");
83 | }
84 |
85 | mDigestName = digestName;
86 | mHmacName = hmacName;
87 | mClientNonce = clientNonce;
88 | }
89 |
90 |
91 | /**
92 | * Prepares first client message
93 | *
94 | * You may want to use {@link StringPrep#isContainingProhibitedCharacters(String)} in order to check if the
95 | * username contains only valid characters
96 | * @param username Username
97 | * @return prepared first message
98 | * @throws ScramException if username contains prohibited characters
99 | */
100 | @Override
101 | public String prepareFirstMessage(String username) throws ScramException {
102 | if (mState != State.INITIAL) {
103 | throw new IllegalStateException("You can call this method only once");
104 | }
105 |
106 | try {
107 | mClientFirstMessageBare = "n=" + StringPrep.prepAsQueryString(username) + ",r=" + mClientNonce;
108 | mState = State.FIRST_PREPARED;
109 | return GS2_HEADER + mClientFirstMessageBare;
110 | } catch (StringPrep.StringPrepError e) {
111 | mState = State.ENDED;
112 | throw new ScramException("Username contains prohibited character");
113 | }
114 | }
115 |
116 |
117 | @Override
118 | public String prepareFinalMessage(String password, String serverFirstMessage) throws ScramException {
119 | if (mState != State.FIRST_PREPARED) {
120 | throw new IllegalStateException("You can call this method once only after " +
121 | "calling prepareFirstMessage()");
122 | }
123 |
124 | Matcher m = SERVER_FIRST_MESSAGE.matcher(serverFirstMessage);
125 | if (!m.matches()) {
126 | mState = State.ENDED;
127 | return null;
128 | }
129 |
130 | String nonce = m.group(1);
131 |
132 | if (!nonce.startsWith(mClientNonce)) {
133 | mState = State.ENDED;
134 | return null;
135 | }
136 |
137 |
138 | String salt = m.group(2);
139 | String iterationCountString = m.group(3);
140 | int iterations = Integer.parseInt(iterationCountString);
141 | if (iterations <= 0) {
142 | mState = State.ENDED;
143 | return null;
144 | }
145 |
146 |
147 | try {
148 | mSaltedPassword = ScramUtils.generateSaltedPassword(password,
149 | Base64.decode(salt),
150 | iterations,
151 | mHmacName);
152 |
153 |
154 | String clientFinalMessageWithoutProof = "c=" + Base64.encodeBytes(GS2_HEADER.getBytes(ASCII)
155 | , Base64.DONT_BREAK_LINES)
156 | + ",r=" + nonce;
157 |
158 | mAuthMessage = mClientFirstMessageBare + "," + serverFirstMessage + "," + clientFinalMessageWithoutProof;
159 |
160 | byte[] clientKey = ScramUtils.computeHmac(mSaltedPassword, mHmacName, "Client Key");
161 | byte[] storedKey = MessageDigest.getInstance(mDigestName).digest(clientKey);
162 |
163 | byte[] clientSignature = ScramUtils.computeHmac(storedKey, mHmacName, mAuthMessage);
164 |
165 | byte[] clientProof = clientKey.clone();
166 | for (int i = 0; i < clientProof.length; i++) {
167 | clientProof[i] ^= clientSignature[i];
168 | }
169 |
170 | mState = State.FINAL_PREPARED;
171 | return clientFinalMessageWithoutProof + ",p=" + Base64.encodeBytes(clientProof, Base64.DONT_BREAK_LINES);
172 | } catch (InvalidKeyException | NoSuchAlgorithmException e) {
173 | mState = State.ENDED;
174 | throw new ScramException(e);
175 | }
176 | }
177 |
178 |
179 | @Override
180 | public boolean checkServerFinalMessage(String serverFinalMessage) throws ScramException {
181 | if (mState != State.FINAL_PREPARED) {
182 | throw new IllegalStateException("You can call this method only once after " +
183 | "calling prepareFinalMessage()");
184 | }
185 |
186 | Matcher m = SERVER_FINAL_MESSAGE.matcher(serverFinalMessage);
187 | if (!m.matches()) {
188 | mState = State.ENDED;
189 | return false;
190 | }
191 |
192 | byte[] serverSignature = Base64.decode(m.group(1));
193 |
194 | mState = State.ENDED;
195 | mIsSuccessful = Arrays.equals(serverSignature, getExpectedServerSignature());
196 |
197 | return mIsSuccessful;
198 | }
199 |
200 |
201 | @Override
202 | public boolean isSuccessful() {
203 | if (mState == State.ENDED) {
204 | return mIsSuccessful;
205 | } else {
206 | throw new IllegalStateException("You cannot call this method before authentication is ended. " +
207 | "Use isEnded() to check that");
208 | }
209 | }
210 |
211 |
212 | @Override
213 | public boolean isEnded() {
214 | return mState == State.ENDED;
215 | }
216 |
217 |
218 | @Override
219 | public State getState() {
220 | return mState;
221 | }
222 |
223 |
224 | private byte[] getExpectedServerSignature() throws ScramException {
225 | try {
226 | byte[] serverKey = ScramUtils.computeHmac(mSaltedPassword, mHmacName, "Server Key");
227 | return ScramUtils.computeHmac(serverKey, mHmacName, mAuthMessage);
228 | } catch (InvalidKeyException | NoSuchAlgorithmException e) {
229 | mState = State.ENDED;
230 | throw new ScramException(e);
231 | }
232 | }
233 | }
234 |
--------------------------------------------------------------------------------
/lib/src/main/java/com/bolyartech/scram_sasl/common/ScramUtils.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2016 Ognyan Bankov
3 | *
4 | * All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | *
10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | 18 | package com.bolyartech.scram_sasl.common; 19 | 20 | 21 | import javax.crypto.Mac; 22 | import javax.crypto.spec.SecretKeySpec; 23 | import java.nio.charset.StandardCharsets; 24 | import java.security.InvalidKeyException; 25 | import java.security.MessageDigest; 26 | import java.security.NoSuchAlgorithmException; 27 | 28 | 29 | /** 30 | * Provides static methods for working with SCRAM/SASL 31 | */ 32 | @SuppressWarnings({"WeakerAccess", "unused"}) 33 | public class ScramUtils { 34 | private static final byte[] INT_1 = new byte[]{0, 0, 0, 1}; 35 | 36 | 37 | private ScramUtils() { 38 | throw new AssertionError("non-instantiable utility class"); 39 | } 40 | 41 | 42 | /** 43 | * Generates salted password. 44 | * 45 | * @param password Clear form password, i.e. what user typed 46 | * @param salt Salt to be used 47 | * @param iterationsCount Iterations for 'salting' 48 | * @param hmacName HMAC to be used 49 | * @return salted password 50 | * @throws InvalidKeyException if internal error occur while working with SecretKeySpec 51 | * @throws NoSuchAlgorithmException if hmacName is not supported by the java 52 | */ 53 | public static byte[] generateSaltedPassword(final String password, 54 | byte[] salt, 55 | int iterationsCount, 56 | String hmacName) throws InvalidKeyException, NoSuchAlgorithmException { 57 | 58 | 59 | Mac mac = createHmac(password.getBytes(StandardCharsets.US_ASCII), hmacName); 60 | 61 | mac.update(salt); 62 | mac.update(INT_1); 63 | byte[] result = mac.doFinal(); 64 | 65 | byte[] previous = null; 66 | for (int i = 1; i < iterationsCount; i++) { 67 | mac.update(previous != null ? previous : result); 68 | previous = mac.doFinal(); 69 | for (int x = 0; x < result.length; x++) { 70 | result[x] ^= previous[x]; 71 | } 72 | } 73 | 74 | return result; 75 | } 76 | 77 | 78 | /** 79 | * Creates HMAC 80 | * 81 | * @param keyBytes key 82 | * @param hmacName HMAC name 83 | * @return Mac 84 | * @throws InvalidKeyException if internal error occur while working with SecretKeySpec 85 | * @throws NoSuchAlgorithmException if hmacName is not supported by the java 86 | */ 87 | public static Mac createHmac(final byte[] keyBytes, String hmacName) throws NoSuchAlgorithmException, 88 | InvalidKeyException { 89 | 90 | SecretKeySpec key = new SecretKeySpec(keyBytes, hmacName); 91 | Mac mac = Mac.getInstance(hmacName); 92 | mac.init(key); 93 | return mac; 94 | } 95 | 96 | 97 | /** 98 | * Computes HMAC byte array for given string 99 | * 100 | * @param key key 101 | * @param hmacName HMAC name 102 | * @param string string for which HMAC will be computed 103 | * @return computed HMAC 104 | * @throws InvalidKeyException if internal error occur while working with SecretKeySpec 105 | * @throws NoSuchAlgorithmException if hmacName is not supported by the java 106 | */ 107 | public static byte[] computeHmac(final byte[] key, String hmacName, final String string) 108 | throws InvalidKeyException, NoSuchAlgorithmException { 109 | 110 | Mac mac = createHmac(key, hmacName); 111 | mac.update(string.getBytes(StandardCharsets.US_ASCII)); 112 | return mac.doFinal(); 113 | } 114 | 115 | 116 | /** 117 | * Checks if string is null or empty 118 | * 119 | * @param string String to be tested 120 | * @return true if the string is null or empty, false otherwise 121 | */ 122 | public static boolean isNullOrEmpty(String string) { 123 | return string == null || string.length() == 0; // string.isEmpty() in Java 6 124 | } 125 | 126 | 127 | /** 128 | * Computes the data associated with new password like salted password, keys, etc 129 | *
130 | * This method is supposed to be used by a server when user provides new clear form password. 131 | * We don't want to save it that way so we generate salted password and store it along with 132 | * other data required by the SCRAM mechanism 133 | * 134 | * @param passwordClearText Clear form password, i.e. as provided by the user 135 | * @param salt Salt to be used 136 | * @param iterations Iterations for 'salting' 137 | * @param hmacName HMAC name to be used 138 | * @param digestName Digest name to be used 139 | * @return new password data 140 | * @throws NoSuchAlgorithmException if hmacName is not supported by the java 141 | * @throws InvalidKeyException InvalidKeyException if internal error occur while working with SecretKeySpec 142 | */ 143 | public static NewPasswordByteArrayData newPassword(String passwordClearText, 144 | byte[] salt, 145 | int iterations, 146 | String digestName, 147 | String hmacName) 148 | throws NoSuchAlgorithmException, InvalidKeyException { 149 | 150 | if (!hmacName.toLowerCase().startsWith("hmac")) { 151 | throw new IllegalArgumentException("Invalid HMAC. Please check digestName and hmacName " + 152 | "to be in correct order"); 153 | } 154 | 155 | byte[] saltedPassword = ScramUtils.generateSaltedPassword(passwordClearText, 156 | salt, 157 | iterations, 158 | hmacName); 159 | 160 | byte[] clientKey = ScramUtils.computeHmac(saltedPassword, hmacName, "Client Key"); 161 | byte[] storedKey = MessageDigest.getInstance(digestName).digest(clientKey); 162 | byte[] serverKey = ScramUtils.computeHmac(saltedPassword, hmacName, "Server Key"); 163 | 164 | return new NewPasswordByteArrayData(saltedPassword, salt, clientKey, storedKey, serverKey, iterations); 165 | } 166 | 167 | 168 | /** 169 | * Transforms NewPasswordByteArrayData into NewPasswordStringData into database friendly (string) representation 170 | * Uses Base64 to encode the byte arrays into strings 171 | * 172 | * @param ba Byte array data 173 | * @return String data 174 | */ 175 | public static NewPasswordStringData byteArrayToStringData(NewPasswordByteArrayData ba) { 176 | return new NewPasswordStringData(Base64.encodeBytes(ba.saltedPassword, 177 | Base64.DONT_BREAK_LINES), 178 | 179 | Base64.encodeBytes(ba.salt, Base64.DONT_BREAK_LINES), 180 | Base64.encodeBytes(ba.clientKey, Base64.DONT_BREAK_LINES), 181 | Base64.encodeBytes(ba.storedKey, Base64.DONT_BREAK_LINES), 182 | Base64.encodeBytes(ba.serverKey, Base64.DONT_BREAK_LINES), 183 | ba.iterations 184 | ); 185 | } 186 | 187 | 188 | /** 189 | * New password data in database friendly format, i.e. Base64 encoded strings 190 | */ 191 | @SuppressWarnings("unused") 192 | public static class NewPasswordStringData { 193 | /** 194 | * Salted password 195 | */ 196 | public final String saltedPassword; 197 | /** 198 | * Used salt 199 | */ 200 | public final String salt; 201 | /** 202 | * Client key 203 | */ 204 | public final String clientKey; 205 | /** 206 | * Stored key 207 | */ 208 | public final String storedKey; 209 | /** 210 | * Server key 211 | */ 212 | public final String serverKey; 213 | /** 214 | * Iterations for slating 215 | */ 216 | public final int iterations; 217 | 218 | 219 | /** 220 | * Creates new NewPasswordStringData 221 | * 222 | * @param saltedPassword Salted password 223 | * @param salt Used salt 224 | * @param clientKey Client key 225 | * @param storedKey Stored key 226 | * @param serverKey Server key 227 | * @param iterations Iterations for slating 228 | */ 229 | public NewPasswordStringData(String saltedPassword, 230 | String salt, 231 | String clientKey, 232 | String storedKey, 233 | String serverKey, 234 | int iterations) { 235 | this.saltedPassword = saltedPassword; 236 | this.salt = salt; 237 | this.clientKey = clientKey; 238 | this.storedKey = storedKey; 239 | this.serverKey = serverKey; 240 | this.iterations = iterations; 241 | } 242 | } 243 | 244 | 245 | /** 246 | * New password data in byte array format 247 | */ 248 | @SuppressWarnings("unused") 249 | public static class NewPasswordByteArrayData { 250 | /** 251 | * Salted password 252 | */ 253 | public final byte[] saltedPassword; 254 | /** 255 | * Used salt 256 | */ 257 | public final byte[] salt; 258 | /** 259 | * Client key 260 | */ 261 | public final byte[] clientKey; 262 | /** 263 | * Stored key 264 | */ 265 | public final byte[] storedKey; 266 | /** 267 | * Server key 268 | */ 269 | public final byte[] serverKey; 270 | /** 271 | * Iterations for slating 272 | */ 273 | public final int iterations; 274 | 275 | 276 | /** 277 | * Creates new NewPasswordByteArrayData 278 | * 279 | * @param saltedPassword Salted password 280 | * @param salt Used salt 281 | * @param clientKey Client key 282 | * @param storedKey Stored key 283 | * @param serverKey Server key 284 | * @param iterations Iterations for slating 285 | */ 286 | public NewPasswordByteArrayData(byte[] saltedPassword, 287 | byte[] salt, 288 | byte[] clientKey, 289 | byte[] storedKey, 290 | byte[] serverKey, 291 | int iterations) { 292 | 293 | this.saltedPassword = saltedPassword; 294 | this.salt = salt; 295 | this.clientKey = clientKey; 296 | this.storedKey = storedKey; 297 | this.serverKey = serverKey; 298 | this.iterations = iterations; 299 | } 300 | } 301 | } 302 | -------------------------------------------------------------------------------- /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 | # SCRAM SASL authentication for Java 2 | Java library that implements SCRAM SASL ([RFC5802](https://tools.ietf.org/html/rfc5802)) for both server and client. 3 | 4 | Includes SHA-1, SHA-256, SHA-512 implementations and examples (you can easily create implementation that uses your own hashing function and digest). 5 | 6 | This library was created because there was no Java-friendly implementation for client or server. Existing implementations were looking like a port of C/C++ code and/or was using [Oracle's SASL API](https://docs.oracle.com/javase/8/docs/technotes/guides/security/sasl/sasl-refguide.html) which is a) way too abstract for the 99% of the projects and b) not available on all platforms (Android, OpenJDK). Current library intentionally uses simple and straightforward approach in order to provide easy integration. 7 | 8 | 9 | # Why use SCRAM? 10 | Please go to this [Wikipedia page](https://en.wikipedia.org/wiki/Salted_Challenge_Response_Authentication_Mechanism) for a good explanation why it is good idea to use SCRAM. 11 | 12 | In short: SCRAM provides more security in (at least) two aspects: 13 | 14 | 1. You don't keep the passwords in your database weakly hashed (MD5/SHA-1) and thus even if your database is stolen the attacker cannot guess the passwords; 15 | 2. During the authentication passwords are never send in clear form thus eliminating the use of man-in-the-middle attack. 16 | 17 | 18 | # How to use the library 19 | There are two ways to use the library: 20 | * High level usage - which is described bellow and provides classes that can be used as a base for your client or server (`Scram*SaslClientProcessor`, `Scram*SaslServerProcessor`) 21 | * Low level usage - you can use directly/manually the building blocks in order to create your own implementation of server/client (`ScramClientFunctionalityImpl`, `ScramServerFunctionalityImpl`). 22 | 23 | ## Server 24 | 25 | To support SCRAM your server will need two distinct functionalities: user registration and user authentication. 26 | 27 | Bellow are the simplified explanations (for detailed ones please read the [standard](https://tools.ietf.org/html/rfc5802)). 28 | 29 | User registration goes like this: 30 | 1. An user fills in registration form 31 | 2. The user sends the data which contains username and password along with potential other fields 32 | 3. The server generates `salt`, `serverKey`, `storedKey` and `iterations` and stores them along with the username locally usually in DB. Please note that the password is not stored in clear or hashed form. 33 | 34 | User authentication goes like this: 35 | 1. Client sends the *first message* which contains the username 36 | 2. Server loads the user data for that username which contain the `salt`, `serverKey`, `storedKey` and `iterations` and sends back the `salt` and the `iterations` value (*server's first message*). 37 | 3. Client uses the `salt` and the `iterations` to 'salt' his password and compute a `proof` which he sends back to the server (*client's final message*) 38 | 4. Server uses the `serverKey` and the `storedKey` to analyze the `proof` and determine if it is correct and sends to the client its *final message*. 39 | 40 | 41 | 42 | ### User registration 43 | 44 | For the user registration you will need the static method `ScramUtils.newPassword()`: 45 | 46 | ```Java 47 | // given we have username and password in clear text received from the user 48 | String username = ... 49 | String password = ... 50 | 51 | // ... we generate salt 52 | SecureRandom random = new SecureRandom(); 53 | byte[] salt = new byte[24]; 54 | random.nextBytes(salt); 55 | 56 | // ... then we generate value for the 'iterations' between 4096 and 6000 57 | int iterations = 4096 + random.nextInt(1092); 58 | 59 | // Compute user data using SHA-256 60 | NewPasswordByteArrayData userDataArr = ScramUtils.newPassword(password, 61 | salt, 62 | iterations, 63 | "HmacSHA256", 64 | "SHA-256" 65 | ); 66 | 67 | // transform the data into DB friendly format i.e. String 68 | NewPasswordStringData userDataString = ScramUtils.byteArrayToStringData(userDataArr); 69 | 70 | // save the user data in your DB using `username` as key 71 | ... 72 | ``` 73 | 74 | ### Authentication (login) 75 | For your server you will need some of the `ScramSha*SaslServerProcessor` classes in order to process the authentication sequence. You will have to create a new instance per each authentication. 76 | 77 | There are 4 parameters needed to create an instance: 78 | * `long connectionId` - usually a server tracks its clients by connection ID which is assigned upon connection. Use this ID as first parameter. If your server uses something different than a `long` you will need to modify the lib (initially it was created to use generic parameter for `connectionId` but later I've decided that it is an overkill which only complicates the implementation). 79 | * [Listener](https://github.com/ogrebgr/scram-sasl/blob/master/lib/src/main/java/com/bolyartech/scram_sasl/server/ScramSaslServerProcessor.java#L118) `listener` - you will have to provide implementation of `ScramSaslServerProcessor.Listener`. It has `void onSuccess(long connectionId);` and `void onFailure(long connectionId);` methods which will be used to notify your code that authentication has completed. 80 | * [UserDataLoader](https://github.com/ogrebgr/scram-sasl/blob/master/lib/src/main/java/com/bolyartech/scram_sasl/server/ScramSaslServerProcessor.java#L105) `userDataLoader` - you will have to provide implementation that loads the user data from the DB and calls back the processor's `onUserDataLoaded()`. 81 | * [Sender](https://github.com/ogrebgr/scram-sasl/blob/master/lib/src/main/java/com/bolyartech/scram_sasl/server/ScramSaslServerProcessor.java#L135) `sender` - you will have to provide implementation that sends messages to the clients 82 | 83 | ```Java 84 | // usually you will have global listener, user loader and sender 85 | mListener = new Listener() {...} 86 | mLoader = new UserDataLoader() {...} 87 | mSender = new Sender() {...} 88 | ``` 89 | 90 | When a client connects: 91 | ```Java 92 | // you will have connection ID 93 | long connectionId = ... 94 | ScramSaslServerProcessor processor = new ScramSha256SaslServerProcessor( 95 | connectionId, 96 | listener, 97 | loader, 98 | sender 99 | ); 100 | 101 | // usually you will have a map where processors are kept 102 | mScramProcessors.put(connectionId, processor); 103 | ``` 104 | 105 | When you receive message: 106 | ```Java 107 | void onMessageReceived(long connectionId, String message) { 108 | // first you get the needed processor 109 | ScramSaslServerProcessor processor = mScramProcessors.get(connectionId); 110 | 111 | // then you feed in the message 112 | processor.onMessage(message); 113 | 114 | // from this point on everything is automatic and you just wait for onSuccess 115 | // or onFailure call or abort the procedure with abort() (if for example it takes too long) 116 | } 117 | ``` 118 | 119 | After creating the instance you just wait for the *first client message* and feed it to the processor via `onMessage(String message)`. The processor will extract the username from it and call your implementation of UserDataLoader's `loadUserData(String username, long connectionId, ScramSaslServerProcessor processor)`. There you will initiate the loading of the data (by adding the request to some queue for example) and when the data is available you will call processor's `onUserDataLoaded(UserData data)` which will prepare the `first server message` and send it to the client using your `Sender` implementation. 120 | 121 | On the other side client will prepare it's *final message* and send it back to your server. When you receive it you will feed it again to `onMessage(String message)` and processor will prepare the `server final message` and send it. After that your listener will be called with `onSuccess` or `onFailure` depending on the success of the authentication. Please note that `onFailure` might be called at any stage of the authentication procedure if there is a problem with the authentication. 122 | 123 | You must take care on your own to interrupt the sequence with `abort()` after given timeout if there is no outcome. 124 | 125 | 126 | For an example please see the [SCRAM SHA-256 SASL example](https://github.com/ogrebgr/scram-sasl/blob/master/examples/src/main/java/com/bolyartech/scram_sasl/examples/ScramSha256Example.java). 127 | 128 | 129 | ## Client 130 | 131 | To authenticate as a client you will need an instance of some of the `ScramSha*SaslClientProcessor` classes. 132 | 133 | There are two parameters needed to create an instance: 134 | * [Listener](https://github.com/ogrebgr/scram-sasl/blob/master/lib/src/main/java/com/bolyartech/scram_sasl/client/ScramSaslClientProcessor.java#L52) `listener` - will be used to notify your code of the authentication outcome. Implementation of `ScramSaslClientProcessor.Listener`; 135 | * [Sender](https://github.com/ogrebgr/scram-sasl/blob/master/lib/src/main/java/com/bolyartech/scram_sasl/client/ScramSaslClientProcessor.java#L68) `sender` - will be used to send messages to the server. Implementation of `ScramSaslClientProcessor.Sender` 136 | 137 | After creating the instance you have to initiate the sequence by calling the `start()` method of the processor: 138 | 139 | ```Java 140 | // get the username and password from the UI 141 | String username = ... 142 | String password = ... 143 | 144 | Listener listener = new Listener() {...}; 145 | Sender sender = new Sender() {...}; 146 | 147 | ScramSaslClientProcessor processor = new ScramSha256SaslClientProcessor( 148 | listener, sender); 149 | 150 | processor.start(username, password); 151 | ``` 152 | When you call `start()` `first client message` will be prepared and send to the server. 153 | 154 | Now we are waiting for server to reply. When you receive message from the server you have to feed it to the processor: 155 | 156 | ```Java 157 | // message is received 158 | String message = ... 159 | processor.onMessage(message); 160 | ``` 161 | From that point on everything goes automatically. When the sequence is completed your listener will be notified with `onSuccess` or `onFailure` depending on the success of the authentication. Please note that `onFailure` might be called at any stage of the authentication procedure if there is a problem with the authentication. 162 | 163 | You must take care on your own to interrupt the sequence with `abort()` after given timeout if there is no outcome. 164 | 165 | # Download 166 | 167 | Gradle 168 | 169 | `compile 'com.bolyartech.scram_sasl:scram_sasl:2.0.2'` 170 | 171 | Don't forget to include `jcenter` in your repos like: 172 | 173 | ``` 174 | repositories { 175 | jcenter() 176 | } 177 | ``` 178 | 179 | # Credits 180 | Server implementation is based on [ScramSha1SaslServer](http://download.igniterealtime.org/openfire/docs/4.0.2/documentation/javadoc/org/jivesoftware/openfire/sasl/ScramSha1SaslServer.html) created by Richard Midwinter for the 181 | [OpenFire XMPP Server](https://www.igniterealtime.org/projects/openfire/) 182 | 183 | Client implementatin is based on AbstractScramSaslClient from [Qpid JMS](https://qpid.apache.org/components/jms/) project. 184 | 185 | StringPrep and Normalizer are using code created by Glenn Maynard with some minor modifications in order to suppress typo warnings in Intellij IDEA. 186 | 187 | 188 | # License 189 | Copyright 2016 Ognyan Bankov 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 | -------------------------------------------------------------------------------- /lib/src/main/java/com/bolyartech/scram_sasl/common/StringPrep.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2011 Glenn Maynard 3 | *
4 | * All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | *
10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.bolyartech.scram_sasl.common; 17 | 18 | 19 | import java.util.*; 20 | 21 | 22 | /** 23 | * rfc3454 StringPrep, with an implementation of rfc4013 SASLPrep. 24 | *
25 | * StringPrep case folding is unimplemented, as it's not required by SASLPrep.
26 | */
27 | @SuppressWarnings({"WeakerAccess", "unused", "SpellCheckingInspection", "JavaDoc"})
28 | public class StringPrep {
29 | /**
30 | * A representation of sets of character classes.
31 | */
32 | @SuppressWarnings({"SpellCheckingInspection", "JavaDoc"})
33 | static protected class CharClass {
34 | // Each character class is a set of [start,end] tuples; each tuple is represented
35 | // in the mapping as mapping[start] = (end-start+1).
36 | // Invariants:
37 | // - tupleStart is in ascending order.
38 | // - All values in tupleCount are >= 1 (no empty ranges).
39 | // - tupleStart.size() == tupleCount.size().
40 | // - There will be no overlapping ranges.
41 | //
42 | // TreeMap would work well for this, but it was missing basic operations like lowerEntry
43 | // until JDK1.6, which we don't want to depend on.
44 | private final ArrayList