添加Java和Kotlin实现的API签名工具,包括核心库、命令行工具和使用文档,支持多种签名算法和环境变量配置。

This commit is contained in:
SF-bytebytebrew
2025-05-21 18:44:37 +08:00
parent f6186868b7
commit d1fdcfa7e7
21 changed files with 2130 additions and 0 deletions

12
kotlin/.gitattributes vendored Normal file
View File

@@ -0,0 +1,12 @@
#
# https://help.github.com/articles/dealing-with-line-endings/
#
# Linux start script should use lf
/gradlew text eol=lf
# These are Windows script files and should use crlf
*.bat text eol=crlf
# Binary files should be left untouched
*.jar binary

5
kotlin/.gitignore vendored Normal file
View File

@@ -0,0 +1,5 @@
# Ignore Gradle project-specific cache directory
.gradle
# Ignore Gradle build output directory
build

177
kotlin/README.md Normal file
View File

@@ -0,0 +1,177 @@
# API签名工具 - Kotlin实现
## 项目结构
根据实际项目文件结构:
```plaintext
kotlin/
├── build.gradle.kts # Gradle构建文件
├── gradle/ # Gradle包装器目录
├── gradlew # Gradle包装器脚本(Unix)
├── gradlew.bat # Gradle包装器脚本(Windows)
├── gradle.properties # Gradle属性配置
├── settings.gradle.kts # Gradle设置
├── src/
│ └── main/
│ └── kotlin/
│ └── com/
│ └── soundforce/
│ └── apisign/
│ ├── ApiSigner.kt # 签名工具实现
│ ├── Main.kt # 命令行接口
│ ├── SignOptions.kt # 签名配置
│ └── SignatureAlgorithm.kt # 签名算法
├── build/ # 构建输出目录
└── .gradle/ # Gradle缓存目录
```
## 使用方法
### 构建项目
```bash
# 初始化Gradle包装器如果尚未初始化
gradle wrapper
# 构建项目
./gradlew build
# 构建可执行JAR文件
./gradlew shadowJar
```
这将在`build/libs/`目录下生成一个包含所有依赖的可执行JAR文件。
### 运行命令行工具
```bash
# 直接运行(不需要先构建)
./gradlew run --args="[选项]"
# 或使用构建后的JAR文件
java -jar build/libs/apisign-1.0.0.jar [选项]
```
### 命令行选项
| 选项 | 描述 |
|------|------|
| `-a, --algorithm` | 签名算法: MD5, SHA1, SHA256, HMAC-SHA256 |
| `-u, --url` | API基础URL |
| `-p, --param` | 请求参数格式为key=value可多次使用 |
| `-k, --key` | 访问密钥ID |
| `-s, --secret` | 密钥 |
| `-c, --channel` | 合作渠道方ID |
| `-h, --help` | 显示帮助信息 |
### 常用命令示例
**基本用法**
```bash
java -jar build/libs/apisign-1.0.0.jar
```
**自定义参数**
```bash
java -jar build/libs/apisign-1.0.0.jar \
-u "https://api.example.com/user/info" \
-p "userId=12345" -p "action=getInfo" \
-k "YOUR_ACCESS_KEY" \
-s "YOUR_SECRET_KEY" \
-c "3"
```
**指定签名算法**
```bash
java -jar build/libs/apisign-1.0.0.jar -a SHA256
```
**帮助信息**
```bash
java -jar build/libs/apisign-1.0.0.jar --help
```
### API接口测试实例
使用真实API接口进行测试
```bash
# 未签名的API调用测试 - 返回错误
curl "https://api-v1.sound-force.com:8443/p/album/single/media-url?channelId=3&singleId=381980"
# 返回: {"code":400,"data":null,"msg":"Missing AccessKeyId","success":false}
# 生成访问https://api-v1.sound-force.com:8443/p/album/single/media-url的签名URL
java -jar build/libs/apisign-1.0.0.jar \
-a MD5 \
-u "https://api-v1.sound-force.com:8443/p/album/single/media-url" \
-p "singleId=381980" \
-k "YOUR_ACCESS_KEY" \
-s "YOUR_SECRET_KEY" \
-c "3"
# 使用curl测试API接口
signed_url=$(java -jar build/libs/apisign-1.0.0.jar \
-a MD5 \
-u "https://api-v1.sound-force.com:8443/p/album/single/media-url" \
-p "singleId=381980" \
-k "YOUR_ACCESS_KEY" \
-s "YOUR_SECRET_KEY" \
-c "3" | grep -A 1 "签名后的URL:" | tail -n 1)
curl -v "$signed_url"
```
请注意:
- 替换`YOUR_ACCESS_KEY`为实际的访问密钥ID
- 替换`YOUR_SECRET_KEY`为实际的密钥
- 示例使用的渠道ID为`3`,请根据实际情况调整
使用有效的密钥和签名后API接口将返回成功响应(状态码200)并提供媒体URL数据。
### 代码集成
```kotlin
import com.soundforce.apisign.ApiSigner
import com.soundforce.apisign.SignOptions
import com.soundforce.apisign.SignatureAlgorithm
// 创建签名工具
val signer = ApiSigner()
// 参数
val params = mapOf(
"singleId" to "381980"
)
// 执行签名
val signedParams = signer.signRequest(
params,
"YOUR_ACCESS_KEY",
"YOUR_SECRET_KEY",
"3"
)
// 或签名URL
val signedUrl = signer.signUrl(
"https://api-v1.sound-force.com:8443/p/album/single/media-url",
params,
"YOUR_ACCESS_KEY",
"YOUR_SECRET_KEY",
"3"
)
```
### 环境变量
该工具支持从`.env`文件加载以下配置:
- `ACCESS_KEY_ID`: 访问密钥ID
- `SECRET_KEY`: 密钥
- `CHANNEL_ID`: 渠道ID
- `SIGN_ALGORITHM`: 签名算法
- `API_BASE_URL`: API基础URL

