├── .gitignore ├── LICENSE ├── README.md ├── build.gradle ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── src ├── main │ └── java │ │ └── com │ │ └── tls │ │ ├── base64_url │ │ └── base64_url.java │ │ └── tls_sigature │ │ └── tls_sigature.java └── test │ └── java │ ├── TestBase64.java │ └── TlsSigTest.java └── user_build.gradle /.gitignore: -------------------------------------------------------------------------------- 1 | .gradle 2 | /build/ 3 | 4 | # Ignore Gradle GUI config 5 | gradle-app.setting 6 | 7 | # Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored) 8 | !gradle-wrapper.jar 9 | 10 | # Cache of project 11 | .gradletasknamecache 12 | 13 | # # Work around https://youtrack.jetbrains.com/issue/IDEA-116898 14 | # gradle/wrapper/gradle-wrapper.properties 15 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2018 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## 使用构建工具集成 2 | 3 | ### maven 4 | ```xml 5 | 6 | 7 | com.github.tencentyun 8 | tls-sig-api 9 | 1.2 10 | 11 | 12 | ``` 13 | 14 | ### gradle 15 | ```java 16 | dependencies { 17 | compile 'com.github.tencentyun:tls-sig-api:1.2' 18 | } 19 | ``` 20 | 21 | ### 源码构建 22 | ``` shell 23 | ./gradlew -b user_build.gradle build 24 | ``` 25 | 生成的 jar 在 `build/libs` 下面可以找到。依赖需要自行到 [release](https://github.com/tencentyun/tls-sig-api-java/releases) 下载。 26 | 27 | 28 | ## 生成 sig 29 | 30 | ### 默认有效期接口 31 | ```java 32 | import com.tls.tls_sigature.*; 33 | 34 | GenTLSSignatureResult result = tls_sigature.genSig(140000000, "xiaojun", priKeyContent); 35 | System.out.println(result.urlSig); 36 | ``` 37 | 38 | ### 指定有效期接口 39 | ```java 40 | import com.tls.tls_sigature.*; 41 | 42 | GenTLSSignatureResult result = tls_sigature.GenTLSSignatureEx(140000000, "xiaojun", priKeyContent, 24*3600*180); 43 | System.out.println(result.urlSig); 44 | ``` 45 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'java' 2 | apply plugin: 'maven' 3 | apply plugin: 'signing' 4 | repositories { 5 | mavenCentral() 6 | } 7 | dependencies { 8 | // https://mvnrepository.com/artifact/org.bouncycastle/bcpkix-jdk15on 9 | compile group: 'org.bouncycastle', name: 'bcpkix-jdk18on', version: '1.78.1' 10 | // https://mvnrepository.com/artifact/org.bouncycastle/bcprov-jdk15on 11 | compile group: 'org.bouncycastle', name: 'bcprov-jdk18on', version: '1.78.1' 12 | // https://mvnrepository.com/artifact/org.json/json 13 | compile group: 'org.json', name: 'json', version: '20240303' 14 | // https://mvnrepository.com/artifact/junit/junit 15 | testCompile group: 'junit', name: 'junit', version: '4.13.1' 16 | } 17 | sourceCompatibility = 1.8 18 | version = '1.2' 19 | group = "com.github.tencentyun" 20 | archivesBaseName = "tls-sig-api" 21 | tasks.withType(JavaCompile) { 22 | options.encoding = 'UTF-8' 23 | } 24 | tasks.withType(Javadoc) { 25 | options.encoding = 'UTF-8' 26 | } 27 | 28 | task javadocJar(type: Jar) { 29 | classifier = 'javadoc' 30 | from javadoc 31 | } 32 | 33 | task sourcesJar(type: Jar) { 34 | classifier = 'sources' 35 | from sourceSets.main.allSource 36 | } 37 | 38 | artifacts { 39 | archives javadocJar, sourcesJar 40 | } 41 | 42 | signing { 43 | sign configurations.archives 44 | } 45 | 46 | uploadArchives { 47 | repositories { 48 | mavenDeployer { 49 | beforeDeployment { MavenDeployment deployment -> signing.signPom(deployment) } 50 | 51 | repository(url: "https://oss.sonatype.org/service/local/staging/deploy/maven2/") { 52 | authentication(userName: ossrhUsername, password: ossrhPassword) 53 | } 54 | 55 | snapshotRepository(url: "https://oss.sonatype.org/content/repositories/snapshots/") { 56 | authentication(userName: ossrhUsername, password: ossrhPassword) 57 | } 58 | 59 | pom.project { 60 | name 'tls-sig-api' 61 | packaging 'jar' 62 | // optionally artifactId can be defined here 63 | description 'tls sig api for java' 64 | url 'https://github.com/tencentyun/tls-sig-api-java' 65 | 66 | scm { 67 | connection 'scm:git:git://github.com/tencentyun/tls-sig-api-java.git' 68 | developerConnection 'scm:git:ssh://git@github.com:tencentyun/tls-sig-api-java.git' 69 | url 'https://github.com/tencentyun/tls-sig-api-java' 70 | } 71 | 72 | licenses { 73 | license { 74 | name 'MIT License' 75 | url 'http://www.opensource.org/licenses/mit-license.php' 76 | } 77 | } 78 | 79 | developers { 80 | developer { 81 | id 'weijunyi' 82 | name 'weijunyi' 83 | email 'weijunyi@tencent.com' 84 | } 85 | } 86 | } 87 | } 88 | } 89 | } 90 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tencentyun/tls-sig-api-java/ed35883d3258fac8ea0bd4d65458c43c85588fd4/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-5.4.1-all.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | # 4 | # Copyright 2015 the original author or authors. 5 | # 6 | # 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 | ## 21 | ## Gradle start up script for UN*X 22 | ## 23 | ############################################################################## 24 | 25 | # Attempt to set APP_HOME 26 | # Resolve links: $0 may be a link 27 | PRG="$0" 28 | # Need this for relative symlinks. 29 | while [ -h "$PRG" ] ; do 30 | ls=`ls -ld "$PRG"` 31 | link=`expr "$ls" : '.*-> \(.*\)$'` 32 | if expr "$link" : '/.*' > /dev/null; then 33 | PRG="$link" 34 | else 35 | PRG=`dirname "$PRG"`"/$link" 36 | fi 37 | done 38 | SAVED="`pwd`" 39 | cd "`dirname \"$PRG\"`/" >/dev/null 40 | APP_HOME="`pwd -P`" 41 | cd "$SAVED" >/dev/null 42 | 43 | APP_NAME="Gradle" 44 | APP_BASE_NAME=`basename "$0"` 45 | 46 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 47 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 48 | 49 | # Use the maximum available, or set MAX_FD != -1 to use that value. 50 | MAX_FD="maximum" 51 | 52 | warn () { 53 | echo "$*" 54 | } 55 | 56 | die () { 57 | echo 58 | echo "$*" 59 | echo 60 | exit 1 61 | } 62 | 63 | # OS specific support (must be 'true' or 'false'). 64 | cygwin=false 65 | msys=false 66 | darwin=false 67 | nonstop=false 68 | case "`uname`" in 69 | CYGWIN* ) 70 | cygwin=true 71 | ;; 72 | Darwin* ) 73 | darwin=true 74 | ;; 75 | MINGW* ) 76 | msys=true 77 | ;; 78 | NONSTOP* ) 79 | nonstop=true 80 | ;; 81 | esac 82 | 83 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 84 | 85 | # Determine the Java command to use to start the JVM. 86 | if [ -n "$JAVA_HOME" ] ; then 87 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 88 | # IBM's JDK on AIX uses strange locations for the executables 89 | JAVACMD="$JAVA_HOME/jre/sh/java" 90 | else 91 | JAVACMD="$JAVA_HOME/bin/java" 92 | fi 93 | if [ ! -x "$JAVACMD" ] ; then 94 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 95 | 96 | Please set the JAVA_HOME variable in your environment to match the 97 | location of your Java installation." 98 | fi 99 | else 100 | JAVACMD="java" 101 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 102 | 103 | Please set the JAVA_HOME variable in your environment to match the 104 | location of your Java installation." 105 | fi 106 | 107 | # Increase the maximum file descriptors if we can. 108 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 109 | MAX_FD_LIMIT=`ulimit -H -n` 110 | if [ $? -eq 0 ] ; then 111 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 112 | MAX_FD="$MAX_FD_LIMIT" 113 | fi 114 | ulimit -n $MAX_FD 115 | if [ $? -ne 0 ] ; then 116 | warn "Could not set maximum file descriptor limit: $MAX_FD" 117 | fi 118 | else 119 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 120 | fi 121 | fi 122 | 123 | # For Darwin, add options to specify how the application appears in the dock 124 | if $darwin; then 125 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 126 | fi 127 | 128 | # For Cygwin, switch paths to Windows format before running java 129 | if $cygwin ; then 130 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 131 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 132 | JAVACMD=`cygpath --unix "$JAVACMD"` 133 | 134 | # We build the pattern for arguments to be converted via cygpath 135 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 136 | SEP="" 137 | for dir in $ROOTDIRSRAW ; do 138 | ROOTDIRS="$ROOTDIRS$SEP$dir" 139 | SEP="|" 140 | done 141 | OURCYGPATTERN="(^($ROOTDIRS))" 142 | # Add a user-defined pattern to the cygpath arguments 143 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 144 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 145 | fi 146 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 147 | i=0 148 | for arg in "$@" ; do 149 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 150 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 151 | 152 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 153 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 154 | else 155 | eval `echo args$i`="\"$arg\"" 156 | fi 157 | i=$((i+1)) 158 | done 159 | case $i in 160 | (0) set -- ;; 161 | (1) set -- "$args0" ;; 162 | (2) set -- "$args0" "$args1" ;; 163 | (3) set -- "$args0" "$args1" "$args2" ;; 164 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 165 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 166 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 167 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 168 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 169 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 170 | esac 171 | fi 172 | 173 | # Escape application args 174 | save () { 175 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 176 | echo " " 177 | } 178 | APP_ARGS=$(save "$@") 179 | 180 | # Collect all arguments for the java command, following the shell quoting and substitution rules 181 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 182 | 183 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong 184 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then 185 | cd "$(dirname "$0")" 186 | fi 187 | 188 | exec "$JAVACMD" "$@" 189 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem http://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%" == "" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%" == "" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 33 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 34 | 35 | @rem Find java.exe 36 | if defined JAVA_HOME goto findJavaFromJavaHome 37 | 38 | set JAVA_EXE=java.exe 39 | %JAVA_EXE% -version >NUL 2>&1 40 | if "%ERRORLEVEL%" == "0" goto init 41 | 42 | echo. 43 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 44 | echo. 45 | echo Please set the JAVA_HOME variable in your environment to match the 46 | echo location of your Java installation. 47 | 48 | goto fail 49 | 50 | :findJavaFromJavaHome 51 | set JAVA_HOME=%JAVA_HOME:"=% 52 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 53 | 54 | if exist "%JAVA_EXE%" goto init 55 | 56 | echo. 57 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 58 | echo. 59 | echo Please set the JAVA_HOME variable in your environment to match the 60 | echo location of your Java installation. 61 | 62 | goto fail 63 | 64 | :init 65 | @rem Get command-line arguments, handling Windows variants 66 | 67 | if not "%OS%" == "Windows_NT" goto win9xME_args 68 | 69 | :win9xME_args 70 | @rem Slurp the command line arguments. 71 | set CMD_LINE_ARGS= 72 | set _SKIP=2 73 | 74 | :win9xME_args_slurp 75 | if "x%~1" == "x" goto execute 76 | 77 | set CMD_LINE_ARGS=%* 78 | 79 | :execute 80 | @rem Setup the command line 81 | 82 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 83 | 84 | @rem Execute Gradle 85 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 86 | 87 | :end 88 | @rem End local scope for the variables with windows NT shell 89 | if "%ERRORLEVEL%"=="0" goto mainEnd 90 | 91 | :fail 92 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 93 | rem the _cmd.exe /c_ return code! 94 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 95 | exit /b 1 96 | 97 | :mainEnd 98 | if "%OS%"=="Windows_NT" endlocal 99 | 100 | :omega 101 | -------------------------------------------------------------------------------- /src/main/java/com/tls/base64_url/base64_url.java: -------------------------------------------------------------------------------- 1 | package com.tls.base64_url; 2 | 3 | import org.bouncycastle.util.encoders.Base64; 4 | import org.bouncycastle.util.encoders.DecoderException; 5 | 6 | public class base64_url { 7 | //int base64_encode_url(const unsigned char *in_str, int length, char *out_str,int *ret_length) 8 | public static byte[] base64EncodeUrl(byte[] in_str) { 9 | byte[] base64 = Base64.encode(in_str); 10 | for (int i = 0; i < base64.length; ++i) 11 | switch (base64[i]) { 12 | case '+': 13 | base64[i] = '*'; 14 | break; 15 | case '/': 16 | base64[i] = '-'; 17 | break; 18 | case '=': 19 | base64[i] = '_'; 20 | break; 21 | default: 22 | break; 23 | } 24 | return base64; 25 | } 26 | 27 | //int base64_decode_url(const unsigned char *in_str, int length, char *out_str, int *ret_length) 28 | public static byte[] base64DecodeUrl(byte[] in_str) throws DecoderException { 29 | byte[] base64 = in_str.clone(); 30 | for (int i = 0; i < base64.length; ++i) 31 | switch (base64[i]) { 32 | case '*': 33 | base64[i] = '+'; 34 | break; 35 | case '-': 36 | base64[i] = '/'; 37 | break; 38 | case '_': 39 | base64[i] = '='; 40 | break; 41 | default: 42 | break; 43 | } 44 | return Base64.decode(base64); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/main/java/com/tls/tls_sigature/tls_sigature.java: -------------------------------------------------------------------------------- 1 | package com.tls.tls_sigature; 2 | 3 | import java.io.CharArrayReader; 4 | import java.io.IOException; 5 | import java.io.Reader; 6 | import java.security.PrivateKey; 7 | import java.security.PublicKey; 8 | import java.security.Security; 9 | import java.nio.charset.Charset; 10 | 11 | import java.security.Signature; 12 | import java.util.zip.DataFormatException; 13 | import java.util.zip.Deflater; 14 | import java.util.zip.Inflater; 15 | 16 | import org.bouncycastle.util.encoders.Base64; 17 | import org.bouncycastle.asn1.pkcs.PrivateKeyInfo; 18 | import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; 19 | import org.bouncycastle.jce.provider.BouncyCastleProvider; 20 | import org.bouncycastle.openssl.PEMParser; 21 | import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter; 22 | import org.bouncycastle.util.Arrays; 23 | import org.json.JSONObject; 24 | 25 | import com.tls.base64_url.base64_url; 26 | 27 | public class tls_sigature { 28 | public static class GenTLSSignatureResult 29 | { 30 | public String errMessage; 31 | public String urlSig; 32 | public int expireTime; 33 | public int initTime; 34 | public GenTLSSignatureResult() 35 | { 36 | errMessage = ""; 37 | urlSig = ""; 38 | } 39 | } 40 | 41 | public static class CheckTLSSignatureResult 42 | { 43 | public String errMessage; 44 | public boolean verifyResult; 45 | public int expireTime; 46 | public int initTime; 47 | public CheckTLSSignatureResult() 48 | { 49 | errMessage = ""; 50 | verifyResult = false; 51 | } 52 | } 53 | 54 | /** 55 | * 生成 tls 票据 56 | * @param expire 有效期,单位是秒,推荐一个月 57 | * @param appid3rd 填写与 sdkAppid 一致字符串形式的值 58 | * @param sdkappid 应用的 appid 59 | * @param identifier 用户 id 60 | * @param accountType 创建应用后在配置页面上展示的 acctype 61 | * @param priKeyContent 生成 tls 票据使用的私钥内容 62 | * @return 如果出错,GenTLSSignatureResult 中的 urlSig为空,errMsg 为出错信息,成功返回有效的票据 63 | */ 64 | @Deprecated 65 | public static GenTLSSignatureResult GenTLSSignature(long expire, 66 | String appid3rd, long sdkappid, String identifier, 67 | long accountType, String priKeyContent) { 68 | 69 | GenTLSSignatureResult result = new GenTLSSignatureResult(); 70 | 71 | Security.addProvider(new BouncyCastleProvider()); 72 | Reader reader = new CharArrayReader(priKeyContent.toCharArray()); 73 | JcaPEMKeyConverter converter = new JcaPEMKeyConverter(); 74 | PEMParser parser = new PEMParser(reader); 75 | PrivateKey privKeyStruct; 76 | try{ 77 | Object obj = parser.readObject(); 78 | parser.close(); 79 | privKeyStruct = converter.getPrivateKey((PrivateKeyInfo) obj); 80 | } catch (IOException e) { 81 | result.errMessage = "read pem error:" + e.getMessage(); 82 | return result; 83 | } 84 | 85 | //Create Json string and serialization String 86 | String jsonString = "{" 87 | + "\"TLS.account_type\":\"" + accountType +"\"," 88 | + "\"TLS.identifier\":\"" + identifier +"\"," 89 | + "\"TLS.appid_at_3rd\":\"" + appid3rd +"\"," 90 | + "\"TLS.sdk_appid\":\"" + sdkappid +"\"," 91 | + "\"TLS.expire_after\":\"" + expire +"\"" 92 | + "}"; 93 | String time = String.valueOf(System.currentTimeMillis()/1000); 94 | String SerialString = "TLS.appid_at_3rd:" + appid3rd + "\n" 95 | + "TLS.account_type:" + accountType + "\n" 96 | + "TLS.identifier:" + identifier + "\n" 97 | + "TLS.sdk_appid:" + sdkappid + "\n" 98 | + "TLS.time:" + time + "\n" 99 | + "TLS.expire_after:" + expire +"\n"; 100 | try{ 101 | //Create Signature by SerialString 102 | Signature signature = Signature.getInstance("SHA256withECDSA", "BC"); 103 | signature.initSign(privKeyStruct); 104 | signature.update(SerialString.getBytes(Charset.forName("UTF-8"))); 105 | byte[] signatureBytes = signature.sign(); 106 | 107 | String sigTLS = Base64.toBase64String(signatureBytes); 108 | 109 | //Add TlsSig to jsonString 110 | JSONObject jsonObject= new JSONObject(jsonString); 111 | jsonObject.put("TLS.sig", sigTLS); 112 | jsonObject.put("TLS.time", time); 113 | jsonString = jsonObject.toString(); 114 | 115 | //compression 116 | Deflater compresser = new Deflater(); 117 | compresser.setInput(jsonString.getBytes(Charset.forName("UTF-8"))); 118 | 119 | compresser.finish(); 120 | byte [] compressBytes = new byte [512]; 121 | int compressBytesLength = compresser.deflate(compressBytes); 122 | compresser.end(); 123 | 124 | result.urlSig = new String(base64_url.base64EncodeUrl(Arrays.copyOfRange(compressBytes,0,compressBytesLength))); 125 | } catch(Exception e) { 126 | e.printStackTrace(); 127 | result.errMessage = e.getMessage(); 128 | } 129 | 130 | return result; 131 | } 132 | 133 | /** 134 | * 校验 tls 票据 135 | * @param sig 返回 tls 票据 136 | * @param appid3rd 填写与 sdkAppid 一致的字符串形式的值 137 | * @param sdkappid 应的 appid 138 | * @param identifier 用户 id 139 | * @param accountType 创建应用后在配置页面上展示的 acctype 140 | * @param pubKeyContent 用于校验 tls 票据的公钥内容,但是需要先将公钥文件转换为 java 原生 api 使用的格式,下面是推荐的命令 141 | * openssl pkcs8 -topk8 -in ec_key.pem -outform PEM -out p8_priv.pem -nocrypt 142 | * @return 如果出错 CheckTLSSignatureResult 中的 verifyResult 为 false,错误信息在 errMsg,校验成功为 true 143 | */ 144 | @Deprecated 145 | public static CheckTLSSignatureResult CheckTLSSignature(String sig, String appid3rd, long sdkappid, 146 | String identifier, long accountType, 147 | String pubKeyContent) { 148 | CheckTLSSignatureResult result = new CheckTLSSignatureResult(); 149 | Security.addProvider(new BouncyCastleProvider()); 150 | 151 | byte [] compressBytes = base64_url.base64DecodeUrl(sig.getBytes(Charset.forName("UTF-8"))); 152 | 153 | //Decompression 154 | Inflater decompression = new Inflater(); 155 | decompression.setInput(compressBytes, 0, compressBytes.length); 156 | byte [] decompressBytes = new byte [1024]; 157 | int decompressLength; 158 | try { 159 | decompressLength = decompression.inflate(decompressBytes); 160 | } catch (DataFormatException e){ 161 | result.errMessage = "uncompress data error:" + e.getMessage(); 162 | return result; 163 | } 164 | decompression.end(); 165 | 166 | String jsonString = new String(Arrays.copyOfRange(decompressBytes, 0, decompressLength)); 167 | 168 | //Get TLS.Sig from json 169 | JSONObject jsonObject= new JSONObject(jsonString); 170 | String sigTLS = jsonObject.getString("TLS.sig"); 171 | 172 | //debase64 TLS.Sig to get serailString 173 | byte[] signatureBytes = Base64.decode(sigTLS.getBytes(Charset.forName("UTF-8"))); 174 | 175 | try{ 176 | 177 | String sigTime = jsonObject.getString("TLS.time"); 178 | String sigExpire = jsonObject.getString("TLS.expire_after"); 179 | 180 | //checkTime 181 | if( System.currentTimeMillis()/1000 - Long.parseLong(sigTime) > Long.parseLong(sigExpire)) 182 | { 183 | result.errMessage = new String("TLS sig is out of date "); 184 | System.out.println("Timeout"); 185 | return result; 186 | } 187 | 188 | //Get Serial String from json 189 | String SerialString = "TLS.appid_at_3rd:" + appid3rd + "\n" 190 | + "TLS.account_type:" + accountType + "\n" 191 | + "TLS.identifier:" + identifier + "\n" 192 | + "TLS.sdk_appid:" + sdkappid + "\n" 193 | + "TLS.time:" + sigTime + "\n" 194 | + "TLS.expire_after:" + sigExpire + "\n"; 195 | 196 | Reader reader = new CharArrayReader(pubKeyContent.toCharArray()); 197 | PEMParser parser = new PEMParser(reader); 198 | JcaPEMKeyConverter converter = new JcaPEMKeyConverter(); 199 | Object obj = parser.readObject(); 200 | parser.close(); 201 | PublicKey pubKeyStruct = converter.getPublicKey((SubjectPublicKeyInfo) obj); 202 | 203 | Signature signature = Signature.getInstance("SHA256withECDSA","BC"); 204 | signature.initVerify(pubKeyStruct); 205 | signature.update(SerialString.getBytes(Charset.forName("UTF-8"))); 206 | result.verifyResult = signature.verify(signatureBytes); 207 | } catch(Exception e) { 208 | e.printStackTrace(); 209 | result.errMessage = "Failed in checking sig"; 210 | } 211 | 212 | return result; 213 | } 214 | 215 | /** 216 | * 生成 tls 票据,精简参数列表,有效期默认为 180 天 217 | * @param skdAppid 应用的 sdkappid 218 | * @param identifier 用户 id 219 | * @param priKeyContent 私钥文件内容 220 | * @return GenTLSSignatureResult 221 | */ 222 | public static GenTLSSignatureResult GenTLSSignatureEx( 223 | long skdAppid, 224 | String identifier, 225 | String priKeyContent) { 226 | return GenTLSSignatureEx(skdAppid, identifier, priKeyContent, 3600*24*180); 227 | } 228 | 229 | /** 230 | * 生成 tls 票据,精简参数列表 231 | * @param skdAppid 应用的 sdkappid 232 | * @param identifier 用户 id 233 | * @param priKeyContent 私钥文件内容 234 | * @param expire 有效期,以秒为单位,推荐时长一个月 235 | * @return GenTLSSignatureResult 236 | */ 237 | public static GenTLSSignatureResult GenTLSSignatureEx( 238 | long skdAppid, 239 | String identifier, 240 | String priKeyContent, 241 | long expire) { 242 | return GenTLSSignature(expire, "0", skdAppid, identifier, 0, priKeyContent); 243 | } 244 | 245 | public static CheckTLSSignatureResult CheckTLSSignatureEx( 246 | String sig, 247 | long sdkappid, 248 | String identifier, 249 | String publicKey) throws DataFormatException { 250 | 251 | CheckTLSSignatureResult result = new CheckTLSSignatureResult(); 252 | Security.addProvider(new BouncyCastleProvider()); 253 | 254 | byte [] compressBytes = base64_url.base64DecodeUrl(sig.getBytes(Charset.forName("UTF-8"))); 255 | 256 | //Decompression 257 | Inflater decompression = new Inflater(); 258 | decompression.setInput(compressBytes, 0, compressBytes.length); 259 | byte[] decompressBytes = new byte[1024]; 260 | int decompressLength = decompression.inflate(decompressBytes); 261 | decompression.end(); 262 | 263 | String jsonString = new String(Arrays.copyOfRange(decompressBytes, 0, decompressLength)); 264 | 265 | //Get TLS.Sig from json 266 | JSONObject jsonObject= new JSONObject(jsonString); 267 | String sigTLS = jsonObject.getString("TLS.sig"); 268 | 269 | //debase64 TLS.Sig to get serailString 270 | byte[] signatureBytes = Base64.decode(sigTLS.getBytes(Charset.forName("UTF-8"))); 271 | 272 | try { 273 | String strSdkappid = jsonObject.getString("TLS.sdk_appid"); 274 | String sigTime = jsonObject.getString("TLS.time"); 275 | String sigExpire = jsonObject.getString("TLS.expire_after"); 276 | 277 | if (Integer.parseInt(strSdkappid) != sdkappid) 278 | { 279 | result.errMessage = new String( "sdkappid " 280 | + strSdkappid 281 | + " in tls sig not equal sdkappid " 282 | + sdkappid 283 | + " in request"); 284 | return result; 285 | } 286 | 287 | if ( System.currentTimeMillis()/1000 - Long.parseLong(sigTime) > Long.parseLong(sigExpire)) { 288 | result.errMessage = new String("TLS sig is out of date"); 289 | return result; 290 | } 291 | 292 | //Get Serial String from json 293 | String SerialString = "TLS.appid_at_3rd:" + 0 + "\n" 294 | + "TLS.account_type:" + 0 + "\n" 295 | + "TLS.identifier:" + identifier + "\n" 296 | + "TLS.sdk_appid:" + sdkappid + "\n" 297 | + "TLS.time:" + sigTime + "\n" 298 | + "TLS.expire_after:" + sigExpire + "\n"; 299 | 300 | Reader reader = new CharArrayReader(publicKey.toCharArray()); 301 | PEMParser parser = new PEMParser(reader); 302 | JcaPEMKeyConverter converter = new JcaPEMKeyConverter(); 303 | Object obj = parser.readObject(); 304 | parser.close(); 305 | PublicKey pubKeyStruct = converter.getPublicKey((SubjectPublicKeyInfo) obj); 306 | 307 | Signature signature = Signature.getInstance("SHA256withECDSA","BC"); 308 | signature.initVerify(pubKeyStruct); 309 | signature.update(SerialString.getBytes(Charset.forName("UTF-8"))); 310 | boolean bool = signature.verify(signatureBytes); 311 | result.expireTime = Integer.parseInt(sigExpire); 312 | result.initTime = Integer.parseInt(sigTime); 313 | result.verifyResult = bool; 314 | } 315 | catch(Exception e) 316 | { 317 | e.printStackTrace(); 318 | result.errMessage = "Failed in checking sig"; 319 | } 320 | 321 | return result; 322 | } 323 | 324 | public static GenTLSSignatureResult genSig( 325 | long sdkappid, 326 | String identifier, 327 | String priKey) { 328 | // 默认 180 天 329 | return GenTLSSignature(24*3600*180, "0", sdkappid, identifier, 0, priKey); 330 | } 331 | 332 | public static GenTLSSignatureResult genSig( 333 | long sdkappid, 334 | String identifier, 335 | int expire, 336 | String priKey) { 337 | return GenTLSSignature(expire, "0", sdkappid, identifier, 0, priKey); 338 | } 339 | } 340 | -------------------------------------------------------------------------------- /src/test/java/TestBase64.java: -------------------------------------------------------------------------------- 1 | import org.junit.Assert; 2 | import org.junit.Test; 3 | import com.tls.base64_url.*; 4 | import org.bouncycastle.util.encoders.DecoderException; 5 | 6 | public class TestBase64 { 7 | @Test 8 | public void base64() { 9 | byte[] res = base64_url.base64EncodeUrl("123".getBytes()); 10 | Assert.assertArrayEquals("MTIz".getBytes(), res); 11 | 12 | res = base64_url.base64DecodeUrl(res); 13 | Assert.assertArrayEquals("123".getBytes(), res); 14 | 15 | res = base64_url.base64EncodeUrl("1".getBytes()); 16 | Assert.assertArrayEquals("MQ__".getBytes(), res); 17 | 18 | res = base64_url.base64DecodeUrl(res); 19 | Assert.assertArrayEquals("1".getBytes(), res); 20 | } 21 | 22 | @Test 23 | public void failed() { 24 | try { 25 | base64_url.base64DecodeUrl("123".getBytes()); 26 | Assert.fail(); 27 | } catch (Exception e) { 28 | Assert.assertEquals(DecoderException.class, e.getClass()); 29 | } 30 | } 31 | 32 | @Test 33 | public void testLong() { 34 | byte[] res = base64_url.base64EncodeUrl("111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111".getBytes()); 35 | Assert.assertArrayEquals("MTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTEx".getBytes(), res); 36 | 37 | res = base64_url.base64DecodeUrl(res); 38 | Assert.assertArrayEquals("111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111".getBytes(), res); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/test/java/TlsSigTest.java: -------------------------------------------------------------------------------- 1 | import org.junit.Assert; 2 | import org.junit.Test; 3 | import com.tls.tls_sigature.*; 4 | 5 | public class TlsSigTest { 6 | @Test 7 | public void genAndVerify() { 8 | try { 9 | //Use pemfile keys to test 10 | String privStr = "-----BEGIN PRIVATE KEY-----\n" + 11 | "MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgkTfHxPa8YusG+va8\n" + 12 | "1CRztNQBOEr90TBEjlQBZ5d1Y0ChRANCAAS9isP/xLib7EZ1vS5OUy+gOsYBwees\n" + 13 | "PMDvWiTygPAUsGZv1PHLoa0ciqsElkO1fMGwNrzOKJx1Oo194Ri+SypV\n" + 14 | "-----END PRIVATE KEY-----"; 15 | 16 | //change public pem string to public string 17 | String pubStr = "-----BEGIN PUBLIC KEY-----\n" + 18 | "MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEvYrD/8S4m+xGdb0uTlMvoDrGAcHn\n" + 19 | "rDzA71ok8oDwFLBmb9Txy6GtHIqrBJZDtXzBsDa8ziicdTqNfeEYvksqVQ==\n" + 20 | "-----END PUBLIC KEY-----"; 21 | 22 | // generate signature 23 | tls_sigature.GenTLSSignatureResult result = tls_sigature.GenTLSSignatureEx(1400000000, "xiaojun", privStr); 24 | Assert.assertNotEquals(null, result); 25 | Assert.assertNotEquals(null, result.urlSig); 26 | Assert.assertNotEquals(0, result.urlSig.length()); 27 | 28 | // check signature 29 | tls_sigature.CheckTLSSignatureResult checkResult = tls_sigature.CheckTLSSignatureEx(result.urlSig, 1400000000, "xiaojun", pubStr); 30 | Assert.assertNotEquals(null, checkResult); 31 | Assert.assertTrue(checkResult.verifyResult); 32 | 33 | checkResult = tls_sigature.CheckTLSSignatureEx(result.urlSig, 1400000000, "xiaojun2", pubStr); 34 | Assert.assertNotEquals(null, checkResult); 35 | Assert.assertFalse( checkResult.verifyResult); 36 | 37 | 38 | // new interface generate signature 39 | result = tls_sigature.genSig(1400000000, "xiaojun", privStr); 40 | Assert.assertNotEquals(null, result); 41 | Assert.assertNotEquals(null, result.urlSig); 42 | Assert.assertNotEquals(0, result.urlSig.length()); 43 | 44 | // check signature 45 | checkResult = tls_sigature.CheckTLSSignatureEx(result.urlSig, 1400000000, "xiaojun", pubStr); 46 | Assert.assertNotEquals(null, checkResult); 47 | Assert.assertTrue(checkResult.verifyResult); 48 | 49 | checkResult = tls_sigature.CheckTLSSignatureEx(result.urlSig, 1400000000, "xiaojun2", pubStr); 50 | Assert.assertNotEquals(null, checkResult); 51 | Assert.assertFalse( checkResult.verifyResult); 52 | } catch (Exception e) { 53 | e.printStackTrace(); 54 | } 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /user_build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'java' 2 | apply plugin: 'maven' 3 | 4 | repositories { 5 | mavenCentral() 6 | } 7 | 8 | dependencies { 9 | // https://mvnrepository.com/artifact/org.bouncycastle/bcpkix-jdk15on 10 | compile group: 'org.bouncycastle', name: 'bcpkix-jdk15on', version: '1.59' 11 | // https://mvnrepository.com/artifact/org.bouncycastle/bcprov-jdk15on 12 | compile group: 'org.bouncycastle', name: 'bcprov-jdk15on', version: '1.59' 13 | // https://mvnrepository.com/artifact/org.json/json 14 | compile group: 'org.json', name: 'json', version: '20180130' 15 | // https://mvnrepository.com/artifact/junit/junit 16 | testCompile group: 'junit', name: 'junit', version: '4.12' 17 | } 18 | 19 | sourceCompatibility = 1.6 20 | group = "com.github.tencentyun" 21 | archivesBaseName = "tls-sig-api" 22 | tasks.withType(JavaCompile) { 23 | options.encoding = 'UTF-8' 24 | } 25 | tasks.withType(Javadoc) { 26 | options.encoding = 'UTF-8' 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 | --------------------------------------------------------------------------------