├── .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 tupleStart = new ArrayList<>(); 45 | private final ArrayList tupleCount = new ArrayList<>(); 46 | 47 | 48 | @SuppressWarnings("ForLoopReplaceableByForEach") 49 | static CharClass fromList(int[] charMap) { 50 | SortedMap mapping = new TreeMap<>(); 51 | for (int i = 0; i < charMap.length; ++i) 52 | mapping.put(charMap[i], 1); 53 | 54 | return new CharClass(mapping); 55 | } 56 | 57 | 58 | static CharClass fromRanges(int[] charMap) { 59 | // There must be an even number of tuples in RANGES tables. 60 | if ((charMap.length % 2) != 0) 61 | throw new IllegalArgumentException("Invalid character list size"); 62 | 63 | SortedMap mapping = new TreeMap<>(); 64 | for (int i = 0; i < charMap.length; i += 2) { 65 | int start = charMap[i]; 66 | int end = charMap[i + 1]; 67 | int count = end - start + 1; 68 | mapping.put(start, count); 69 | } 70 | 71 | return new CharClass(mapping); 72 | } 73 | 74 | 75 | static CharClass fromClasses(CharClass... classes) { 76 | SortedMap mapping = new TreeMap<>(); 77 | for (CharClass charClass : classes) { 78 | for (int i = 0; i < charClass.tupleStart.size(); ++i) { 79 | int start = charClass.tupleStart.get(i); 80 | int count = charClass.tupleCount.get(i); 81 | mapping.put(start, count); 82 | } 83 | } 84 | 85 | return new CharClass(mapping); 86 | } 87 | 88 | 89 | private CharClass(SortedMap mappings) { 90 | for (Map.Entry pair : mappings.entrySet()) { 91 | int start = pair.getKey(); 92 | int count = pair.getValue(); 93 | 94 | // Coalesce overlapping ranges. 95 | if (tupleStart.size() > 0) { 96 | int prevIndex = tupleStart.size() - 1; 97 | int prevStart = tupleStart.get(prevIndex); 98 | int prevCount = tupleCount.get(prevIndex); 99 | // If the previous tuple is (0,1), and this tuple is (1,5), then 100 | // coalesce into (0,6). If ths previous tuple is (0,3) and this 101 | // tuple is (1,3), coalesce into (0,4). 102 | if (prevStart + prevCount >= start) { 103 | int endPos = start + count; 104 | int newCount = endPos - prevStart; 105 | tupleCount.set(prevIndex, newCount); 106 | continue; 107 | } 108 | } 109 | 110 | tupleStart.add(start); 111 | tupleCount.add(count); 112 | } 113 | } 114 | 115 | 116 | public boolean isCharInClass(int c) { 117 | // Find the first entry in tupleStart which is <= c. Java's binarySearch 118 | // API is a bit braindamaged (it was written only considering search-and-insert), 119 | // so we have to jump some hoops to get this. 120 | int pos = Collections.binarySearch(tupleStart, c); 121 | if (pos >= 0) { 122 | // If pos >= 0, tupleStart[pos] == c. The value is the start of a range, 123 | // so it's included in the class. 124 | return true; 125 | //while(pos > 0 && tupleStart.get(pos-1) == c) 126 | // --pos; 127 | } 128 | // -pos - 1 is the lowest index where tupleStart[pos] > c. If this is the 129 | // first entry, then c is below all entries in the class. 130 | pos = -pos - 1; 131 | if (pos == 0) 132 | return false; 133 | --pos; 134 | 135 | // tupleStart[pos] is <= c. 136 | int start = tupleStart.get(pos); 137 | int count = tupleCount.get(pos); 138 | return start <= c && c < start + count; 139 | 140 | } 141 | } 142 | 143 | /** A.1 Unassigned code points in Unicode 3.2 */ 144 | static final CharClass A1 = CharClass.fromRanges(new int[]{ 145 | 0x0221, 0x0221, 0x0234, 0x024F, 0x02AE, 0x02AF, 0x02EF, 0x02FF, 0x0350, 0x035F, 0x0370, 0x0373, 146 | 0x0376, 0x0379, 0x037B, 0x037D, 0x037F, 0x0383, 0x038B, 0x038B, 0x038D, 0x038D, 0x03A2, 0x03A2, 147 | 0x03CF, 0x03CF, 0x03F7, 0x03FF, 0x0487, 0x0487, 0x04CF, 0x04CF, 0x04F6, 0x04F7, 0x04FA, 0x04FF, 148 | 0x0510, 0x0530, 0x0557, 0x0558, 0x0560, 0x0560, 0x0588, 0x0588, 0x058B, 0x0590, 0x05A2, 0x05A2, 149 | 0x05BA, 0x05BA, 0x05C5, 0x05CF, 0x05EB, 0x05EF, 0x05F5, 0x060B, 0x060D, 0x061A, 0x061C, 0x061E, 150 | 0x0620, 0x0620, 0x063B, 0x063F, 0x0656, 0x065F, 0x06EE, 0x06EF, 0x06FF, 0x06FF, 0x070E, 0x070E, 151 | 0x072D, 0x072F, 0x074B, 0x077F, 0x07B2, 0x0900, 0x0904, 0x0904, 0x093A, 0x093B, 0x094E, 0x094F, 152 | 0x0955, 0x0957, 0x0971, 0x0980, 0x0984, 0x0984, 0x098D, 0x098E, 0x0991, 0x0992, 0x09A9, 0x09A9, 153 | 0x09B1, 0x09B1, 0x09B3, 0x09B5, 0x09BA, 0x09BB, 0x09BD, 0x09BD, 0x09C5, 0x09C6, 0x09C9, 0x09CA, 154 | 0x09CE, 0x09D6, 0x09D8, 0x09DB, 0x09DE, 0x09DE, 0x09E4, 0x09E5, 0x09FB, 0x0A01, 0x0A03, 0x0A04, 155 | 0x0A0B, 0x0A0E, 0x0A11, 0x0A12, 0x0A29, 0x0A29, 0x0A31, 0x0A31, 0x0A34, 0x0A34, 0x0A37, 0x0A37, 156 | 0x0A3A, 0x0A3B, 0x0A3D, 0x0A3D, 0x0A43, 0x0A46, 0x0A49, 0x0A4A, 0x0A4E, 0x0A58, 0x0A5D, 0x0A5D, 157 | 0x0A5F, 0x0A65, 0x0A75, 0x0A80, 0x0A84, 0x0A84, 0x0A8C, 0x0A8C, 0x0A8E, 0x0A8E, 0x0A92, 0x0A92, 158 | 0x0AA9, 0x0AA9, 0x0AB1, 0x0AB1, 0x0AB4, 0x0AB4, 0x0ABA, 0x0ABB, 0x0AC6, 0x0AC6, 0x0ACA, 0x0ACA, 159 | 0x0ACE, 0x0ACF, 0x0AD1, 0x0ADF, 0x0AE1, 0x0AE5, 0x0AF0, 0x0B00, 0x0B04, 0x0B04, 0x0B0D, 0x0B0E, 160 | 0x0B11, 0x0B12, 0x0B29, 0x0B29, 0x0B31, 0x0B31, 0x0B34, 0x0B35, 0x0B3A, 0x0B3B, 0x0B44, 0x0B46, 161 | 0x0B49, 0x0B4A, 0x0B4E, 0x0B55, 0x0B58, 0x0B5B, 0x0B5E, 0x0B5E, 0x0B62, 0x0B65, 0x0B71, 0x0B81, 162 | 0x0B84, 0x0B84, 0x0B8B, 0x0B8D, 0x0B91, 0x0B91, 0x0B96, 0x0B98, 0x0B9B, 0x0B9B, 0x0B9D, 0x0B9D, 163 | 0x0BA0, 0x0BA2, 0x0BA5, 0x0BA7, 0x0BAB, 0x0BAD, 0x0BB6, 0x0BB6, 0x0BBA, 0x0BBD, 0x0BC3, 0x0BC5, 164 | 0x0BC9, 0x0BC9, 0x0BCE, 0x0BD6, 0x0BD8, 0x0BE6, 0x0BF3, 0x0C00, 0x0C04, 0x0C04, 0x0C0D, 0x0C0D, 165 | 0x0C11, 0x0C11, 0x0C29, 0x0C29, 0x0C34, 0x0C34, 0x0C3A, 0x0C3D, 0x0C45, 0x0C45, 0x0C49, 0x0C49, 166 | 0x0C4E, 0x0C54, 0x0C57, 0x0C5F, 0x0C62, 0x0C65, 0x0C70, 0x0C81, 0x0C84, 0x0C84, 0x0C8D, 0x0C8D, 167 | 0x0C91, 0x0C91, 0x0CA9, 0x0CA9, 0x0CB4, 0x0CB4, 0x0CBA, 0x0CBD, 0x0CC5, 0x0CC5, 0x0CC9, 0x0CC9, 168 | 0x0CCE, 0x0CD4, 0x0CD7, 0x0CDD, 0x0CDF, 0x0CDF, 0x0CE2, 0x0CE5, 0x0CF0, 0x0D01, 0x0D04, 0x0D04, 169 | 0x0D0D, 0x0D0D, 0x0D11, 0x0D11, 0x0D29, 0x0D29, 0x0D3A, 0x0D3D, 0x0D44, 0x0D45, 0x0D49, 0x0D49, 170 | 0x0D4E, 0x0D56, 0x0D58, 0x0D5F, 0x0D62, 0x0D65, 0x0D70, 0x0D81, 0x0D84, 0x0D84, 0x0D97, 0x0D99, 171 | 0x0DB2, 0x0DB2, 0x0DBC, 0x0DBC, 0x0DBE, 0x0DBF, 0x0DC7, 0x0DC9, 0x0DCB, 0x0DCE, 0x0DD5, 0x0DD5, 172 | 0x0DD7, 0x0DD7, 0x0DE0, 0x0DF1, 0x0DF5, 0x0E00, 0x0E3B, 0x0E3E, 0x0E5C, 0x0E80, 0x0E83, 0x0E83, 173 | 0x0E85, 0x0E86, 0x0E89, 0x0E89, 0x0E8B, 0x0E8C, 0x0E8E, 0x0E93, 0x0E98, 0x0E98, 0x0EA0, 0x0EA0, 174 | 0x0EA4, 0x0EA4, 0x0EA6, 0x0EA6, 0x0EA8, 0x0EA9, 0x0EAC, 0x0EAC, 0x0EBA, 0x0EBA, 0x0EBE, 0x0EBF, 175 | 0x0EC5, 0x0EC5, 0x0EC7, 0x0EC7, 0x0ECE, 0x0ECF, 0x0EDA, 0x0EDB, 0x0EDE, 0x0EFF, 0x0F48, 0x0F48, 176 | 0x0F6B, 0x0F70, 0x0F8C, 0x0F8F, 0x0F98, 0x0F98, 0x0FBD, 0x0FBD, 0x0FCD, 0x0FCE, 0x0FD0, 0x0FFF, 177 | 0x1022, 0x1022, 0x1028, 0x1028, 0x102B, 0x102B, 0x1033, 0x1035, 0x103A, 0x103F, 0x105A, 0x109F, 178 | 0x10C6, 0x10CF, 0x10F9, 0x10FA, 0x10FC, 0x10FF, 0x115A, 0x115E, 0x11A3, 0x11A7, 0x11FA, 0x11FF, 179 | 0x1207, 0x1207, 0x1247, 0x1247, 0x1249, 0x1249, 0x124E, 0x124F, 0x1257, 0x1257, 0x1259, 0x1259, 180 | 0x125E, 0x125F, 0x1287, 0x1287, 0x1289, 0x1289, 0x128E, 0x128F, 0x12AF, 0x12AF, 0x12B1, 0x12B1, 181 | 0x12B6, 0x12B7, 0x12BF, 0x12BF, 0x12C1, 0x12C1, 0x12C6, 0x12C7, 0x12CF, 0x12CF, 0x12D7, 0x12D7, 182 | 0x12EF, 0x12EF, 0x130F, 0x130F, 0x1311, 0x1311, 0x1316, 0x1317, 0x131F, 0x131F, 0x1347, 0x1347, 183 | 0x135B, 0x1360, 0x137D, 0x139F, 0x13F5, 0x1400, 0x1677, 0x167F, 0x169D, 0x169F, 0x16F1, 0x16FF, 184 | 0x170D, 0x170D, 0x1715, 0x171F, 0x1737, 0x173F, 0x1754, 0x175F, 0x176D, 0x176D, 0x1771, 0x1771, 185 | 0x1774, 0x177F, 0x17DD, 0x17DF, 0x17EA, 0x17FF, 0x180F, 0x180F, 0x181A, 0x181F, 0x1878, 0x187F, 186 | 0x18AA, 0x1DFF, 0x1E9C, 0x1E9F, 0x1EFA, 0x1EFF, 0x1F16, 0x1F17, 0x1F1E, 0x1F1F, 0x1F46, 0x1F47, 187 | 0x1F4E, 0x1F4F, 0x1F58, 0x1F58, 0x1F5A, 0x1F5A, 0x1F5C, 0x1F5C, 0x1F5E, 0x1F5E, 0x1F7E, 0x1F7F, 188 | 0x1FB5, 0x1FB5, 0x1FC5, 0x1FC5, 0x1FD4, 0x1FD5, 0x1FDC, 0x1FDC, 0x1FF0, 0x1FF1, 0x1FF5, 0x1FF5, 189 | 0x1FFF, 0x1FFF, 0x2053, 0x2056, 0x2058, 0x205E, 0x2064, 0x2069, 0x2072, 0x2073, 0x208F, 0x209F, 190 | 0x20B2, 0x20CF, 0x20EB, 0x20FF, 0x213B, 0x213C, 0x214C, 0x2152, 0x2184, 0x218F, 0x23CF, 0x23FF, 191 | 0x2427, 0x243F, 0x244B, 0x245F, 0x24FF, 0x24FF, 0x2614, 0x2615, 0x2618, 0x2618, 0x267E, 0x267F, 192 | 0x268A, 0x2700, 0x2705, 0x2705, 0x270A, 0x270B, 0x2728, 0x2728, 0x274C, 0x274C, 0x274E, 0x274E, 193 | 0x2753, 0x2755, 0x2757, 0x2757, 0x275F, 0x2760, 0x2795, 0x2797, 0x27B0, 0x27B0, 0x27BF, 0x27CF, 194 | 0x27EC, 0x27EF, 0x2B00, 0x2E7F, 0x2E9A, 0x2E9A, 0x2EF4, 0x2EFF, 0x2FD6, 0x2FEF, 0x2FFC, 0x2FFF, 195 | 0x3040, 0x3040, 0x3097, 0x3098, 0x3100, 0x3104, 0x312D, 0x3130, 0x318F, 0x318F, 0x31B8, 0x31EF, 196 | 0x321D, 0x321F, 0x3244, 0x3250, 0x327C, 0x327E, 0x32CC, 0x32CF, 0x32FF, 0x32FF, 0x3377, 0x337A, 197 | 0x33DE, 0x33DF, 0x33FF, 0x33FF, 0x4DB6, 0x4DFF, 0x9FA6, 0x9FFF, 0xA48D, 0xA48F, 0xA4C7, 0xABFF, 198 | 0xD7A4, 0xD7FF, 0xFA2E, 0xFA2F, 0xFA6B, 0xFAFF, 0xFB07, 0xFB12, 0xFB18, 0xFB1C, 0xFB37, 0xFB37, 199 | 0xFB3D, 0xFB3D, 0xFB3F, 0xFB3F, 0xFB42, 0xFB42, 0xFB45, 0xFB45, 0xFBB2, 0xFBD2, 0xFD40, 0xFD4F, 200 | 0xFD90, 0xFD91, 0xFDC8, 0xFDCF, 0xFDFD, 0xFDFF, 0xFE10, 0xFE1F, 0xFE24, 0xFE2F, 0xFE47, 0xFE48, 201 | 0xFE53, 0xFE53, 0xFE67, 0xFE67, 0xFE6C, 0xFE6F, 0xFE75, 0xFE75, 0xFEFD, 0xFEFE, 0xFF00, 0xFF00, 202 | 0xFFBF, 0xFFC1, 0xFFC8, 0xFFC9, 0xFFD0, 0xFFD1, 0xFFD8, 0xFFD9, 0xFFDD, 0xFFDF, 0xFFE7, 0xFFE7, 203 | 0xFFEF, 0xFFF8, 204 | 0x10000, 0x102FF, 0x1031F, 0x1031F, 0x10324, 0x1032F, 0x1034B, 0x103FF, 0x10426, 0x10427, 205 | 0x1044E, 0x1CFFF, 0x1D0F6, 0x1D0FF, 0x1D127, 0x1D129, 0x1D1DE, 0x1D3FF, 0x1D455, 0x1D455, 206 | 0x1D49D, 0x1D49D, 0x1D4A0, 0x1D4A1, 0x1D4A3, 0x1D4A4, 0x1D4A7, 0x1D4A8, 0x1D4AD, 0x1D4AD, 207 | 0x1D4BA, 0x1D4BA, 0x1D4BC, 0x1D4BC, 0x1D4C1, 0x1D4C1, 0x1D4C4, 0x1D4C4, 0x1D506, 0x1D506, 208 | 0x1D50B, 0x1D50C, 0x1D515, 0x1D515, 0x1D51D, 0x1D51D, 0x1D53A, 0x1D53A, 0x1D53F, 0x1D53F, 209 | 0x1D545, 0x1D545, 0x1D547, 0x1D549, 0x1D551, 0x1D551, 0x1D6A4, 0x1D6A7, 0x1D7CA, 0x1D7CD, 210 | 0x1D800, 0x1FFFD, 0x2A6D7, 0x2F7FF, 0x2FA1E, 0x2FFFD, 0x30000, 0x3FFFD, 0x40000, 0x4FFFD, 211 | 0x50000, 0x5FFFD, 0x60000, 0x6FFFD, 0x70000, 0x7FFFD, 0x80000, 0x8FFFD, 0x90000, 0x9FFFD, 212 | 0xA0000, 0xAFFFD, 0xB0000, 0xBFFFD, 0xC0000, 0xCFFFD, 0xD0000, 0xDFFFD, 0xE0000, 0xE0000, 213 | 0xE0002, 0xE001F, 0xE0080, 0xEFFFD, 214 | }); 215 | 216 | /** B.1 Commonly mapped to nothing */ 217 | static final CharClass B1 = CharClass.fromList(new int[]{ 218 | 0x00AD, 0x034F, 0x1806, 0x180B, 0x180C, 0x180D, 0x200B, 0x200C, 0x200D, 0x2060, 219 | 0xFE00, 0xFE01, 0xFE02, 0xFE03, 0xFE04, 0xFE05, 0xFE06, 0xFE07, 0xFE08, 0xFE09, 220 | 0xFE0A, 0xFE0B, 0xFE0C, 0xFE0D, 0xFE0E, 0xFE0F, 0xFEFF, 221 | }); 222 | 223 | /** C.1.1 ASCII space characters */ 224 | static final CharClass C11 = CharClass.fromList(new int[]{ 225 | 0x0020 226 | }); 227 | 228 | /** C.1.2 Non-ASCII space characters */ 229 | static final CharClass C12 = CharClass.fromList(new int[]{ 230 | 0x00A0, 0x1680, 0x2000, 0x2001, 0x2002, 0x2003, 0x2004, 0x2005, 0x2006, 0x2007, 231 | 0x2008, 0x2009, 0x200A, 0x200B, 0x202F, 0x205F, 0x3000, 232 | }); 233 | 234 | /** C.2.1 ASCII control characters */ 235 | static final CharClass C21 = CharClass.fromList(new int[]{ 236 | 0x0000, 0x0001, 0x0002, 0x0003, 0x0004, 0x0005, 0x0006, 0x0007, 0x0008, 0x0009, 237 | 0x000A, 0x000B, 0x000C, 0x000D, 0x000E, 0x000F, 0x0010, 0x0011, 0x0012, 0x0013, 238 | 0x0014, 0x0015, 0x0016, 0x0017, 0x0018, 0x0019, 0x001A, 0x001B, 0x001C, 0x001D, 239 | 0x001E, 0x001F, 0x007F 240 | }); 241 | 242 | /** C.2.2 Non-ASCII control characters */ 243 | static final CharClass C22 = CharClass.fromList(new int[]{ 244 | 0x0080, 0x0081, 0x0082, 0x0083, 0x0084, 0x0085, 0x0086, 0x0087, 0x0088, 0x0089, 245 | 0x008A, 0x008B, 0x008C, 0x008D, 0x008E, 0x008F, 0x0090, 0x0091, 0x0092, 0x0093, 246 | 0x0094, 0x0095, 0x0096, 0x0097, 0x0098, 0x0099, 0x009A, 0x009B, 0x009C, 0x009D, 247 | 0x009E, 0x009F, 0x06DD, 0x070F, 0x180E, 0x200C, 0x200D, 0x2028, 0x2029, 0x2060, 248 | 0x2061, 0x2062, 0x2063, 0x206A, 0x206B, 0x206C, 0x206D, 0x206E, 0x206F, 0xFEFF, 249 | 0xFFF9, 0xFFFA, 0xFFFB, 0xFFFC, 250 | 0x1D173, 0x1D174, 0x1D175, 0x1D176, 0x1D177, 0x1D178, 0x1D179, 0x1D17A, 251 | }); 252 | 253 | /** C.3 Private use */ 254 | static final CharClass C3 = CharClass.fromRanges(new int[]{ 255 | 0xE000, 0xF8FF, 0xF0000, 0xFFFFD, 0x100000, 0x10FFFD, 256 | }); 257 | 258 | /** C.4 Non-character code points */ 259 | static final CharClass C4 = CharClass.fromRanges(new int[]{ 260 | 0xFDD0, 0xFDEF, 0xFFFE, 0xFFFF, 0x1FFFE, 0x1FFFF, 0x2FFFE, 0x2FFFF, 261 | 0x3FFFE, 0x3FFFF, 0x4FFFE, 0x4FFFF, 0x5FFFE, 0x5FFFF, 0x6FFFE, 0x6FFFF, 262 | 0x7FFFE, 0x7FFFF, 0x8FFFE, 0x8FFFF, 0x9FFFE, 0x9FFFF, 0xAFFFE, 0xAFFFF, 263 | 0xBFFFE, 0xBFFFF, 0xCFFFE, 0xCFFFF, 0xDFFFE, 0xDFFFF, 0xEFFFE, 0xEFFFF, 264 | 0xFFFFE, 0xFFFFF, 0x10FFFE, 0x10FFFF, 265 | }); 266 | 267 | /** C.5 Surrogate codes */ 268 | static final CharClass C5 = CharClass.fromRanges(new int[]{ 269 | 0xD800, 0xDFFF, 270 | }); 271 | 272 | /** C.6 Inappropriate for plain text */ 273 | static final CharClass C6 = CharClass.fromList(new int[]{ 274 | 0xFFF9, 0xFFFA, 0xFFFB, 0xFFFC, 0xFFFD, 275 | }); 276 | 277 | /** C.7 Inappropriate for canonical representation */ 278 | static final CharClass C7 = CharClass.fromList(new int[]{ 279 | 0x2FF0, 0x2FF1, 0x2FF2, 0x2FF3, 0x2FF4, 0x2FF5, 0x2FF6, 0x2FF7, 0x2FF8, 0x2FF9, 280 | 0x2FFA, 0x2FFB, 281 | }); 282 | 283 | /** C.8 Change display properties or are deprecated */ 284 | static final CharClass C8 = CharClass.fromList(new int[]{ 285 | 0x0340, 0x0341, 0x200E, 0x200F, 0x202A, 0x202B, 0x202C, 0x202D, 0x202E, 0x206A, 286 | 0x206B, 0x206C, 0x206D, 0x206E, 0x206F, 287 | }); 288 | 289 | /** C.9 Tagging characters (tuples) */ 290 | static final CharClass C9 = CharClass.fromRanges(new int[]{ 291 | 0xE0001, 0xE0001, 0xE0020, 0xE007F, 292 | }); 293 | 294 | /** D.1 Characters with bidirectional property "R" or "AL" */ 295 | static final CharClass D1 = CharClass.fromRanges(new int[]{ 296 | 0x05BE, 0x05BE, 0x05C0, 0x05C0, 0x05C3, 0x05C3, 0x05D0, 0x05EA, 0x05F0, 0x05F4, 297 | 0x061B, 0x061B, 0x061F, 0x061F, 0x0621, 0x063A, 0x0640, 0x064A, 0x066D, 0x066F, 298 | 0x0671, 0x06D5, 0x06DD, 0x06DD, 0x06E5, 0x06E6, 0x06FA, 0x06FE, 0x0700, 0x070D, 299 | 0x0710, 0x0710, 0x0712, 0x072C, 0x0780, 0x07A5, 0x07B1, 0x07B1, 0x200F, 0x200F, 300 | 0xFB1D, 0xFB1D, 0xFB1F, 0xFB28, 0xFB2A, 0xFB36, 0xFB38, 0xFB3C, 0xFB3E, 0xFB3E, 301 | 0xFB40, 0xFB41, 0xFB43, 0xFB44, 0xFB46, 0xFBB1, 0xFBD3, 0xFD3D, 0xFD50, 0xFD8F, 302 | 0xFD92, 0xFDC7, 0xFDF0, 0xFDFC, 0xFE70, 0xFE74, 0xFE76, 0xFEFC, 303 | }); 304 | 305 | /** D.2 Characters with bidirectional property "L" */ 306 | static final CharClass D2 = CharClass.fromRanges(new int[]{ 307 | 0x0041, 0x005A, 0x0061, 0x007A, 0x00AA, 0x00AA, 0x00B5, 0x00B5, 0x00BA, 0x00BA, 0x00C0, 0x00D6, 308 | 0x00D8, 0x00F6, 0x00F8, 0x0220, 0x0222, 0x0233, 0x0250, 0x02AD, 0x02B0, 0x02B8, 0x02BB, 0x02C1, 309 | 0x02D0, 0x02D1, 0x02E0, 0x02E4, 0x02EE, 0x02EE, 0x037A, 0x037A, 0x0386, 0x0386, 0x0388, 0x038A, 310 | 0x038C, 0x038C, 0x038E, 0x03A1, 0x03A3, 0x03CE, 0x03D0, 0x03F5, 0x0400, 0x0482, 0x048A, 0x04CE, 311 | 0x04D0, 0x04F5, 0x04F8, 0x04F9, 0x0500, 0x050F, 0x0531, 0x0556, 0x0559, 0x055F, 0x0561, 0x0587, 312 | 0x0589, 0x0589, 0x0903, 0x0903, 0x0905, 0x0939, 0x093D, 0x0940, 0x0949, 0x094C, 0x0950, 0x0950, 313 | 0x0958, 0x0961, 0x0964, 0x0970, 0x0982, 0x0983, 0x0985, 0x098C, 0x098F, 0x0990, 0x0993, 0x09A8, 314 | 0x09AA, 0x09B0, 0x09B2, 0x09B2, 0x09B6, 0x09B9, 0x09BE, 0x09C0, 0x09C7, 0x09C8, 0x09CB, 0x09CC, 315 | 0x09D7, 0x09D7, 0x09DC, 0x09DD, 0x09DF, 0x09E1, 0x09E6, 0x09F1, 0x09F4, 0x09FA, 0x0A05, 0x0A0A, 316 | 0x0A0F, 0x0A10, 0x0A13, 0x0A28, 0x0A2A, 0x0A30, 0x0A32, 0x0A33, 0x0A35, 0x0A36, 0x0A38, 0x0A39, 317 | 0x0A3E, 0x0A40, 0x0A59, 0x0A5C, 0x0A5E, 0x0A5E, 0x0A66, 0x0A6F, 0x0A72, 0x0A74, 0x0A83, 0x0A83, 318 | 0x0A85, 0x0A8B, 0x0A8D, 0x0A8D, 0x0A8F, 0x0A91, 0x0A93, 0x0AA8, 0x0AAA, 0x0AB0, 0x0AB2, 0x0AB3, 319 | 0x0AB5, 0x0AB9, 0x0ABD, 0x0AC0, 0x0AC9, 0x0AC9, 0x0ACB, 0x0ACC, 0x0AD0, 0x0AD0, 0x0AE0, 0x0AE0, 320 | 0x0AE6, 0x0AEF, 0x0B02, 0x0B03, 0x0B05, 0x0B0C, 0x0B0F, 0x0B10, 0x0B13, 0x0B28, 0x0B2A, 0x0B30, 321 | 0x0B32, 0x0B33, 0x0B36, 0x0B39, 0x0B3D, 0x0B3E, 0x0B40, 0x0B40, 0x0B47, 0x0B48, 0x0B4B, 0x0B4C, 322 | 0x0B57, 0x0B57, 0x0B5C, 0x0B5D, 0x0B5F, 0x0B61, 0x0B66, 0x0B70, 0x0B83, 0x0B83, 0x0B85, 0x0B8A, 323 | 0x0B8E, 0x0B90, 0x0B92, 0x0B95, 0x0B99, 0x0B9A, 0x0B9C, 0x0B9C, 0x0B9E, 0x0B9F, 0x0BA3, 0x0BA4, 324 | 0x0BA8, 0x0BAA, 0x0BAE, 0x0BB5, 0x0BB7, 0x0BB9, 0x0BBE, 0x0BBF, 0x0BC1, 0x0BC2, 0x0BC6, 0x0BC8, 325 | 0x0BCA, 0x0BCC, 0x0BD7, 0x0BD7, 0x0BE7, 0x0BF2, 0x0C01, 0x0C03, 0x0C05, 0x0C0C, 0x0C0E, 0x0C10, 326 | 0x0C12, 0x0C28, 0x0C2A, 0x0C33, 0x0C35, 0x0C39, 0x0C41, 0x0C44, 0x0C60, 0x0C61, 0x0C66, 0x0C6F, 327 | 0x0C82, 0x0C83, 0x0C85, 0x0C8C, 0x0C8E, 0x0C90, 0x0C92, 0x0CA8, 0x0CAA, 0x0CB3, 0x0CB5, 0x0CB9, 328 | 0x0CBE, 0x0CBE, 0x0CC0, 0x0CC4, 0x0CC7, 0x0CC8, 0x0CCA, 0x0CCB, 0x0CD5, 0x0CD6, 0x0CDE, 0x0CDE, 329 | 0x0CE0, 0x0CE1, 0x0CE6, 0x0CEF, 0x0D02, 0x0D03, 0x0D05, 0x0D0C, 0x0D0E, 0x0D10, 0x0D12, 0x0D28, 330 | 0x0D2A, 0x0D39, 0x0D3E, 0x0D40, 0x0D46, 0x0D48, 0x0D4A, 0x0D4C, 0x0D57, 0x0D57, 0x0D60, 0x0D61, 331 | 0x0D66, 0x0D6F, 0x0D82, 0x0D83, 0x0D85, 0x0D96, 0x0D9A, 0x0DB1, 0x0DB3, 0x0DBB, 0x0DBD, 0x0DBD, 332 | 0x0DC0, 0x0DC6, 0x0DCF, 0x0DD1, 0x0DD8, 0x0DDF, 0x0DF2, 0x0DF4, 0x0E01, 0x0E30, 0x0E32, 0x0E33, 333 | 0x0E40, 0x0E46, 0x0E4F, 0x0E5B, 0x0E81, 0x0E82, 0x0E84, 0x0E84, 0x0E87, 0x0E88, 0x0E8A, 0x0E8A, 334 | 0x0E8D, 0x0E8D, 0x0E94, 0x0E97, 0x0E99, 0x0E9F, 0x0EA1, 0x0EA3, 0x0EA5, 0x0EA5, 0x0EA7, 0x0EA7, 335 | 0x0EAA, 0x0EAB, 0x0EAD, 0x0EB0, 0x0EB2, 0x0EB3, 0x0EBD, 0x0EBD, 0x0EC0, 0x0EC4, 0x0EC6, 0x0EC6, 336 | 0x0ED0, 0x0ED9, 0x0EDC, 0x0EDD, 0x0F00, 0x0F17, 0x0F1A, 0x0F34, 0x0F36, 0x0F36, 0x0F38, 0x0F38, 337 | 0x0F3E, 0x0F47, 0x0F49, 0x0F6A, 0x0F7F, 0x0F7F, 0x0F85, 0x0F85, 0x0F88, 0x0F8B, 0x0FBE, 0x0FC5, 338 | 0x0FC7, 0x0FCC, 0x0FCF, 0x0FCF, 0x1000, 0x1021, 0x1023, 0x1027, 0x1029, 0x102A, 0x102C, 0x102C, 339 | 0x1031, 0x1031, 0x1038, 0x1038, 0x1040, 0x1057, 0x10A0, 0x10C5, 0x10D0, 0x10F8, 0x10FB, 0x10FB, 340 | 0x1100, 0x1159, 0x115F, 0x11A2, 0x11A8, 0x11F9, 0x1200, 0x1206, 0x1208, 0x1246, 0x1248, 0x1248, 341 | 0x124A, 0x124D, 0x1250, 0x1256, 0x1258, 0x1258, 0x125A, 0x125D, 0x1260, 0x1286, 0x1288, 0x1288, 342 | 0x128A, 0x128D, 0x1290, 0x12AE, 0x12B0, 0x12B0, 0x12B2, 0x12B5, 0x12B8, 0x12BE, 0x12C0, 0x12C0, 343 | 0x12C2, 0x12C5, 0x12C8, 0x12CE, 0x12D0, 0x12D6, 0x12D8, 0x12EE, 0x12F0, 0x130E, 0x1310, 0x1310, 344 | 0x1312, 0x1315, 0x1318, 0x131E, 0x1320, 0x1346, 0x1348, 0x135A, 0x1361, 0x137C, 0x13A0, 0x13F4, 345 | 0x1401, 0x1676, 0x1681, 0x169A, 0x16A0, 0x16F0, 0x1700, 0x170C, 0x170E, 0x1711, 0x1720, 0x1731, 346 | 0x1735, 0x1736, 0x1740, 0x1751, 0x1760, 0x176C, 0x176E, 0x1770, 0x1780, 0x17B6, 0x17BE, 0x17C5, 347 | 0x17C7, 0x17C8, 0x17D4, 0x17DA, 0x17DC, 0x17DC, 0x17E0, 0x17E9, 0x1810, 0x1819, 0x1820, 0x1877, 348 | 0x1880, 0x18A8, 0x1E00, 0x1E9B, 0x1EA0, 0x1EF9, 0x1F00, 0x1F15, 0x1F18, 0x1F1D, 0x1F20, 0x1F45, 349 | 0x1F48, 0x1F4D, 0x1F50, 0x1F57, 0x1F59, 0x1F59, 0x1F5B, 0x1F5B, 0x1F5D, 0x1F5D, 0x1F5F, 0x1F7D, 350 | 0x1F80, 0x1FB4, 0x1FB6, 0x1FBC, 0x1FBE, 0x1FBE, 0x1FC2, 0x1FC4, 0x1FC6, 0x1FCC, 0x1FD0, 0x1FD3, 351 | 0x1FD6, 0x1FDB, 0x1FE0, 0x1FEC, 0x1FF2, 0x1FF4, 0x1FF6, 0x1FFC, 0x200E, 0x200E, 0x2071, 0x2071, 352 | 0x207F, 0x207F, 0x2102, 0x2102, 0x2107, 0x2107, 0x210A, 0x2113, 0x2115, 0x2115, 0x2119, 0x211D, 353 | 0x2124, 0x2124, 0x2126, 0x2126, 0x2128, 0x2128, 0x212A, 0x212D, 0x212F, 0x2131, 0x2133, 0x2139, 354 | 0x213D, 0x213F, 0x2145, 0x2149, 0x2160, 0x2183, 0x2336, 0x237A, 0x2395, 0x2395, 0x249C, 0x24E9, 355 | 0x3005, 0x3007, 0x3021, 0x3029, 0x3031, 0x3035, 0x3038, 0x303C, 0x3041, 0x3096, 0x309D, 0x309F, 356 | 0x30A1, 0x30FA, 0x30FC, 0x30FF, 0x3105, 0x312C, 0x3131, 0x318E, 0x3190, 0x31B7, 0x31F0, 0x321C, 357 | 0x3220, 0x3243, 0x3260, 0x327B, 0x327F, 0x32B0, 0x32C0, 0x32CB, 0x32D0, 0x32FE, 0x3300, 0x3376, 358 | 0x337B, 0x33DD, 0x33E0, 0x33FE, 0x3400, 0x4DB5, 0x4E00, 0x9FA5, 0xA000, 0xA48C, 0xAC00, 0xD7A3, 359 | 0xD800, 0xFA2D, 0xFA30, 0xFA6A, 0xFB00, 0xFB06, 0xFB13, 0xFB17, 0xFF21, 0xFF3A, 0xFF41, 0xFF5A, 360 | 0xFF66, 0xFFBE, 0xFFC2, 0xFFC7, 0xFFCA, 0xFFCF, 0xFFD2, 0xFFD7, 0xFFDA, 0xFFDC, 361 | 0x10300, 0x1031E, 0x10320, 0x10323, 0x10330, 0x1034A, 0x10400, 0x10425, 0x10428, 0x1044D, 362 | 0x1D000, 0x1D0F5, 0x1D100, 0x1D126, 0x1D12A, 0x1D166, 0x1D16A, 0x1D172, 0x1D183, 0x1D184, 363 | 0x1D18C, 0x1D1A9, 0x1D1AE, 0x1D1DD, 0x1D400, 0x1D454, 0x1D456, 0x1D49C, 0x1D49E, 0x1D49F, 364 | 0x1D4A2, 0x1D4A2, 0x1D4A5, 0x1D4A6, 0x1D4A9, 0x1D4AC, 0x1D4AE, 0x1D4B9, 0x1D4BB, 0x1D4BB, 365 | 0x1D4BD, 0x1D4C0, 0x1D4C2, 0x1D4C3, 0x1D4C5, 0x1D505, 0x1D507, 0x1D50A, 0x1D50D, 0x1D514, 366 | 0x1D516, 0x1D51C, 0x1D51E, 0x1D539, 0x1D53B, 0x1D53E, 0x1D540, 0x1D544, 0x1D546, 0x1D546, 367 | 0x1D54A, 0x1D550, 0x1D552, 0x1D6A3, 0x1D6A8, 0x1D7C9, 0x20000, 0x2A6D6, 0x2F800, 0x2FA1D, 368 | 0xF0000, 0xFFFFD, 0x100000, 0x10FFFD, 369 | }); 370 | 371 | /** rfc4013 2.3. Prohibited Output */ 372 | static final CharClass saslProhibited = CharClass.fromClasses(C12, C21, C22, C3, C4, C5, C6, C7, C8, C9); 373 | 374 | /** A prohibited string has been passed to StringPrep. */ 375 | @SuppressWarnings({"WeakerAccess", "JavaDoc"}) 376 | static abstract public class StringPrepError extends Exception { 377 | protected StringPrepError(String message) { 378 | super(message); 379 | } 380 | } 381 | 382 | /** A prohibited character was detected. */ 383 | @SuppressWarnings({"WeakerAccess", "JavaDoc"}) 384 | static public class StringPrepProhibitedCharacter extends StringPrepError { 385 | StringPrepProhibitedCharacter() { 386 | super("String contains a prohibited character"); 387 | } 388 | 389 | 390 | protected StringPrepProhibitedCharacter(String s) { 391 | super(s); 392 | } 393 | } 394 | 395 | /** A prohibited unassigned codepoint was detected. */ 396 | @SuppressWarnings("JavaDoc") 397 | static public class StringPrepUnassignedCodepoint extends StringPrepProhibitedCharacter { 398 | StringPrepUnassignedCodepoint() { 399 | super("String contains an unassigned codepoint"); 400 | } 401 | } 402 | 403 | /** RTL verification has failed, according to rfc3454 section 6. */ 404 | @SuppressWarnings({"unused", "JavaDoc"}) 405 | static public class StringPrepRTLError extends StringPrepError { 406 | StringPrepRTLError() { 407 | super("Invalid RTL string"); 408 | } 409 | } 410 | 411 | static public class StringPrepRTLErrorBothRALandL extends StringPrepRTLError { 412 | } 413 | 414 | static public class StringPrepRTLErrorRALWithoutPrefix extends StringPrepRTLError { 415 | } 416 | 417 | static public class StringPrepRTLErrorRALWithoutSuffix extends StringPrepRTLError { 418 | } 419 | 420 | 421 | /** Replace each character of {@code s} which is in the {@link CharClass} mapFrom 422 | * with the string {@code mapTo}. */ 423 | static String applyMapTo(String s, CharClass mapFrom, String mapTo) { 424 | StringBuilder result = new StringBuilder(); 425 | for (int i = 0; i < s.length(); ) { 426 | int c = Character.codePointAt(s, i); 427 | int charCount = Character.charCount(c); 428 | if (mapFrom.isCharInClass(c)) 429 | result.append(mapTo); 430 | else 431 | result.append(s, i, i + charCount); 432 | i += charCount; 433 | } 434 | 435 | return result.toString(); 436 | } 437 | 438 | 439 | /** Return the first character index in s which is in {@link CharClass}, or -1 if 440 | * no character is in the class.*/ 441 | static int containsCharacterInClass(String s, CharClass charClass) { 442 | for (int i = 0; i < s.length(); ) { 443 | int c = Character.codePointAt(s, i); 444 | if (charClass.isCharInClass(c)) 445 | return i; 446 | 447 | i += Character.charCount(c); 448 | } 449 | return -1; 450 | } 451 | 452 | 453 | /** Perform RTL verification according to rfc3454 section 6. On failure, 454 | * throw a subclass of {@link StringPrepRTLError}. */ 455 | protected static void verifyRTL(String s) throws StringPrepRTLError { 456 | int containsRAL = containsCharacterInClass(s, D1); 457 | if (containsRAL != -1) { 458 | // 2) If a string contains any RandALCat character, the string MUST NOT 459 | // contain any LCat character. 460 | int containsL = containsCharacterInClass(s, D2); 461 | if (containsL != -1) 462 | throw new StringPrepRTLErrorBothRALandL(); 463 | // 3) If a string contains any RandALCat character, a RandALCat 464 | // character MUST be the first character of the string 465 | if (containsRAL != 0) 466 | throw new StringPrepRTLErrorRALWithoutPrefix(); 467 | 468 | // ... and a RandALCat character MUST be the last character of the string. 469 | if (!D1.isCharInClass(s.charAt(s.length() - 1))) 470 | throw new StringPrepRTLErrorRALWithoutSuffix(); 471 | } 472 | } 473 | 474 | 475 | /** Apply SASLPrep and return the result. {@code} is treated as a stored string. */ 476 | static public String prepAsStoredString(String s) throws StringPrepError { 477 | s = prepAsQueryString(s); 478 | 479 | // rfc3454: 7. Unassigned Code Points in Stringprep Profiles 480 | // Stored strings using the profile MUST NOT contain any unassigned code points. 481 | // rfc4013: 2.5. Unassigned Code Points 482 | // This profile specifies the [StringPrep, A.1] table as its list of unassigned 483 | // code points. 484 | int containsUnassignedCodepoint = containsCharacterInClass(s, A1); 485 | if (containsUnassignedCodepoint != -1) 486 | throw new StringPrepUnassignedCodepoint(); 487 | return s; 488 | } 489 | 490 | 491 | /** Apply SASLPrep and return the result. {@code} is treated as a query string. */ 492 | static public String prepAsQueryString(String s) throws StringPrepError { 493 | // 1) Map 494 | // rfc4013: 2.1. Mapping 495 | // Note that applying the mapping this way works here because we only 496 | // map to nothing or space. A StringPrep mapping that maps strings to 497 | // another string (eg. case folding) can't be applied sequentially like 498 | // this. 499 | s = applyMapTo(s, B1, ""); 500 | s = applyMapTo(s, C12, " "); 501 | 502 | // 2) Normalize 503 | // rfc4013: 2.2. Normalization 504 | s = Normalizer.normalize(s); 505 | 506 | // 3) Prohibit 507 | int idx = containsCharacterInClass(s, saslProhibited); 508 | if (idx != -1) 509 | throw new StringPrepProhibitedCharacter(); 510 | 511 | // 4) Check bidi 512 | verifyRTL(s); 513 | 514 | return s; 515 | } 516 | 517 | 518 | public static boolean isContainingProhibitedCharacters(String s) { 519 | int idx = containsCharacterInClass(s, saslProhibited); 520 | return idx != -1; 521 | } 522 | } 523 | --------------------------------------------------------------------------------