54
kotlin/build.gradle.kts Normal file
View File

@@ -0,0 +1,54 @@
plugins {
kotlin("jvm") version "2.1.21"
application
id("com.github.johnrengelman.shadow") version "8.1.1"
}
group = "com.soundforce.apisign"
version = "1.0.0"
repositories {
mavenCentral()
}
dependencies {
implementation(kotlin("stdlib"))
implementation("org.jetbrains.kotlinx:kotlinx-cli:0.3.6")
implementation("io.github.cdimascio:dotenv-kotlin:6.5.1")
testImplementation(kotlin("test"))
}
application {
mainClass.set("com.soundforce.apisign.MainKt")
}
tasks.test {
useJUnitPlatform()
}
java {
toolchain {
languageVersion.set(JavaLanguageVersion.of(21))
}
}
tasks.withType<org.jetbrains.kotlin.gradle.tasks.KotlinCompile> {
kotlinOptions {
jvmTarget = "21"
}
}
tasks.jar {
manifest {
attributes["Main-Class"] = "com.soundforce.apisign.MainKt"
}
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
from(configurations.runtimeClasspath.get().map { if (it.isDirectory) it else zipTree(it) })
}
tasks.shadowJar {
archiveBaseName.set("apisign")
archiveClassifier.set("")
archiveVersion.set("1.0.0")
mergeServiceFiles()
}

7
kotlin/gradle.properties Normal file
View File

@@ -0,0 +1,7 @@
# This file was generated by the Gradle 'init' task.
# https://docs.gradle.org/current/userguide/build_environment.html#sec:gradle_configuration_properties
org.gradle.configuration-cache=true
org.gradle.parallel=true
org.gradle.caching=true

View File

@@ -0,0 +1,11 @@
# This file was generated by the Gradle 'init' task.
# https://docs.gradle.org/current/userguide/platforms.html#sub::toml-dependencies-format
[versions]
guava = "33.4.5-jre"
[libraries]
guava = { module = "com.google.guava:guava", version.ref = "guava" }
[plugins]
kotlin-jvm = { id = "org.jetbrains.kotlin.jvm", version = "2.1.20" }

BIN
kotlin/gradle/wrapper/gradle-wrapper.jar vendored Normal file

Binary file not shown.

View File

@@ -0,0 +1,7 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.14-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

251
kotlin/gradlew vendored Executable file
View File

@@ -0,0 +1,251 @@
#!/bin/sh
#
# Copyright © 2015-2021 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# SPDX-License-Identifier: Apache-2.0
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH="\\\"\\\""
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
if ! command -v java >/dev/null 2>&1
then
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command:
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
-jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"

94
kotlin/gradlew.bat vendored Normal file
View File

@@ -0,0 +1,94 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@rem SPDX-License-Identifier: Apache-2.0
@rem
@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:execute
@rem Setup the command line
set CLASSPATH=
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %*
:end
@rem End local scope for the variables with windows NT shell
if %ERRORLEVEL% equ 0 goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
set EXIT_CODE=%ERRORLEVEL%
if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

