first commit

This commit is contained in:
usbharu 2023-10-17 00:09:06 +09:00
commit dfa6a4946f
Signed by: usbharu
GPG Key ID: 6556747BF94EEBC8
25 changed files with 839 additions and 0 deletions

42
.gitignore vendored Normal file
View File

@ -0,0 +1,42 @@
.gradle
build/
!gradle/wrapper/gradle-wrapper.jar
!**/src/main/**/build/
!**/src/test/**/build/
### IntelliJ IDEA ###
.idea/modules.xml
.idea/jarRepositories.xml
.idea/compiler.xml
.idea/libraries/
*.iws
*.iml
*.ipr
out/
!**/src/main/**/out/
!**/src/test/**/out/
### Eclipse ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
bin/
!**/src/main/**/bin/
!**/src/test/**/bin/
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
### VS Code ###
.vscode/
### Mac OS ###
.DS_Store

28
build.gradle.kts Normal file
View File

@ -0,0 +1,28 @@
plugins {
kotlin("jvm") version "1.9.0"
application
}
group = "dev.usbharu"
version = "1.0-SNAPSHOT"
repositories {
mavenCentral()
}
dependencies {
testImplementation(kotlin("test"))
testImplementation("org.junit.jupiter:junit-jupiter:5.8.1")
}
tasks.test {
useJUnitPlatform()
}
kotlin {
jvmToolchain(8)
}
application {
mainClass.set("MainKt")
}

1
gradle.properties Normal file
View File

@ -0,0 +1 @@
kotlin.code.style=official

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

Binary file not shown.

View File

@ -0,0 +1,5 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.2-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

234
gradlew vendored Normal file
View File