View File

@@ -0,0 +1,15 @@
/*
* This file was generated by the Gradle 'init' task.
*
* The settings file is used to specify which projects to include in your build.
* For more detailed information on multi-project builds, please refer to https://docs.gradle.org/8.14/userguide/multi_project_builds.html in the Gradle documentation.
* This project uses @Incubating APIs which are subject to change.
*/
plugins {
// Apply the foojay-resolver plugin to allow automatic download of JDKs
id("org.gradle.toolchains.foojay-resolver-convention") version "0.10.0"
}
rootProject.name = "kotlin"
include("app")

View File

@@ -0,0 +1,226 @@
package com.soundforce.apisign
import java.net.URLEncoder
import java.security.MessageDigest
import java.time.Instant
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec
import kotlin.math.abs
import kotlin.random.Random
/**
* API签名工具
*/
class ApiSigner(private val options: SignOptions = SignOptions()) {
/**
* 生成随机字符串
* @return 一个基于当前时间的随机字符串
*/
fun generateNonce(): String {
val timestamp = getTimestamp()
val random = Random.nextInt(0, 1000000)
return "$timestamp$random"
}
/**
* 获取当前时间戳(毫秒)
* @return 当前的Unix时间戳毫秒
*/
fun getTimestamp(): Long {
return Instant.now().toEpochMilli()
}
/**
* 对请求进行签名
* @param params 请求参数
* @param accessKeyId 访问密钥ID
* @param secretKey 密钥
* @param channelId 合作渠道方ID
* @return 添加了签名的完整参数
*/
fun signRequest(
params: Map<String, String>, accessKeyId: String, secretKey: String, channelId: String
): Map<String, String> {
val signedParams = params.toMutableMap()
val timestamp = getTimestamp()
signedParams[options.keyName] = accessKeyId
signedParams[options.channelIdName] = channelId
signedParams[options.timestampName] = timestamp.toString()
signedParams[options.nonceName] = generateNonce()
val signature = calculateSignature(signedParams, secretKey)
signedParams[options.signatureName] = signature
return signedParams
}
/**
* 对URL进行签名
* @param baseUrl 基础URL地址
* @param params 请求参数
* @param accessKeyId 访问密钥ID
* @param secretKey 密钥
* @param channelId 合作渠道方ID
* @return 添加了签名的完整URL
*/
fun signUrl(
baseUrl: String, params: Map<String, String>, accessKeyId: String, secretKey: String, channelId: String
): String {
val signedParams = signRequest(params, accessKeyId, secretKey, channelId)
val queryString = buildQueryString(signedParams)
return if (baseUrl.contains("?")) {
"$baseUrl&$queryString"
} else {
"$baseUrl?$queryString"
}
}
/**
* 构建URL查询字符串
* @param params 参数
* @return 查询字符串
*/
private fun buildQueryString(params: Map<String, String>): String {
return params.entries.sortedBy { it.key }.joinToString("&") { (key, value) ->
"${encodeURIComponent(key)}=${encodeURIComponent(value)}"
}
}
/**
* URL编码
*/
private fun encodeURIComponent(s: String): String {
return URLEncoder.encode(s, "UTF-8").replace("+", "%20").replace("%21", "!").replace("%27", "'")
.replace("%28", "(").replace("%29", ")").replace("%7E", "~")
}
/**
* 计算签名
* @param params 请求参数
* @param secretKey 密钥
* @return 签名字符串
*/
fun calculateSignature(params: Map<String, String>, secretKey: String): String {
val signingString = createSigningString(params)
val finalString = "$signingString&key=$secretKey"
return when (options.algorithm) {
SignatureAlgorithm.MD5 -> md5(finalString)
SignatureAlgorithm.SHA1 -> sha1(finalString)
SignatureAlgorithm.SHA256 -> sha256(finalString)
SignatureAlgorithm.HMAC_SHA256 -> hmacSha256(finalString, secretKey)
}
}
/**
* 创建用于签名的规范化字符串
* @param params 请求参数
* @return 按键名排序并拼接的字符串
*/
fun createSigningString(params: Map<String, String>): String {
return params.entries.filter { it.key != options.signatureName }.sortedBy { it.key }
.joinToString("&") { (key, value) ->
val encodedValue = if (needsUrlEncode(value)) encodeURIComponent(value) else value
"$key=$encodedValue"
}
}
/**
* 判断是否需要对字符串进行URL编码
* @param s 需要判断的字符串
* @return 如果包含非字母数字字符返回true否则返回false
*/
private fun needsUrlEncode(s: String): Boolean {
return !s.matches(Regex("^[a-zA-Z0-9]*$"))
}
/**
* 验证签名
* @param params 所有请求参数,包括签名
* @param secretKey 密钥
* @param maxAgeMs 允许的最大时间差(毫秒)
* @return 验证结果
*/
fun verifySignature(
params: Map<String, String>, secretKey: String, maxAgeMs: Long = 300000
): VerifyResult {
if (!params.containsKey(options.keyName)) {
return VerifyResult(false, "缺少参数: ${options.keyName}")
}
if (!params.containsKey(options.channelIdName)) {
return VerifyResult(false, "缺少参数: ${options.channelIdName}")
}
val timestampStr =
params[options.timestampName] ?: return VerifyResult(false, "缺少参数: ${options.timestampName}")
val timestamp = timestampStr.toLongOrNull() ?: return VerifyResult(false, "无效的时间戳")
val now = getTimestamp()
if (abs(now - timestamp) > maxAgeMs) {
return VerifyResult(false, "时间戳过期")
}
if (!params.containsKey(options.nonceName)) {
return VerifyResult(false, "缺少参数: ${options.nonceName}")
}
val providedSignature =
params[options.signatureName] ?: return VerifyResult(false, "缺少参数: ${options.signatureName}")
val expectedSignature = calculateSignature(params, secretKey)
return if (expectedSignature.equals(providedSignature, ignoreCase = true)) {
VerifyResult(true)
} else {
VerifyResult(false, "签名不匹配")
}
}
// 签名算法实现
private fun md5(input: String): String {
val md = MessageDigest.getInstance("MD5")
return bytesToHex(md.digest(input.toByteArray()))
}
private fun sha1(input: String): String {
val md = MessageDigest.getInstance("SHA-1")
return bytesToHex(md.digest(input.toByteArray()))
}
private fun sha256(input: String): String {
val md = MessageDigest.getInstance("SHA-256")
return bytesToHex(md.digest(input.toByteArray()))
}
private fun hmacSha256(input: String, key: String): String {
val mac = Mac.getInstance("HmacSHA256")
val secretKeySpec = SecretKeySpec(key.toByteArray(), "HmacSHA256")
mac.init(secretKeySpec)
return bytesToHex(mac.doFinal(input.toByteArray()))
}
private fun bytesToHex(bytes: ByteArray): String {
val hexArray = "0123456789abcdef".toCharArray()
val hexChars = CharArray(bytes.size * 2)
for (j in bytes.indices) {
val v = bytes[j].toInt() and 0xFF
hexChars[j * 2] = hexArray[v ushr 4]
hexChars[j * 2 + 1] = hexArray[v and 0x0F]
}
return String(hexChars)
}
}
/**
* 验证结果
*/
data class VerifyResult(val valid: Boolean, val error: String? = null)

View File

@@ -0,0 +1,151 @@
package com.soundforce.apisign
import kotlinx.cli.ArgParser
import kotlinx.cli.ArgType
import kotlinx.cli.default
import kotlinx.cli.multiple
import java.io.File
import java.util.*
/**
* 主程序入口
*/
fun main(args: Array<String>) {
try {
val envFile = File(".env")
if (envFile.exists()) {
val properties = Properties()
properties.load(envFile.inputStream())
properties.forEach { (key, value) ->
if (System.getenv(key.toString()) == null) {
System.setProperty(key.toString(), value.toString())
}
}
}
} catch (e: Exception) {
println("Warning: Failed to load .env file. ${e.message}")
}
val parser = ArgParser("api-signer")
val algorithm by parser.option(
ArgType.String,
shortName = "a",
fullName = "algorithm",
description = "签名算法: MD5, SHA1, SHA256, HMAC-SHA256"
).default(System.getenv("SIGN_ALGORITHM") ?: "MD5")
val url by parser.option(
ArgType.String,
shortName = "u",
fullName = "url",
description = "API基础URL"
).default(System.getenv("API_BASE_URL") ?: "https://api.example.com/v1/data")
val params by parser.option(
ArgType.String,
shortName = "p",
fullName = "param",
description = "请求参数格式为key=value"
).multiple()
val accessKeyId by parser.option(
ArgType.String,
shortName = "k",
fullName = "key",
description = "访问密钥ID"
).default(System.getenv("ACCESS_KEY_ID") ?: "test-access-key-id")
val secretKey by parser.option(
ArgType.String,
shortName = "s",
fullName = "secret",
description = "密钥"
).default(System.getenv("SECRET_KEY") ?: "test-secret-key")
val channelId by parser.option(
ArgType.String,
shortName = "c",
fullName = "channel",
description = "合作渠道方ID"
).default(System.getenv("CHANNEL_ID") ?: "test-channel-id")
parser.parse(args)
val signAlgorithm = try {
SignatureAlgorithm.fromString(algorithm)
} catch (e: IllegalArgumentException) {
println("Warning: ${e.message}, using MD5 as default")
SignatureAlgorithm.MD5
}
val signer = ApiSigner(SignOptions(algorithm = signAlgorithm, signatureName = "sign"))
val requestParams = mutableMapOf<String, String>()
for (param in params) {
val parts = param.split("=", limit = 2)
if (parts.size == 2) {
requestParams[parts[0]] = parts[1]
}
}
if (requestParams.isEmpty()) {
requestParams["userId"] = "12345"
requestParams["action"] = "getData"
requestParams["data"] = "测试数据"
}
println("===================== API签名示例 =====================")
println("AccessKeyId: $accessKeyId")
println("ChannelId: $channelId")
println("SecretKey: $secretKey")
println("签名算法: $signAlgorithm")
println("基础URL: $url")
println("请求参数:")
requestParams.forEach { (key, value) ->
println(" $key: $value")
}
val signedUrl = signer.signUrl(url, requestParams, accessKeyId, secretKey, channelId)
println("\n签名后的URL:")
println(signedUrl)
val signedParams = signer.signRequest(requestParams, accessKeyId, secretKey, channelId)
println("\n签名后的参数:")
signedParams.forEach { (key, value) ->
println(" $key: $value")
}
demonstrateAlgorithms(requestParams, accessKeyId, secretKey, channelId)
}
/**
* 演示不同算法的签名结果
*/
private fun demonstrateAlgorithms(
params: Map<String, String>,
accessKeyId: String,
secretKey: String,
channelId: String
) {
println("\n不同算法的签名结果:")
val algorithms = listOf(
SignatureAlgorithm.MD5,
SignatureAlgorithm.SHA1,
SignatureAlgorithm.SHA256,
SignatureAlgorithm.HMAC_SHA256
)
for (alg in algorithms) {
val options = SignOptions(algorithm = alg)
val signer = ApiSigner(options)
val signParams = params.toMutableMap()
signParams["AccessKeyId"] = accessKeyId
signParams["channelId"] = channelId
val signature = signer.calculateSignature(signParams, secretKey)
println(" $alg: $signature")
}
}