@ -0,0 +1,234 @@
#!/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.
#
##############################################################################
#
# 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/master/subprojects/plugins/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
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
APP_NAME="Gradle"
APP_BASE_NAME=${0##*/}
# 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"'
# 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=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# 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
which java >/dev/null 2>&1 || 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
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
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
# Collect all arguments for the java command;
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
# shell script including quotes and variable substitutions, so put them in
# double quotes to make sure that they get re-expanded; and
# * put everything else in single quotes, so that it's not re-expanded.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
org.gradle.wrapper.GradleWrapperMain \
"$@"
# 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" "$@"

89
gradlew.bat vendored Normal file
View File

@ -0,0 +1,89 @@
@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
@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=.
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%" == "0" goto execute
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="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!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

12
settings.gradle.kts Normal file
View File

@ -0,0 +1,12 @@
pluginManagement {
repositories {
mavenCentral()
gradlePluginPortal()
}
}
plugins {
id("org.gradle.toolchains.foojay-resolver-convention") version "0.5.0"
}
rootProject.name = "http-signature"

7
src/main/kotlin/Main.kt Normal file
View File

@ -0,0 +1,7 @@
fun main(args: Array<String>) {
println("Hello World!")
// Try adding program arguments via Run/Debug configuration.
// Learn more about running applications: https://www.jetbrains.com/help/idea/running-applications.html.
println("Program arguments: ${args.joinToString()}")
}

View File

@ -0,0 +1,17 @@
package dev.usbharu.httpsignature.common
class HttpHeaders(headers: Map<String, List<String>>) {
private val map = mutableMapOf<String, List<String>>()
init {
map.putAll(headers.map { it.key.lowercase() to it.value })
}
fun get(key: String): List<String> {
return map.get(key.lowercase()) ?: throw IllegalArgumentException("Header $key was not found.")
}
fun plus(key: String, value: List<String>): HttpHeaders {
return HttpHeaders(map.plus(key to value))
}
}

View File

@ -0,0 +1,6 @@
package dev.usbharu.httpsignature.common
enum class HttpMethod(val value: String) {
GET("get"),
POST("post")
}

View File

@ -0,0 +1,5 @@
package dev.usbharu.httpsignature.common
import java.net.URL
class HttpRequest(val url: URL, val headers: HttpHeaders, val method: HttpMethod)

View File

@ -0,0 +1,10 @@
package dev.usbharu.httpsignature.common
import java.security.PrivateKey
import java.security.PublicKey
sealed class Key(open val keyId: String)
data class PrivateKey(val privateKey: PrivateKey, override val keyId: String) : Key(keyId)
data class PublicKey(val publicKey: PublicKey, override val keyId: String) : Key(keyId)

View File

@ -0,0 +1,18 @@
package dev.usbharu.httpsignature.sign
import dev.usbharu.httpsignature.common.HttpHeaders
import dev.usbharu.httpsignature.common.HttpMethod
import dev.usbharu.httpsignature.common.HttpRequest
import dev.usbharu.httpsignature.common.PrivateKey
import java.net.URL
interface HttpSignatureSigner {
fun sign(httpRequest: HttpRequest, privateKey: PrivateKey, signHeaders: List<String>): Signature
fun signRaw(signString: String, privateKey: PrivateKey, signHeaders: List<String>): String
fun buildSignString(
url: URL,
method: HttpMethod,
headers: HttpHeaders,
signHeaders: List<String>
): String
}

View File

@ -0,0 +1,55 @@
package dev.usbharu.httpsignature.sign
import dev.usbharu.httpsignature.common.HttpHeaders
import dev.usbharu.httpsignature.common.HttpMethod
import dev.usbharu.httpsignature.common.HttpRequest
import dev.usbharu.httpsignature.common.PrivateKey
import java.net.URL
import java.util.*
class HttpSignatureSignerImpl : HttpSignatureSigner {
override fun sign(httpRequest: HttpRequest, privateKey: PrivateKey, signHeaders: List<String>): Signature {
val buildSignString = buildSignString(httpRequest.url, httpRequest.method, httpRequest.headers, signHeaders)
val signature = signRaw(buildSignString, privateKey, signHeaders)
val signatureHeader =
"""keyId="${privateKey.keyId}",algorithm="rsa-sha256",headers="${signHeaders.joinToString(" ")}",signature="$signature""""
return Signature(httpRequest, signature, signatureHeader)
}
override fun signRaw(signString: String, privateKey: PrivateKey, signHeaders: List<String>): String {
val signer = java.security.Signature.getInstance("SHA256withRSA")
signer.initSign(privateKey.privateKey)
signer.update(signString.toByteArray())
val sign = signer.sign()
return Base64.getEncoder().encodeToString(sign)
}
override fun buildSignString(
url: URL,
method: HttpMethod,
headers: HttpHeaders,
signHeaders: List<String>
): String {
val result = signHeaders.joinToString("\n") {
if (it.startsWith("(")) {
specialHeader(it, url, method)
} else {
generalHeader(it, headers.get(it)!!)
}
}
return result
}
private fun specialHeader(fieldName: String, url: URL, method: HttpMethod): String {
if (fieldName != "(request-target)") {
throw IllegalArgumentException(fieldName + "is unsupported type")
}
return "(request-target): ${method.value.lowercase()} ${url.path}"
}
// TODO: 複数ヘッダーの正規化をする
private fun generalHeader(fieldName: String, value: List<String>): String = "$fieldName: ${value.first()}"
}

View File

@ -0,0 +1,9 @@
package dev.usbharu.httpsignature.sign
import dev.usbharu.httpsignature.common.HttpRequest
data class Signature(
val request: HttpRequest,
val signature: String,
val signatureHeader: String
)

View File

@ -0,0 +1,21 @@
package dev.usbharu.httpsignature.verify
import dev.usbharu.httpsignature.common.HttpHeaders
class DefaultSignatureHeaderParser : SignatureHeaderParser {
override fun parse(httpHeaders: HttpHeaders): Signature {
val signatureHeader = httpHeaders.get("Signature").single()
val parameters = signatureHeader.split(",")
.map { it.trim() }
.map { it.trim('"') }
.map { it.split("=\"") }
.associate { it[0].split(" ").last() to it[1].trim('"') }
return Signature(
parameters.getValue("keyId"),
parameters.getValue("algorithm"),
parameters.getValue("headers").split(" "),
parameters.getValue("signature")
)
}
}

View File

@ -0,0 +1,9 @@
package dev.usbharu.httpsignature.verify
import dev.usbharu.httpsignature.common.HttpRequest
import dev.usbharu.httpsignature.common.PrivateKey
import dev.usbharu.httpsignature.common.PublicKey
interface HttpSignatureVerifier {
fun verify(httpRequest: HttpRequest,key: PublicKey):VerificationResult
}

View File

@ -0,0 +1,40 @@
package dev.usbharu.httpsignature.verify
import dev.usbharu.httpsignature.common.HttpRequest
import dev.usbharu.httpsignature.common.PublicKey
import dev.usbharu.httpsignature.sign.HttpSignatureSigner
import java.security.Signature
import java.util.*
class HttpSignatureVerifierImpl(
private val signatureHeaderParser: SignatureHeaderParser,
private val httpSignatureSigner: HttpSignatureSigner
) : HttpSignatureVerifier {
override fun verify(httpRequest: HttpRequest, key: PublicKey): VerificationResult {
val signature = signatureHeaderParser.parse(httpRequest.headers)
if (signature.algorithm.equals("rsa-sha256", true).not()) {
return FailedVerification("Unsupported algorithm : ${signature.algorithm}")
}
if (signature.keyId != key.keyId) {
return FailedVerification("The keyid is different.")
}
val byteSignature = Base64.getDecoder().decode(signature.signature)
val buildSignString = httpSignatureSigner.buildSignString(
httpRequest.url, httpRequest.method, httpRequest.headers, signature.headers
)
val signer = Signature.getInstance("SHA256withRSA")
signer.initVerify(key.publicKey)
signer.update(buildSignString.toByteArray())
val verify = signer.verify(byteSignature)
if (verify) {
return SuccessfulVerification()
}
return FailedVerification("Signature verification failed.")
}
}

View File

@ -0,0 +1,8 @@
package dev.usbharu.httpsignature.verify
data class Signature(
val keyId:String,
val algorithm:String,
val headers:List<String>,
val signature:String
)

View File

@ -0,0 +1,7 @@
package dev.usbharu.httpsignature.verify
import dev.usbharu.httpsignature.common.HttpHeaders
interface SignatureHeaderParser {
fun parse(httpHeaders: HttpHeaders):Signature
}

View File

@ -0,0 +1,7 @@
package dev.usbharu.httpsignature.verify
sealed class VerificationResult(val success: Boolean)
class SuccessfulVerification : VerificationResult(true)
open class FailedVerification(val reason:String) : VerificationResult(false)

View File

@ -0,0 +1,82 @@
package dev.usbharu.httpsignature.sign
import dev.usbharu.httpsignature.common.HttpHeaders
import dev.usbharu.httpsignature.common.HttpMethod
import dev.usbharu.httpsignature.common.HttpRequest
import dev.usbharu.httpsignature.common.PrivateKey
import org.junit.jupiter.api.Test
import java.net.URL
import java.security.KeyFactory
import java.security.interfaces.RSAPrivateKey
import java.security.interfaces.RSAPublicKey
import java.security.spec.PKCS8EncodedKeySpec
import java.security.spec.X509EncodedKeySpec
import java.util.*
import kotlin.test.assertEquals
class HttpSignatureSignerImplTest {
@Test
fun 署名を作成できる() {
val privateKey = Base64.getDecoder().decode(
"MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDH+8IRQdB9vhej" +
"eNQqwxlIutt4Xxjg3eZ5XYm7KgR4jAT/q7+cfsz2/fVTNwDOBpG2H1YJZRLUsrVI" +
"3Pia8k7oFyemYKEUN6kaKioO5C9hB0TaiTGlxAKI7syitvedH1YtHqf4zvqgtI2y" +
"Lv0NAXja3nUoWZWgZg8ZUHWAGhtHd/BpL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8xVOUYcn0CbS2+gOQIVp3F9yjvZSdxM7ZMxmn9Dej0BAoGBAJuf" +
"ZZeOLfJPz8AJvCSKLr+swrDEdwbtqfn8xYXhJacMBHwAm3dFFhH2stNWOP09HwzG" +
"CDjZnWbl1zOaOrJu61saEurF6Vk0mZoX4vChn6/kFX/FdSVkEuVYx04LlBnUN8e8" +
"txGpSBtoN8h88IXevoDOjRbIKZuB/Tjc0jagf8FTAoGAWW8uXsWS4c2nBGNdodqL" +
"xJHcNZVMenHPqdkm7rHEYdf1sdbM7r7Q+oj0cifhbZwaRG9HiRGUAgJerLGEqe+x" +
"vNeYuKRF3A5xBFUTw/t+XFhUZ1sSyvOordp0uNahQqkAx1UQFWUBCEkG2k/X81fY" +
"trEnKP2IjOJDzoXGvc4TG0w="
)
val pkcS8EncodedKeySpec = PKCS8EncodedKeySpec(privateKey)
val rsaPrivateKey = KeyFactory.getInstance("RSA").generatePrivate(pkcS8EncodedKeySpec) as RSAPrivateKey
val publicKey = Base64.getDecoder().decode(
"MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAx/vCEUHQfb4Xo3jUKsMZ" +
"SLrbeF8Y4N3meV2JuyoEeIwE/6u/nH7M9v31UzcAzgaRth9WCWUS1LK1SNz4mvJO" +
"6BcnpmChFDepGioqDuQvYQdE2okxpcQCiO7Morb3nR9WLR6n+M76oLSNsi79DQF4" +
"2t51KFmVoGYPGVB1gBobR3fwaS4sr5cFwMnRR5f3jebvLgmYUA9GyiOSiaovFXLO" +
"fUNd/mTRxXYLzY3g/h3NgHTpmweR61tsERIHdbMoAXGe+7Ei8pXnnpfPnVZA7Kv5" +
"eDEFef9D3jp/jyPKSZMkFKapxMas5Lt+eF1vWROl40RIAW/TNABHcgS5OfmG2cIq" +
"qwIDAQAB"
)
val x509EncodedKeySpec = X509EncodedKeySpec(publicKey)
val rsaPublicKey = KeyFactory.getInstance("RSA").generatePublic(x509EncodedKeySpec) as RSAPublicKey
val httpSignatureSignerImpl = HttpSignatureSignerImpl()
val headers = HttpHeaders(
mapOf(
"X-Request-Id" to listOf("00000000-0000-0000-0000-000000000004"),
"Tpp-Redirect-Uri" to listOf("https://www.sometpp.com/redirect/"),
"Digest" to listOf("SHA-256=TGGHcPGLechhcNo4gndoKUvCBhWaQOPgtoVDIpxc6J4="),
"Psu-Id" to listOf("1337")
)
)
val httpRequest = HttpRequest(URL("https://example.com/"), headers, HttpMethod.GET)
val signature = httpSignatureSignerImpl.sign(
httpRequest, PrivateKey(rsaPrivateKey, "https://test-hideout.usbharu.dev/users/c#pubkey"),
listOf("x-request-id", "tpp-redirect-uri", "digest", "psu-id")
)
assertEquals(signature.signature,"qtLXdWmLmGU7safmO7HdWwKztkxnt3D93XXquYRFh3/QSMFHTYQS6ShiZjv8XpVV5NGeGxb1E/evJxwYe1I+oaVIoI5Wx4D5grz1X1g1oC3nqPy6CDZftKC2u5NogVDWy0kzC9PkWNbQJ3ALYV5kaMa+80kHdxB/1bJ0OqTqCO/XpQ6SwuuH4jb1B01xTVoG/qWH452S1r5Wgo2Rdk+qS9Id3mGS3wbLTPa1+hBij2l1ogQ/7alJsXRsBHOGaT8+AoPE3Lr2VtQ+kKyhMQHiGoJBim6JFzRlCSHN2vJ3cg5ahmCW8cwN6wYvkf/qVAomBSH4U4I4cVJH3YlcisA3Tw==")
}
}

View File

@ -0,0 +1,39 @@
package dev.usbharu.httpsignature.verify
import dev.usbharu.httpsignature.common.HttpHeaders
import org.junit.jupiter.api.Assertions.*
import org.junit.jupiter.api.Test
class DefaultSignatureHeaderParserTest{
@Test
fun 必要なヘッダーが全て揃っているリクエストをパースできる() {
val defaultSignatureHeaderParser = DefaultSignatureHeaderParser()
val signature =
defaultSignatureHeaderParser.parse(HttpHeaders(mapOf("Signature" to listOf("keyId=\"https://test-hideout.usbharu.dev/users/c#pubkey\", algorithm=\"rsa-sha256\", headers=\"x-request-id tpp-redirect-uri digest psu-id\", signature=\"FfpkmBogW70FMo94yovGpl15L/m4bDjVIFb9mSZUstPE3H00nHiqNsjAq671qFMJsGOO1uWfLEExcdvzwTiC3wuHShzingvxQUbTgcgRTRZcHbtrOZxT8hYHGndpCXGv/NOLkfXDtZO9v5u0fnA2yJFokzyPHOPJ1cJliWlXP38Bl/pO4H5rBLQBZKpM2jYIjMyI78G2rDXNHEeGrGiyfB5SKb3H6zFQL+X9QpXUI4n0f07VsnwaDyp63oUopmzNUyBEuSqB+8va/lbfcWwrxpZnKGzQRZ+VBcV7jDoKGNOP9/O1xEI2CwB8sh+h6KVHdX3EQEvO1slaaLzcwRRqrQ==\""))))
val expacted = Signature(
"https://test-hideout.usbharu.dev/users/c#pubkey",
"rsa-sha256",
listOf("x-request-id","tpp-redirect-uri","digest","psu-id"),
"FfpkmBogW70FMo94yovGpl15L/m4bDjVIFb9mSZUstPE3H00nHiqNsjAq671qFMJsGOO1uWfLEExcdvzwTiC3wuHShzingvxQUbTgcgRTRZcHbtrOZxT8hYHGndpCXGv/NOLkfXDtZO9v5u0fnA2yJFokzyPHOPJ1cJliWlXP38Bl/pO4H5rBLQBZKpM2jYIjMyI78G2rDXNHEeGrGiyfB5SKb3H6zFQL+X9QpXUI4n0f07VsnwaDyp63oUopmzNUyBEuSqB+8va/lbfcWwrxpZnKGzQRZ+VBcV7jDoKGNOP9/O1xEI2CwB8sh+h6KVHdX3EQEvO1slaaLzcwRRqrQ=="
)
assertEquals(expacted,signature)
}
@Test
fun Signatureヘッダーに不要なパラメーターが入っていてもパースできる() {
val defaultSignatureHeaderParser = DefaultSignatureHeaderParser()
val signature =
defaultSignatureHeaderParser.parse(HttpHeaders(mapOf("Signature" to listOf("Signature keyId=\"https://test-hideout.usbharu.dev/users/c#pubkey\", algorithm=\"rsa-sha256\", headers=\"x-request-id tpp-redirect-uri digest psu-id\", signature=\"tQs/l4DwlbcZ3GOA4IrCB5vSAt5J6pxonzsCg2inPY7O+Nlc3Hk/z559+kyy6CFVpmW+PzzCMzQPVgZUdfTDnRXCAhlgSBRNl88UCkkS34kiq8i0nCd+erVRUZ3wI3ttqEdOxoJWU+l4jKm/C70m8XHhrtVlvUBk6jhdQP27+zrHawORq/Oxxmj5o3K5gqNMyrgXoEp5MCrswju/tzJl1i1w0ppGtQk93syqFdJpPp1dKUyeE0HxcCl8EBVMojZNR0uWpT/ACInaRM988ZMFU7JEKZ8BeuWkiDNA5Gk8J3Gal2z/hAn6pzLI4YiQ+7iH5QHzoB3RMASprl5wb3OQsQ==\""))))
val expacted = Signature(
"https://test-hideout.usbharu.dev/users/c#pubkey",
"rsa-sha256",
listOf("x-request-id","tpp-redirect-uri","digest","psu-id"),
"tQs/l4DwlbcZ3GOA4IrCB5vSAt5J6pxonzsCg2inPY7O+Nlc3Hk/z559+kyy6CFVpmW+PzzCMzQPVgZUdfTDnRXCAhlgSBRNl88UCkkS34kiq8i0nCd+erVRUZ3wI3ttqEdOxoJWU+l4jKm/C70m8XHhrtVlvUBk6jhdQP27+zrHawORq/Oxxmj5o3K5gqNMyrgXoEp5MCrswju/tzJl1i1w0ppGtQk93syqFdJpPp1dKUyeE0HxcCl8EBVMojZNR0uWpT/ACInaRM988ZMFU7JEKZ8BeuWkiDNA5Gk8J3Gal2z/hAn6pzLI4YiQ+7iH5QHzoB3RMASprl5wb3OQsQ=="
)
assertEquals(expacted,signature)
}
}

View File

@ -0,0 +1,88 @@
package dev.usbharu.httpsignature.verify
import dev.usbharu.httpsignature.common.*
import dev.usbharu.httpsignature.sign.HttpSignatureSignerImpl
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.Test
import java.net.URL
import java.security.KeyFactory
import java.security.interfaces.RSAPrivateKey
import java.security.interfaces.RSAPublicKey
import java.security.spec.PKCS8EncodedKeySpec
import java.security.spec.X509EncodedKeySpec
import java.util.*
class HttpSignatureVerifierImplTest {
@Test
fun 署名の検証を行える() {
val privateKey = Base64.getDecoder().decode(
"MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDH+8IRQdB9vhej" +
"eNQqwxlIut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R29wvGjfER" +
"jY/X1MxFKwKBgAUyOz9fqLuLUb4gYqysdOV/zMPtIFDpB+rftZ615SQ8Te2j1Xdt" +
"S+xY6yhZog5XpIQyi4yiWtmPOFKi1zwP879icKHZ8kR+l+ARwPF8dS4FtNiWzsb8" +
"9KjCZhHK79bzZ8xVOUYcn0CbS2+gOQIVp3F9yjvZSdxM7ZMxmn9Dej0BAoGBAJuf" +
"ZZeOLfJPz8AJvCSKLr+swrDEdwbtqfn8xYXhJacMBHwAm3dFFhH2stNWOP09HwzG" +
"CDjZnWbl1zOaOrJu61saEurF6Vk0mZoX4vChn6/kFX/FdSVkEuVYx04LlBnUN8e8" +
"txGpSBtoN8h88IXevoDOjRbIKZuB/Tjc0jagf8FTAoGAWW8uXsWS4c2nBGNdodqL" +
"xJHcNZVMenHPqdkm7rHEYdf1sdbM7r7Q+oj0cifhbZwaRG9HiRGUAgJerLGEqe+x" +
"vNeYuKRF3A5xBFUTw/t+XFhUZ1sSyvOordp0uNahQqkAx1UQFWUBCEkG2k/X81fY" +
"trEnKP2IjOJDzoXGvc4TG0w="
)
val pkcS8EncodedKeySpec = PKCS8EncodedKeySpec(privateKey)
val rsaPrivateKey = KeyFactory.getInstance("RSA").generatePrivate(pkcS8EncodedKeySpec) as RSAPrivateKey
val publicKey = Base64.getDecoder().decode(
"MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAx/vCEUHQfb4Xo3jUKsMZ" +
"SLrbeF8Y4N3meV2JuyoEeIwE/6u/nH7M9v31UzcAzgaRth9WCWUS1LK1SNz4mvJO" +
"6BcnpmChFDepGioqDuQvYQdE2okxpcQCiO7Morb3nR9WLR6n+M76oLSNsi79DQF4" +
"2t51KFmVoGYPGVB1gBobR3fwaS4sr5cFwMnRR5f3jebvLgmYUA9GyiOSiaovFXLO" +
"fUNd/mTRxXYLzY3g/h3NgHTpmweR61tsERIHdbMoAXGe+7Ei8pXnnpfPnVZA7Kv5" +
"eDEFef9D3jp/jyPKSZMkFKapxMas5Lt+eF1vWROl40RIAW/TNABHcgS5OfmG2cIq" +
"qwIDAQAB"
)
val x509EncodedKeySpec = X509EncodedKeySpec(publicKey)
val rsaPublicKey = KeyFactory.getInstance("RSA").generatePublic(x509EncodedKeySpec) as RSAPublicKey
val httpSignatureSignerImpl = HttpSignatureSignerImpl()
val headers = HttpHeaders(
mapOf(
"X-Request-Id" to listOf("00000000-0000-0000-0000-000000000004"),
"Tpp-Redirect-Uri" to listOf("https://www.sometpp.com/redirect/"),
"Digest" to listOf("SHA-256=TGGHcPGLechhcNo4gndoKUvCBhWaQOPgtoVDIpxc6J4="),
"Psu-Id" to listOf("1337")
)
)
val url = URL("https://example.com/")
val httpRequest = HttpRequest(url, headers, HttpMethod.GET)
val signature = httpSignatureSignerImpl.sign(
httpRequest, PrivateKey(rsaPrivateKey, "https://test-hideout.usbharu.dev/users/c#pubkey"),
listOf("x-request-id", "tpp-redirect-uri", "digest", "psu-id")
)
val httpSignatureVerifierImpl =
HttpSignatureVerifierImpl(DefaultSignatureHeaderParser(), httpSignatureSignerImpl)
val verify = httpSignatureVerifierImpl.verify(
HttpRequest(url, headers.plus("Signature", listOf(signature.signatureHeader)), HttpMethod.GET),
PublicKey(rsaPublicKey, "https://test-hideout.usbharu.dev/users/c#pubkey")
)
Assertions.assertInstanceOf(SuccessfulVerification::class.java,verify)
}
}