View File

@@ -0,0 +1,20 @@
package com.soundforce.apisign
/**
* 签名选项
*
* @property algorithm 签名算法
* @property keyName AccessKeyId参数名
* @property channelIdName 合作渠道方ID参数名
* @property timestampName 时间戳参数名
* @property nonceName 随机字符串参数名
* @property signatureName 签名参数名
*/
data class SignOptions(
val algorithm: SignatureAlgorithm = SignatureAlgorithm.MD5,
val keyName: String = "AccessKeyId",
val channelIdName: String = "channelId",
val timestampName: String = "timestamp",
val nonceName: String = "nonce",
val signatureName: String = "sign"
)

View File

@@ -0,0 +1,42 @@
package com.soundforce.apisign
/**
* 签名算法类型
*/
enum class SignatureAlgorithm {
/** MD5算法默认、最快 */
MD5,
/** SHA1算法 */
SHA1,
/** SHA256算法 */
SHA256,
/** HMAC-SHA256算法最安全 */
HMAC_SHA256;
override fun toString(): String {
return when (this) {
MD5 -> "MD5"
SHA1 -> "SHA1"
SHA256 -> "SHA256"
HMAC_SHA256 -> "HMAC-SHA256"
}
}
companion object {
/**
* 从字符串解析算法类型
*/
fun fromString(value: String): SignatureAlgorithm {
return when (value.uppercase()) {
"MD5" -> MD5
"SHA1" -> SHA1
"SHA256" -> SHA256
"HMAC_SHA256", "HMACSHA256", "HMAC-SHA256" -> HMAC_SHA256
else -> throw IllegalArgumentException("无效的签名算法: $value")
}
}
}
}