edit
This commit is contained in:
parent
12882ae777
commit
f93ffcc770
31
encrypt/rsa-redis-demo/.gitignore
vendored
Normal file
31
encrypt/rsa-redis-demo/.gitignore
vendored
Normal file
@ -0,0 +1,31 @@
|
||||
HELP.md
|
||||
target/
|
||||
!.mvn/wrapper/maven-wrapper.jar
|
||||
!**/src/main/**
|
||||
!**/src/test/**
|
||||
|
||||
### STS ###
|
||||
.apt_generated
|
||||
.classpath
|
||||
.factorypath
|
||||
.project
|
||||
.settings
|
||||
.springBeans
|
||||
.sts4-cache
|
||||
|
||||
### IntelliJ IDEA ###
|
||||
.idea
|
||||
*.iws
|
||||
*.iml
|
||||
*.ipr
|
||||
|
||||
### NetBeans ###
|
||||
/nbproject/private/
|
||||
/nbbuild/
|
||||
/dist/
|
||||
/nbdist/
|
||||
/.nb-gradle/
|
||||
build/
|
||||
|
||||
### VS Code ###
|
||||
.vscode/
|
13
encrypt/rsa-redis-demo/README.md
Normal file
13
encrypt/rsa-redis-demo/README.md
Normal file
@ -0,0 +1,13 @@
|
||||
# 工程简介
|
||||
参考:https://blog.csdn.net/weixin_38192427/article/details/120588208
|
||||
<br/>
|
||||
##访问登录页面
|
||||
http://localhost:8080/login
|
||||
##调用流程
|
||||
1、前端调用后端接口获取公钥,对密码进行加密。
|
||||
<br/>
|
||||
2、前端调用登录接口,将加密密码传到后端。
|
||||
<br/>
|
||||
3、后端对密码解密,存入数据库。
|
||||
# 延伸阅读
|
||||
|
310
encrypt/rsa-redis-demo/mvnw
vendored
Normal file
310
encrypt/rsa-redis-demo/mvnw
vendored
Normal file
@ -0,0 +1,310 @@
|
||||
#!/bin/sh
|
||||
# ----------------------------------------------------------------------------
|
||||
# Licensed to the Apache Software Foundation (ASF) under one
|
||||
# or more contributor license agreements. See the NOTICE file
|
||||
# distributed with this work for additional information
|
||||
# regarding copyright ownership. The ASF licenses this file
|
||||
# to you 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.
|
||||
# ----------------------------------------------------------------------------
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
# Maven Start Up Batch script
|
||||
#
|
||||
# Required ENV vars:
|
||||
# ------------------
|
||||
# JAVA_HOME - location of a JDK home dir
|
||||
#
|
||||
# Optional ENV vars
|
||||
# -----------------
|
||||
# M2_HOME - location of maven2's installed home dir
|
||||
# MAVEN_OPTS - parameters passed to the Java VM when running Maven
|
||||
# e.g. to debug Maven itself, use
|
||||
# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
|
||||
# MAVEN_SKIP_RC - flag to disable loading of mavenrc files
|
||||
# ----------------------------------------------------------------------------
|
||||
|
||||
if [ -z "$MAVEN_SKIP_RC" ] ; then
|
||||
|
||||
if [ -f /etc/mavenrc ] ; then
|
||||
. /etc/mavenrc
|
||||
fi
|
||||
|
||||
if [ -f "$HOME/.mavenrc" ] ; then
|
||||
. "$HOME/.mavenrc"
|
||||
fi
|
||||
|
||||
fi
|
||||
|
||||
# OS specific support. $var _must_ be set to either true or false.
|
||||
cygwin=false;
|
||||
darwin=false;
|
||||
mingw=false
|
||||
case "`uname`" in
|
||||
CYGWIN*) cygwin=true ;;
|
||||
MINGW*) mingw=true;;
|
||||
Darwin*) darwin=true
|
||||
# Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home
|
||||
# See https://developer.apple.com/library/mac/qa/qa1170/_index.html
|
||||
if [ -z "$JAVA_HOME" ]; then
|
||||
if [ -x "/usr/libexec/java_home" ]; then
|
||||
export JAVA_HOME="`/usr/libexec/java_home`"
|
||||
else
|
||||
export JAVA_HOME="/Library/Java/Home"
|
||||
fi
|
||||
fi
|
||||
;;
|
||||
esac
|
||||
|
||||
if [ -z "$JAVA_HOME" ] ; then
|
||||
if [ -r /etc/gentoo-release ] ; then
|
||||
JAVA_HOME=`java-config --jre-home`
|
||||
fi
|
||||
fi
|
||||
|
||||
if [ -z "$M2_HOME" ] ; then
|
||||
## resolve links - $0 may be a link to maven's home
|
||||
PRG="$0"
|
||||
|
||||
# need this for relative symlinks
|
||||
while [ -h "$PRG" ] ; do
|
||||
ls=`ls -ld "$PRG"`
|
||||
link=`expr "$ls" : '.*-> \(.*\)$'`
|
||||
if expr "$link" : '/.*' > /dev/null; then
|
||||
PRG="$link"
|
||||
else
|
||||
PRG="`dirname "$PRG"`/$link"
|
||||
fi
|
||||
done
|
||||
|
||||
saveddir=`pwd`
|
||||
|
||||
M2_HOME=`dirname "$PRG"`/..
|
||||
|
||||
# make it fully qualified
|
||||
M2_HOME=`cd "$M2_HOME" && pwd`
|
||||
|
||||
cd "$saveddir"
|
||||
# echo Using m2 at $M2_HOME
|
||||
fi
|
||||
|
||||
# For Cygwin, ensure paths are in UNIX format before anything is touched
|
||||
if $cygwin ; then
|
||||
[ -n "$M2_HOME" ] &&
|
||||
M2_HOME=`cygpath --unix "$M2_HOME"`
|
||||
[ -n "$JAVA_HOME" ] &&
|
||||
JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
|
||||
[ -n "$CLASSPATH" ] &&
|
||||
CLASSPATH=`cygpath --path --unix "$CLASSPATH"`
|
||||
fi
|
||||
|
||||
# For Mingw, ensure paths are in UNIX format before anything is touched
|
||||
if $mingw ; then
|
||||
[ -n "$M2_HOME" ] &&
|
||||
M2_HOME="`(cd "$M2_HOME"; pwd)`"
|
||||
[ -n "$JAVA_HOME" ] &&
|
||||
JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`"
|
||||
fi
|
||||
|
||||
if [ -z "$JAVA_HOME" ]; then
|
||||
javaExecutable="`which javac`"
|
||||
if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then
|
||||
# readlink(1) is not available as standard on Solaris 10.
|
||||
readLink=`which readlink`
|
||||
if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then
|
||||
if $darwin ; then
|
||||
javaHome="`dirname \"$javaExecutable\"`"
|
||||
javaExecutable="`cd \"$javaHome\" && pwd -P`/javac"
|
||||
else
|
||||
javaExecutable="`readlink -f \"$javaExecutable\"`"
|
||||
fi
|
||||
javaHome="`dirname \"$javaExecutable\"`"
|
||||
javaHome=`expr "$javaHome" : '\(.*\)/bin'`
|
||||
JAVA_HOME="$javaHome"
|
||||
export JAVA_HOME
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
|
||||
if [ -z "$JAVACMD" ] ; then
|
||||
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
|
||||
else
|
||||
JAVACMD="`which java`"
|
||||
fi
|
||||
fi
|
||||
|
||||
if [ ! -x "$JAVACMD" ] ; then
|
||||
echo "Error: JAVA_HOME is not defined correctly." >&2
|
||||
echo " We cannot execute $JAVACMD" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [ -z "$JAVA_HOME" ] ; then
|
||||
echo "Warning: JAVA_HOME environment variable is not set."
|
||||
fi
|
||||
|
||||
CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher
|
||||
|
||||
# traverses directory structure from process work directory to filesystem root
|
||||
# first directory with .mvn subdirectory is considered project base directory
|
||||
find_maven_basedir() {
|
||||
|
||||
if [ -z "$1" ]
|
||||
then
|
||||
echo "Path not specified to find_maven_basedir"
|
||||
return 1
|
||||
fi
|
||||
|
||||
basedir="$1"
|
||||
wdir="$1"
|
||||
while [ "$wdir" != '/' ] ; do
|
||||
if [ -d "$wdir"/.mvn ] ; then
|
||||
basedir=$wdir
|
||||
break
|
||||
fi
|
||||
# workaround for JBEAP-8937 (on Solaris 10/Sparc)
|
||||
if [ -d "${wdir}" ]; then
|
||||
wdir=`cd "$wdir/.."; pwd`
|
||||
fi
|
||||
# end of workaround
|
||||
done
|
||||
echo "${basedir}"
|
||||
}
|
||||
|
||||
# concatenates all lines of a file
|
||||
concat_lines() {
|
||||
if [ -f "$1" ]; then
|
||||
echo "$(tr -s '\n' ' ' < "$1")"
|
||||
fi
|
||||
}
|
||||
|
||||
BASE_DIR=`find_maven_basedir "$(pwd)"`
|
||||
if [ -z "$BASE_DIR" ]; then
|
||||
exit 1;
|
||||
fi
|
||||
|
||||
##########################################################################################
|
||||
# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
|
||||
# This allows using the maven wrapper in projects that prohibit checking in binary data.
|
||||
##########################################################################################
|
||||
if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then
|
||||
if [ "$MVNW_VERBOSE" = true ]; then
|
||||
echo "Found .mvn/wrapper/maven-wrapper.jar"
|
||||
fi
|
||||
else
|
||||
if [ "$MVNW_VERBOSE" = true ]; then
|
||||
echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..."
|
||||
fi
|
||||
if [ -n "$MVNW_REPOURL" ]; then
|
||||
jarUrl="$MVNW_REPOURL/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
|
||||
else
|
||||
jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
|
||||
fi
|
||||
while IFS="=" read key value; do
|
||||
case "$key" in (wrapperUrl) jarUrl="$value"; break ;;
|
||||
esac
|
||||
done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties"
|
||||
if [ "$MVNW_VERBOSE" = true ]; then
|
||||
echo "Downloading from: $jarUrl"
|
||||
fi
|
||||
wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar"
|
||||
if $cygwin; then
|
||||
wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"`
|
||||
fi
|
||||
|
||||
if command -v wget > /dev/null; then
|
||||
if [ "$MVNW_VERBOSE" = true ]; then
|
||||
echo "Found wget ... using wget"
|
||||
fi
|
||||
if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
|
||||
wget "$jarUrl" -O "$wrapperJarPath"
|
||||
else
|
||||
wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath"
|
||||
fi
|
||||
elif command -v curl > /dev/null; then
|
||||
if [ "$MVNW_VERBOSE" = true ]; then
|
||||
echo "Found curl ... using curl"
|
||||
fi
|
||||
if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
|
||||
curl -o "$wrapperJarPath" "$jarUrl" -f
|
||||
else
|
||||
curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f
|
||||
fi
|
||||
|
||||
else
|
||||
if [ "$MVNW_VERBOSE" = true ]; then
|
||||
echo "Falling back to using Java to download"
|
||||
fi
|
||||
javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java"
|
||||
# For Cygwin, switch paths to Windows format before running javac
|
||||
if $cygwin; then
|
||||
javaClass=`cygpath --path --windows "$javaClass"`
|
||||
fi
|
||||
if [ -e "$javaClass" ]; then
|
||||
if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
|
||||
if [ "$MVNW_VERBOSE" = true ]; then
|
||||
echo " - Compiling MavenWrapperDownloader.java ..."
|
||||
fi
|
||||
# Compiling the Java class
|
||||
("$JAVA_HOME/bin/javac" "$javaClass")
|
||||
fi
|
||||
if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
|
||||
# Running the downloader
|
||||
if [ "$MVNW_VERBOSE" = true ]; then
|
||||
echo " - Running MavenWrapperDownloader.java ..."
|
||||
fi
|
||||
("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR")
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
##########################################################################################
|
||||
# End of extension
|
||||
##########################################################################################
|
||||
|
||||
export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"}
|
||||
if [ "$MVNW_VERBOSE" = true ]; then
|
||||
echo $MAVEN_PROJECTBASEDIR
|
||||
fi
|
||||
MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS"
|
||||
|
||||
# For Cygwin, switch paths to Windows format before running java
|
||||
if $cygwin; then
|
||||
[ -n "$M2_HOME" ] &&
|
||||
M2_HOME=`cygpath --path --windows "$M2_HOME"`
|
||||
[ -n "$JAVA_HOME" ] &&
|
||||
JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"`
|
||||
[ -n "$CLASSPATH" ] &&
|
||||
CLASSPATH=`cygpath --path --windows "$CLASSPATH"`
|
||||
[ -n "$MAVEN_PROJECTBASEDIR" ] &&
|
||||
MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"`
|
||||
fi
|
||||
|
||||
# Provide a "standardized" way to retrieve the CLI args that will
|
||||
# work with both Windows and non-Windows executions.
|
||||
MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@"
|
||||
export MAVEN_CMD_LINE_ARGS
|
||||
|
||||
WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
|
||||
|
||||
exec "$JAVACMD" \
|
||||
$MAVEN_OPTS \
|
||||
-classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \
|
||||
"-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \
|
||||
${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@"
|
182
encrypt/rsa-redis-demo/mvnw.cmd
vendored
Normal file
182
encrypt/rsa-redis-demo/mvnw.cmd
vendored
Normal file
@ -0,0 +1,182 @@
|
||||
@REM ----------------------------------------------------------------------------
|
||||
@REM Licensed to the Apache Software Foundation (ASF) under one
|
||||
@REM or more contributor license agreements. See the NOTICE file
|
||||
@REM distributed with this work for additional information
|
||||
@REM regarding copyright ownership. The ASF licenses this file
|
||||
@REM to you under the Apache License, Version 2.0 (the
|
||||
@REM "License"); you may not use this file except in compliance
|
||||
@REM with the License. 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,
|
||||
@REM software distributed under the License is distributed on an
|
||||
@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
@REM KIND, either express or implied. See the License for the
|
||||
@REM specific language governing permissions and limitations
|
||||
@REM under the License.
|
||||
@REM ----------------------------------------------------------------------------
|
||||
|
||||
@REM ----------------------------------------------------------------------------
|
||||
@REM Maven Start Up Batch script
|
||||
@REM
|
||||
@REM Required ENV vars:
|
||||
@REM JAVA_HOME - location of a JDK home dir
|
||||
@REM
|
||||
@REM Optional ENV vars
|
||||
@REM M2_HOME - location of maven2's installed home dir
|
||||
@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands
|
||||
@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending
|
||||
@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven
|
||||
@REM e.g. to debug Maven itself, use
|
||||
@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
|
||||
@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files
|
||||
@REM ----------------------------------------------------------------------------
|
||||
|
||||
@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on'
|
||||
@echo off
|
||||
@REM set title of command window
|
||||
title %0
|
||||
@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on'
|
||||
@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO%
|
||||
|
||||
@REM set %HOME% to equivalent of $HOME
|
||||
if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%")
|
||||
|
||||
@REM Execute a user defined script before this one
|
||||
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre
|
||||
@REM check for pre script, once with legacy .bat ending and once with .cmd ending
|
||||
if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat"
|
||||
if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd"
|
||||
:skipRcPre
|
||||
|
||||
@setlocal
|
||||
|
||||
set ERROR_CODE=0
|
||||
|
||||
@REM To isolate internal variables from possible post scripts, we use another setlocal
|
||||
@setlocal
|
||||
|
||||
@REM ==== START VALIDATION ====
|
||||
if not "%JAVA_HOME%" == "" goto OkJHome
|
||||
|
||||
echo.
|
||||
echo Error: JAVA_HOME not found in your environment. >&2
|
||||
echo Please set the JAVA_HOME variable in your environment to match the >&2
|
||||
echo location of your Java installation. >&2
|
||||
echo.
|
||||
goto error
|
||||
|
||||
:OkJHome
|
||||
if exist "%JAVA_HOME%\bin\java.exe" goto init
|
||||
|
||||
echo.
|
||||
echo Error: JAVA_HOME is set to an invalid directory. >&2
|
||||
echo JAVA_HOME = "%JAVA_HOME%" >&2
|
||||
echo Please set the JAVA_HOME variable in your environment to match the >&2
|
||||
echo location of your Java installation. >&2
|
||||
echo.
|
||||
goto error
|
||||
|
||||
@REM ==== END VALIDATION ====
|
||||
|
||||
:init
|
||||
|
||||
@REM Find the project base dir, i.e. the directory that contains the folder ".mvn".
|
||||
@REM Fallback to current working directory if not found.
|
||||
|
||||
set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR%
|
||||
IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir
|
||||
|
||||
set EXEC_DIR=%CD%
|
||||
set WDIR=%EXEC_DIR%
|
||||
:findBaseDir
|
||||
IF EXIST "%WDIR%"\.mvn goto baseDirFound
|
||||
cd ..
|
||||
IF "%WDIR%"=="%CD%" goto baseDirNotFound
|
||||
set WDIR=%CD%
|
||||
goto findBaseDir
|
||||
|
||||
:baseDirFound
|
||||
set MAVEN_PROJECTBASEDIR=%WDIR%
|
||||
cd "%EXEC_DIR%"
|
||||
goto endDetectBaseDir
|
||||
|
||||
:baseDirNotFound
|
||||
set MAVEN_PROJECTBASEDIR=%EXEC_DIR%
|
||||
cd "%EXEC_DIR%"
|
||||
|
||||
:endDetectBaseDir
|
||||
|
||||
IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig
|
||||
|
||||
@setlocal EnableExtensions EnableDelayedExpansion
|
||||
for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a
|
||||
@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS%
|
||||
|
||||
:endReadAdditionalConfig
|
||||
|
||||
SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe"
|
||||
set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar"
|
||||
set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
|
||||
|
||||
set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
|
||||
|
||||
FOR /F "tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO (
|
||||
IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B
|
||||
)
|
||||
|
||||
@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
|
||||
@REM This allows using the maven wrapper in projects that prohibit checking in binary data.
|
||||
if exist %WRAPPER_JAR% (
|
||||
if "%MVNW_VERBOSE%" == "true" (
|
||||
echo Found %WRAPPER_JAR%
|
||||
)
|
||||
) else (
|
||||
if not "%MVNW_REPOURL%" == "" (
|
||||
SET DOWNLOAD_URL="%MVNW_REPOURL%/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
|
||||
)
|
||||
if "%MVNW_VERBOSE%" == "true" (
|
||||
echo Couldn't find %WRAPPER_JAR%, downloading it ...
|
||||
echo Downloading from: %DOWNLOAD_URL%
|
||||
)
|
||||
|
||||
powershell -Command "&{"^
|
||||
"$webclient = new-object System.Net.WebClient;"^
|
||||
"if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^
|
||||
"$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^
|
||||
"}"^
|
||||
"[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^
|
||||
"}"
|
||||
if "%MVNW_VERBOSE%" == "true" (
|
||||
echo Finished downloading %WRAPPER_JAR%
|
||||
)
|
||||
)
|
||||
@REM End of extension
|
||||
|
||||
@REM Provide a "standardized" way to retrieve the CLI args that will
|
||||
@REM work with both Windows and non-Windows executions.
|
||||
set MAVEN_CMD_LINE_ARGS=%*
|
||||
|
||||
%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %*
|
||||
if ERRORLEVEL 1 goto error
|
||||
goto end
|
||||
|
||||
:error
|
||||
set ERROR_CODE=1
|
||||
|
||||
:end
|
||||
@endlocal & set ERROR_CODE=%ERROR_CODE%
|
||||
|
||||
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost
|
||||
@REM check for post script, once with legacy .bat ending and once with .cmd ending
|
||||
if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat"
|
||||
if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd"
|
||||
:skipRcPost
|
||||
|
||||
@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on'
|
||||
if "%MAVEN_BATCH_PAUSE%" == "on" pause
|
||||
|
||||
if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE%
|
||||
|
||||
exit /B %ERROR_CODE%
|
123
encrypt/rsa-redis-demo/pom.xml
Normal file
123
encrypt/rsa-redis-demo/pom.xml
Normal file
@ -0,0 +1,123 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.ybw</groupId>
|
||||
<artifactId>rsa-redis-demo</artifactId>
|
||||
<version>1.0.0</version>
|
||||
<name>rsa-redis-demo</name>
|
||||
<description>rsa web密码加密</description>
|
||||
|
||||
<properties>
|
||||
<java.version>1.8</java.version>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
|
||||
<spring-boot.version>2.6.6</spring-boot.version>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-web</artifactId>
|
||||
</dependency>
|
||||
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-thymeleaf -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-thymeleaf</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
<optional>true</optional>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-collections4</artifactId>
|
||||
<version>4.4</version>
|
||||
</dependency>
|
||||
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
<version>3.12.0</version>
|
||||
</dependency>
|
||||
<!-- https://mvnrepository.com/artifact/commons-codec/commons-codec -->
|
||||
<dependency>
|
||||
<groupId>commons-codec</groupId>
|
||||
<artifactId>commons-codec</artifactId>
|
||||
<version>1.15</version>
|
||||
</dependency>
|
||||
<!-- https://mvnrepository.com/artifact/org.bouncycastle/bcprov-ext-jdk15on -->
|
||||
<dependency>
|
||||
<groupId>org.bouncycastle</groupId>
|
||||
<artifactId>bcprov-ext-jdk15on</artifactId>
|
||||
<version>1.70</version>
|
||||
</dependency>
|
||||
<!-- https://mvnrepository.com/artifact/com.alibaba.fastjson2/fastjson2 -->
|
||||
<dependency>
|
||||
<groupId>com.alibaba.fastjson2</groupId>
|
||||
<artifactId>fastjson2</artifactId>
|
||||
<version>2.0.11</version>
|
||||
</dependency>
|
||||
<!--redis start-->
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-data-redis</artifactId>
|
||||
</dependency>
|
||||
<!--spring2.0集成redis所需common-pool2 -->
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-pool2</artifactId>
|
||||
</dependency>
|
||||
<!--redis end-->
|
||||
</dependencies>
|
||||
|
||||
<dependencyManagement>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-dependencies</artifactId>
|
||||
<version>${spring-boot.version}</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</dependencyManagement>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>3.8.1</version>
|
||||
<configuration>
|
||||
<source>1.8</source>
|
||||
<target>1.8</target>
|
||||
<encoding>UTF-8</encoding>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
<version>2.4.1</version>
|
||||
<configuration>
|
||||
<mainClass>com.ybw.rsa.demo.RsaDemoApplication</mainClass>
|
||||
</configuration>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>repackage</id>
|
||||
<goals>
|
||||
<goal>repackage</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
</project>
|
@ -0,0 +1,13 @@
|
||||
package com.ybw.rsa.demo;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
@SpringBootApplication
|
||||
public class RsaDemoApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(RsaDemoApplication.class, args);
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,106 @@
|
||||
package com.ybw.rsa.demo.config;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonAutoDetect;
|
||||
import com.fasterxml.jackson.annotation.JsonTypeInfo;
|
||||
import com.fasterxml.jackson.annotation.PropertyAccessor;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.SerializationFeature;
|
||||
import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
|
||||
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
|
||||
import org.springframework.cache.CacheManager;
|
||||
import org.springframework.cache.annotation.CachingConfigurerSupport;
|
||||
import org.springframework.cache.annotation.EnableCaching;
|
||||
import org.springframework.cache.interceptor.KeyGenerator;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.data.redis.cache.RedisCacheManager;
|
||||
import org.springframework.data.redis.connection.RedisConnectionFactory;
|
||||
import org.springframework.data.redis.core.RedisTemplate;
|
||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
|
||||
/**
|
||||
* 缓存管理(注解用)
|
||||
*
|
||||
* @author ybwei
|
||||
* @date 2022/2/18 16:55
|
||||
**/
|
||||
@Configuration
|
||||
@EnableCaching
|
||||
public class CacheConfig extends CachingConfigurerSupport {
|
||||
|
||||
/**
|
||||
* 生成key的策略
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
@Override
|
||||
@Bean
|
||||
public KeyGenerator keyGenerator() {
|
||||
return new KeyGenerator() {
|
||||
@Override
|
||||
public Object generate(Object target, Method method, Object... params) {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append(target.getClass().getName());
|
||||
sb.append(method.getName());
|
||||
for (Object obj : params) {
|
||||
sb.append(obj.toString());
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 管理缓存
|
||||
*
|
||||
* @param redisConnectionFactory
|
||||
* @methodName: cacheManager
|
||||
* @return: org.springframework.cache.CacheManager
|
||||
* @author: geoffrey
|
||||
* @date: 2022/2/16
|
||||
**/
|
||||
@Bean
|
||||
public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
|
||||
RedisCacheManager.RedisCacheManagerBuilder builder = RedisCacheManager.RedisCacheManagerBuilder
|
||||
.fromConnectionFactory(redisConnectionFactory);
|
||||
return builder.build();
|
||||
}
|
||||
|
||||
/**
|
||||
* RedisTemplate配置
|
||||
*
|
||||
* @param factory
|
||||
* @methodName: redisTemplate
|
||||
* @return: org.springframework.data.redis.core.RedisTemplate<java.lang.String, java.lang.String>
|
||||
* @author: geoffrey
|
||||
* @date: 2022/2/16
|
||||
**/
|
||||
@Bean
|
||||
public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
|
||||
StringRedisTemplate template = new StringRedisTemplate(factory);
|
||||
// 使用Jackson库将对象序列化为JSON字符串
|
||||
Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<Object>(
|
||||
Object.class);
|
||||
ObjectMapper om = new ObjectMapper();
|
||||
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
|
||||
om.activateDefaultTyping(
|
||||
LaissezFaireSubTypeValidator.instance,
|
||||
ObjectMapper.DefaultTyping.NON_FINAL,
|
||||
JsonTypeInfo.As.WRAPPER_ARRAY);
|
||||
// 解决jackson2无法反序列化LocalDateTime的问题
|
||||
om.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
|
||||
om.registerModule(new JavaTimeModule());
|
||||
jackson2JsonRedisSerializer.setObjectMapper(om);
|
||||
//key
|
||||
template.setKeySerializer(jackson2JsonRedisSerializer);
|
||||
template.setValueSerializer(jackson2JsonRedisSerializer);
|
||||
//hash
|
||||
template.setHashKeySerializer(jackson2JsonRedisSerializer);
|
||||
template.setHashValueSerializer(jackson2JsonRedisSerializer);
|
||||
template.afterPropertiesSet();
|
||||
return template;
|
||||
}
|
||||
}
|
@ -0,0 +1,17 @@
|
||||
package com.ybw.rsa.demo.constant;
|
||||
|
||||
/**
|
||||
* @author ybwei
|
||||
* @Description redis前缀
|
||||
* @date 2021/3/20 14:15
|
||||
**/
|
||||
public class RedisPreConstant {
|
||||
/**
|
||||
* rsa
|
||||
*
|
||||
* @author: ybw
|
||||
* @date: 2022/8/12
|
||||
**/
|
||||
public final static String RSA = "RSA:";
|
||||
|
||||
}
|
@ -0,0 +1,32 @@
|
||||
package com.ybw.rsa.demo.constant;
|
||||
|
||||
/**
|
||||
* @author ybw
|
||||
* @version V1.0
|
||||
* @className RsaConstant
|
||||
* @date 2022/8/12
|
||||
**/
|
||||
public interface RsaConstant {
|
||||
/**
|
||||
* 私钥
|
||||
*
|
||||
* @author: ybw
|
||||
* @date: 2022/8/12
|
||||
**/
|
||||
String PRIVATE_KEY = "PRIVATE_KEY";
|
||||
/**
|
||||
* 公钥
|
||||
*
|
||||
* @author: ybw
|
||||
* @date: 2022/8/12
|
||||
**/
|
||||
String PUBLIC_KEY = "PUBLIC_KEY";
|
||||
|
||||
/**
|
||||
* 秘钥大小
|
||||
*
|
||||
* @author: ybw
|
||||
* @date: 2022/8/12
|
||||
**/
|
||||
Integer KEY_SIZE = 1024;
|
||||
}
|
@ -0,0 +1,50 @@
|
||||
package com.ybw.rsa.demo.controller;
|
||||
|
||||
import com.alibaba.fastjson2.JSON;
|
||||
import com.ybw.rsa.demo.service.RsaService;
|
||||
import com.ybw.rsa.demo.vo.req.LoginReqVO;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
|
||||
@Controller
|
||||
@Slf4j
|
||||
public class LoginController {
|
||||
|
||||
@Resource
|
||||
private RsaService rsaService;
|
||||
|
||||
/**
|
||||
*
|
||||
* @methodName: login
|
||||
* @param model
|
||||
* @return: java.lang.String
|
||||
* @author: ybw
|
||||
* @date: 2022/8/12
|
||||
**/
|
||||
@GetMapping("/login")
|
||||
public String login(Model model){
|
||||
model.addAttribute("msg", "RSA前端加密,后端解密测试");
|
||||
return "login";
|
||||
}
|
||||
|
||||
/**
|
||||
* @param loginReqVO
|
||||
* @methodName: login
|
||||
* @return: java.lang.String
|
||||
* @author: ybw
|
||||
* @date: 2022/8/12
|
||||
**/
|
||||
@PostMapping(value = "/login")
|
||||
@ResponseBody
|
||||
public String login(@RequestBody LoginReqVO loginReqVO) throws Exception {
|
||||
log.info("loginReqVO:{}", JSON.toJSONString(loginReqVO));
|
||||
//解密后的密码
|
||||
String password = rsaService.decryptWithPrivate(loginReqVO.getPassword());
|
||||
log.info("解密后密码,password:{}", password);
|
||||
return "OK";
|
||||
}
|
||||
}
|
@ -0,0 +1,32 @@
|
||||
package com.ybw.rsa.demo.controller;
|
||||
|
||||
import com.ybw.rsa.demo.service.RsaService;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
|
||||
/**
|
||||
* @author ybwei
|
||||
* @version V1.0
|
||||
* @className RSAController
|
||||
* @date 2022/8/12
|
||||
**/
|
||||
@RestController
|
||||
public class RSAController {
|
||||
@Resource
|
||||
private RsaService rsaService;
|
||||
|
||||
/**
|
||||
* 获取公钥
|
||||
*
|
||||
* @methodName: getPublicKey
|
||||
* @return: java.lang.String
|
||||
* @author: ybw
|
||||
* @date: 2022/8/12
|
||||
**/
|
||||
@GetMapping("/getPublicKey")
|
||||
public String getPublicKey() throws Exception {
|
||||
return rsaService.getPublicKey();
|
||||
}
|
||||
}
|
@ -0,0 +1,54 @@
|
||||
package com.ybw.rsa.demo.service;
|
||||
|
||||
/**
|
||||
* RSA接口
|
||||
*
|
||||
* @author ybwei
|
||||
* @version V1.0
|
||||
* @className RsaService
|
||||
* @date 2022/8/13
|
||||
**/
|
||||
public interface RsaService {
|
||||
/**
|
||||
* 私钥解密
|
||||
*
|
||||
* @param encryptText
|
||||
* @methodName: decryptWithPrivate
|
||||
* @return: java.lang.String
|
||||
* @author: ybwei
|
||||
* @date: 2022/8/12
|
||||
**/
|
||||
String decryptWithPrivate(String encryptText) throws Exception;
|
||||
|
||||
/**
|
||||
* 公钥加密-测试
|
||||
*
|
||||
* @param plaintext 明文内容
|
||||
* @methodName: encrypt
|
||||
* @return: byte[]
|
||||
* @author: ybwei
|
||||
* @date: 2022/8/12
|
||||
**/
|
||||
byte[] encrypt(String plaintext) throws Exception;
|
||||
|
||||
/**
|
||||
* 私钥解密-测试
|
||||
*
|
||||
* @param cipherText 加密后的字节数组
|
||||
* @methodName: decrypt
|
||||
* @return: java.lang.String
|
||||
* @author: ybwei
|
||||
* @date: 2022/8/12
|
||||
**/
|
||||
String decrypt(byte[] cipherText) throws Exception;
|
||||
|
||||
/**
|
||||
* 获取公钥
|
||||
*
|
||||
* @methodName: getPublicKey
|
||||
* @return: java.lang.String
|
||||
* @author: ybwei
|
||||
* @date: 2022/8/12
|
||||
**/
|
||||
String getPublicKey() throws Exception;
|
||||
}
|
@ -0,0 +1,270 @@
|
||||
package com.ybw.rsa.demo.service.impl;
|
||||
|
||||
import com.ybw.rsa.demo.constant.RedisPreConstant;
|
||||
import com.ybw.rsa.demo.constant.RsaConstant;
|
||||
import com.ybw.rsa.demo.service.RsaService;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.commons.codec.binary.Base64;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.springframework.data.redis.core.RedisTemplate;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import javax.annotation.PostConstruct;
|
||||
import javax.annotation.Resource;
|
||||
import javax.crypto.Cipher;
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.math.BigInteger;
|
||||
import java.net.URLDecoder;
|
||||
import java.net.URLEncoder;
|
||||
import java.security.*;
|
||||
import java.security.interfaces.RSAPrivateKey;
|
||||
import java.security.interfaces.RSAPublicKey;
|
||||
import java.security.spec.InvalidKeySpecException;
|
||||
import java.security.spec.PKCS8EncodedKeySpec;
|
||||
import java.security.spec.X509EncodedKeySpec;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
/**
|
||||
* rsa加密
|
||||
*
|
||||
* @author ybw
|
||||
* @version V1.0
|
||||
* @className RsaServiceImpl
|
||||
* @date 2022/8/12
|
||||
**/
|
||||
@Service
|
||||
@Slf4j
|
||||
public class RsaServiceImpl implements RsaService {
|
||||
@Resource
|
||||
private RedisTemplate redisTemplate;
|
||||
|
||||
/**
|
||||
* 初始化
|
||||
*
|
||||
* @methodName: init
|
||||
* @return: void
|
||||
* @author: ybw
|
||||
* @date: 2022/8/12
|
||||
**/
|
||||
@PostConstruct
|
||||
public void init() throws Exception {
|
||||
log.info("RsaServiceImpl init start");
|
||||
Provider provider = new org.bouncycastle.jce.provider.BouncyCastleProvider();
|
||||
Security.addProvider(provider);
|
||||
SecureRandom random = new SecureRandom();
|
||||
KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA", provider);
|
||||
generator.initialize(RsaConstant.KEY_SIZE, random);
|
||||
KeyPair keyPair = generator.generateKeyPair();
|
||||
//将公钥和私钥存放,登录时会不断请求获取公钥,我们可以将其放到缓存中,而不放入数据库了
|
||||
//我在想,这个是不是有必要存放到Redis,在分布式场景中?
|
||||
//貌似有些必要,万一获取到的pubkey是server1中的,拿着server1的pubkey去server2去解密?
|
||||
storeRsa(keyPair);
|
||||
log.info("RsaServiceImpl init end");
|
||||
}
|
||||
|
||||
/**
|
||||
* 将RSA存入缓存
|
||||
*
|
||||
* @param keyPair
|
||||
* @methodName: storeRsa
|
||||
* @return: void
|
||||
* @author: ybwei
|
||||
* @date: 2022/8/13
|
||||
**/
|
||||
private void storeRsa(KeyPair keyPair) {
|
||||
//1、存储公钥key
|
||||
String publicRedisKey = getRedisKey(RsaConstant.PUBLIC_KEY);
|
||||
PublicKey publicKey = keyPair.getPublic();
|
||||
//公钥字符串
|
||||
String publicKeyStr = new String(Base64.encodeBase64(publicKey.getEncoded()));
|
||||
redisTemplate.opsForValue().set(publicRedisKey, publicKeyStr, 1, TimeUnit.DAYS);
|
||||
|
||||
//2、存储私钥key
|
||||
String privateRedisKey = getRedisKey(RsaConstant.PRIVATE_KEY);
|
||||
PrivateKey privateKey = keyPair.getPrivate();
|
||||
//私钥字符串
|
||||
String privateKeyStr = new String(Base64.encodeBase64(privateKey.getEncoded()));
|
||||
redisTemplate.opsForValue().set(privateRedisKey, privateKeyStr, 1, TimeUnit.DAYS);
|
||||
}
|
||||
|
||||
/**
|
||||
* @className RsaServiceImpl
|
||||
* @author ybw
|
||||
* @date 2022/8/12
|
||||
* @version V1.0
|
||||
**/
|
||||
private String getRedisKey(String publicKey) {
|
||||
return new StringBuilder()
|
||||
.append(RedisPreConstant.RSA)
|
||||
.append(publicKey)
|
||||
.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* 从字符串中加载公钥
|
||||
*
|
||||
* @methodName: loadPublicKeyByStr
|
||||
* @return: java.security.interfaces.RSAPublicKey
|
||||
* @author: ybwei
|
||||
* @date: 2022/8/13
|
||||
**/
|
||||
public RSAPublicKey loadPublicKeyByStr() throws Exception {
|
||||
try {
|
||||
//公钥数据字符串
|
||||
String publicKeyStr = getPublicKey();
|
||||
byte[] buffer = Base64.decodeBase64(publicKeyStr);
|
||||
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
|
||||
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(buffer);
|
||||
return (RSAPublicKey) keyFactory.generatePublic(keySpec);
|
||||
} catch (NoSuchAlgorithmException e) {
|
||||
throw new Exception("无此算法");
|
||||
} catch (InvalidKeySpecException e) {
|
||||
throw new Exception("公钥非法");
|
||||
} catch (NullPointerException e) {
|
||||
throw new Exception("公钥数据为空");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 从字符串中加载私钥
|
||||
*
|
||||
* @methodName: loadPrivateKeyByStr
|
||||
* @return: java.security.interfaces.RSAPrivateKey
|
||||
* @author: ybwei
|
||||
* @date: 2022/8/13
|
||||
**/
|
||||
public RSAPrivateKey loadPrivateKeyByStr() throws Exception {
|
||||
try {
|
||||
//私钥数据字符串
|
||||
String privateKeyStr = getPrivateKey();
|
||||
byte[] buffer = Base64.decodeBase64(privateKeyStr);
|
||||
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(buffer);
|
||||
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
|
||||
return (RSAPrivateKey) keyFactory.generatePrivate(keySpec);
|
||||
} catch (NoSuchAlgorithmException e) {
|
||||
throw new Exception("无此算法");
|
||||
} catch (InvalidKeySpecException e) {
|
||||
throw new Exception("私钥非法");
|
||||
} catch (NullPointerException e) {
|
||||
throw new Exception("私钥数据为空");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 私钥解密(解密前台公钥加密的密文)
|
||||
*
|
||||
* @param encryptText 公钥加密的数据
|
||||
* @return 私钥解密出来的数据
|
||||
* @throws Exception e
|
||||
*/
|
||||
@Override
|
||||
public String decryptWithPrivate(String encryptText) throws Exception {
|
||||
if (StringUtils.isBlank(encryptText)) {
|
||||
return null;
|
||||
}
|
||||
byte[] en_byte = Base64.decodeBase64(encryptText.getBytes());
|
||||
Provider provider = new org.bouncycastle.jce.provider.BouncyCastleProvider();
|
||||
Security.addProvider(provider);
|
||||
Cipher ci = Cipher.getInstance("RSA/ECB/PKCS1Padding", provider);
|
||||
PrivateKey privateKey = loadPrivateKeyByStr();
|
||||
ci.init(Cipher.DECRYPT_MODE, privateKey);
|
||||
byte[] res = ci.doFinal(en_byte);
|
||||
return new String(res);
|
||||
}
|
||||
|
||||
/**
|
||||
* 公钥加密
|
||||
*
|
||||
* @param plaintext 明文内容
|
||||
* @return byte[]
|
||||
* @throws UnsupportedEncodingException e
|
||||
*/
|
||||
@Override
|
||||
public byte[] encrypt(String plaintext) throws Exception {
|
||||
String encode = URLEncoder.encode(plaintext, "utf-8");
|
||||
RSAPublicKey rsaPublicKey = loadPublicKeyByStr();
|
||||
//获取公钥指数
|
||||
BigInteger e = rsaPublicKey.getPublicExponent();
|
||||
//获取公钥系数
|
||||
BigInteger n = rsaPublicKey.getModulus();
|
||||
//获取明文字节数组
|
||||
BigInteger m = new BigInteger(encode.getBytes());
|
||||
//进行明文加密
|
||||
BigInteger res = m.modPow(e, n);
|
||||
return res.toByteArray();
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* 私钥解密
|
||||
*
|
||||
* @param cipherText 加密后的字节数组
|
||||
* @return 解密后的数据
|
||||
* @throws UnsupportedEncodingException e
|
||||
*/
|
||||
@Override
|
||||
public String decrypt(byte[] cipherText) throws Exception {
|
||||
RSAPrivateKey prk = loadPrivateKeyByStr();
|
||||
// 获取私钥参数-指数/系数
|
||||
BigInteger d = prk.getPrivateExponent();
|
||||
BigInteger n = prk.getModulus();
|
||||
// 读取密文
|
||||
BigInteger c = new BigInteger(cipherText);
|
||||
// 进行解密
|
||||
BigInteger m = c.modPow(d, n);
|
||||
// 解密结果-字节数组
|
||||
byte[] mt = m.toByteArray();
|
||||
//转成String,此时是乱码
|
||||
String en = new String(mt);
|
||||
//再进行编码,最后返回解密后得到的明文
|
||||
return URLDecoder.decode(en, "UTF-8");
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取公钥
|
||||
*
|
||||
* @methodName: getPublicKey
|
||||
* @return: java.lang.String
|
||||
* @author: ybw
|
||||
* @date: 2022/8/12
|
||||
**/
|
||||
@Override
|
||||
public String getPublicKey() throws Exception {
|
||||
//1、获取redis key
|
||||
String publicRedisKey = getRedisKey(RsaConstant.PUBLIC_KEY);
|
||||
//2、获取公钥字符串
|
||||
String publicKeyStr = (String) redisTemplate.opsForValue().get(publicRedisKey);
|
||||
if (StringUtils.isNotBlank(publicKeyStr)) {
|
||||
log.info("RsaServiceImpl getPublicKey publicKeyStr:{}", publicKeyStr);
|
||||
return publicKeyStr;
|
||||
}
|
||||
//3、初始化
|
||||
init();
|
||||
//4、重新获取公钥字符串
|
||||
return getPublicKey();
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取私钥
|
||||
*
|
||||
* @methodName: getPrivateKey
|
||||
* @return: java.lang.String
|
||||
* @author: ybw
|
||||
* @date: 2022/8/12
|
||||
**/
|
||||
public String getPrivateKey() throws Exception {
|
||||
//1、获取redis key
|
||||
String privateRedisKey = getRedisKey(RsaConstant.PRIVATE_KEY);
|
||||
//2、获取私钥数据字符串
|
||||
String privateKeyStr = (String) redisTemplate.opsForValue().get(privateRedisKey);
|
||||
if (StringUtils.isNotBlank(privateKeyStr)) {
|
||||
log.info("RsaServiceImpl getPrivateKey privateKeyStr:{}", privateKeyStr);
|
||||
return privateKeyStr;
|
||||
}
|
||||
//3、初始化
|
||||
init();
|
||||
//4、重新获取公钥字符串
|
||||
return getPrivateKey();
|
||||
}
|
||||
}
|
@ -0,0 +1,9 @@
|
||||
package com.ybw.rsa.demo.vo.req;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class LoginReqVO {
|
||||
private String username;
|
||||
private String password;
|
||||
}
|
20
encrypt/rsa-redis-demo/src/main/resources/application.yml
Normal file
20
encrypt/rsa-redis-demo/src/main/resources/application.yml
Normal file
@ -0,0 +1,20 @@
|
||||
server:
|
||||
port: 8081
|
||||
spring:
|
||||
application:
|
||||
name: rsa-redis-demo
|
||||
mvc:
|
||||
view:
|
||||
prefix: / #templates文件目录
|
||||
suffix: .html #文件后缀
|
||||
redis: # redis配置
|
||||
database: 0 # Redis数据库索引(默认为0)
|
||||
host: localhost # Redis服务器地址
|
||||
port: 6379 # Redis服务器连接端口
|
||||
lettuce:
|
||||
pool:
|
||||
max-active: 20
|
||||
max-wait: -1
|
||||
max-idle: 10
|
||||
min-idle: 10
|
||||
timeout: 50000 # 连接超时时间(毫秒)
|
109
encrypt/rsa-redis-demo/src/main/resources/logback.xml
Normal file
109
encrypt/rsa-redis-demo/src/main/resources/logback.xml
Normal file
@ -0,0 +1,109 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<configuration>
|
||||
<!--定义日志文件的存储地址 勿在 LogBack 的配置中使用相对路径 -->
|
||||
<!-- <property name="LOG_HOME" value="d:" /> -->
|
||||
|
||||
<!-- ch.qos.logback.core.ConsoleAppender 控制台输出 -->
|
||||
<appender name="stdout" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<encoder>
|
||||
<pattern>[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %logger{36} - %msg%n
|
||||
</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
|
||||
<!-- error日志输出 -->
|
||||
<appender name="ErrorFile"
|
||||
class="ch.qos.logback.core.rolling.RollingFileAppender">
|
||||
<File>${LOG_HOME:-c:/}logs/error/error.log</File>
|
||||
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
|
||||
<FileNamePattern>${LOG_HOME:-c:/}logs/error/error-%d{yyyy-MM-dd}.%i.log
|
||||
</FileNamePattern>
|
||||
<MaxHistory>7</MaxHistory>
|
||||
<TimeBasedFileNamingAndTriggeringPolicy
|
||||
class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
|
||||
<MaxFileSize>100MB</MaxFileSize>
|
||||
</TimeBasedFileNamingAndTriggeringPolicy>
|
||||
</rollingPolicy>
|
||||
<layout class="ch.qos.logback.classic.PatternLayout">
|
||||
<pattern>[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %logger{36} - %msg%n
|
||||
</pattern>
|
||||
</layout>
|
||||
<filter class="ch.qos.logback.classic.filter.LevelFilter"><!-- 只打印错误日志 -->
|
||||
<level>ERROR</level>
|
||||
<onMatch>ACCEPT</onMatch>
|
||||
<onMismatch>DENY</onMismatch>
|
||||
</filter>
|
||||
</appender>
|
||||
|
||||
<!-- 所有日志输出-保留7天 -->
|
||||
<appender name="AllFile"
|
||||
class="ch.qos.logback.core.rolling.RollingFileAppender">
|
||||
<File>${LOG_HOME:-c:/}logs/all/all.log</File>
|
||||
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
|
||||
<FileNamePattern>${LOG_HOME:-c:/}logs/all/all-%d{yyyy-MM-dd}.%i.log
|
||||
</FileNamePattern>
|
||||
<MaxHistory>7</MaxHistory>
|
||||
<TimeBasedFileNamingAndTriggeringPolicy
|
||||
class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
|
||||
<MaxFileSize>100MB</MaxFileSize>
|
||||
</TimeBasedFileNamingAndTriggeringPolicy>
|
||||
</rollingPolicy>
|
||||
<layout class="ch.qos.logback.classic.PatternLayout">
|
||||
<pattern>[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %logger{36} - %msg%n
|
||||
</pattern>
|
||||
</layout>
|
||||
</appender>
|
||||
|
||||
<!-- 压缩日志输出 start -->
|
||||
<!-- 所有日志输出 -->
|
||||
<appender name="GzAllFile"
|
||||
class="ch.qos.logback.core.rolling.RollingFileAppender">
|
||||
<File>${LOG_HOME:-c:/}logs/gz/all/all.log</File>
|
||||
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
|
||||
<FileNamePattern>${LOG_HOME:-c:/}logs/gz/all/all-%d{yyyy-MM-dd}.%i.log.gz
|
||||
</FileNamePattern>
|
||||
<MaxHistory>3600</MaxHistory>
|
||||
<TimeBasedFileNamingAndTriggeringPolicy
|
||||
class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
|
||||
<MaxFileSize>100MB</MaxFileSize>
|
||||
</TimeBasedFileNamingAndTriggeringPolicy>
|
||||
</rollingPolicy>
|
||||
<layout class="ch.qos.logback.classic.PatternLayout">
|
||||
<pattern>[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %logger{36} - %msg%n
|
||||
</pattern>
|
||||
</layout>
|
||||
</appender>
|
||||
<!-- error日志输出 -->
|
||||
<appender name="GzErrorFile"
|
||||
class="ch.qos.logback.core.rolling.RollingFileAppender">
|
||||
<File>${LOG_HOME:-c:/}logs/gz/error/error.log</File>
|
||||
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
|
||||
<FileNamePattern>${LOG_HOME:-c:/}logs/gz/error/error-%d{yyyy-MM-dd}.%i.log.gz
|
||||
</FileNamePattern>
|
||||
<MaxHistory>3600</MaxHistory>
|
||||
<TimeBasedFileNamingAndTriggeringPolicy
|
||||
class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
|
||||
<MaxFileSize>100MB</MaxFileSize>
|
||||
</TimeBasedFileNamingAndTriggeringPolicy>
|
||||
</rollingPolicy>
|
||||
<layout class="ch.qos.logback.classic.PatternLayout">
|
||||
<pattern>[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %logger{36} - %msg%n
|
||||
</pattern>
|
||||
</layout>
|
||||
<filter class="ch.qos.logback.classic.filter.LevelFilter"><!-- 只打印错误日志 -->
|
||||
<level>ERROR</level>
|
||||
<onMatch>ACCEPT</onMatch>
|
||||
<onMismatch>DENY</onMismatch>
|
||||
</filter>
|
||||
</appender>
|
||||
<!-- 压缩日志输出 end -->
|
||||
|
||||
<root level="info">
|
||||
<appender-ref ref="stdout" />
|
||||
<appender-ref ref="ErrorFile" />
|
||||
<appender-ref ref="AllFile" />
|
||||
<appender-ref ref="GzAllFile" />
|
||||
<appender-ref ref="GzErrorFile" />
|
||||
</root>
|
||||
</configuration>
|
249
encrypt/rsa-redis-demo/src/main/resources/static/js/jsencrypt.js
Normal file
249
encrypt/rsa-redis-demo/src/main/resources/static/js/jsencrypt.js
Normal file
File diff suppressed because one or more lines are too long
@ -0,0 +1,52 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en" xmlns:th="http://www.thymeleaf.org">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<title>Title</title>
|
||||
</head>
|
||||
<script src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
|
||||
<script src="js/jsencrypt.js"></script>
|
||||
|
||||
<body>
|
||||
<h1 th:text="${msg}">RSA测试</h1>
|
||||
<form>
|
||||
用户账号:
|
||||
<input type="text" name="username" id="username">
|
||||
<br>
|
||||
用户密码:
|
||||
<input type="text" name="password" id="password">
|
||||
<br>
|
||||
<input type="button" th:onclick="login()" th:value="提交">
|
||||
</form>
|
||||
</body>
|
||||
<script>
|
||||
function login() {
|
||||
var username = $('#username').val();
|
||||
var password = $('#password').val();
|
||||
|
||||
var encrypt = new JSEncrypt();
|
||||
|
||||
$.ajax({
|
||||
type: "get", // 提交方式
|
||||
url: "/getPublicKey",// 访问路径
|
||||
contentType: 'application/json;charset=utf-8',//返回json结果
|
||||
success: function (data) {
|
||||
console.log(data)
|
||||
encrypt.setPublicKey(data)
|
||||
var encryptPwd = encrypt.encrypt(password)
|
||||
console.log("encryptPwd:"+encryptPwd)
|
||||
$.ajax({
|
||||
type: "post", //提交方式
|
||||
url: "/login",//访问路径
|
||||
contentType: 'application/json;charset=utf-8',//返回json结果
|
||||
data: JSON.stringify({"username":username,"password":encryptPwd}),
|
||||
success: function (data) {
|
||||
console.log(data)
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
}
|
||||
</script>
|
||||
</html>
|
@ -0,0 +1,13 @@
|
||||
package com.ybw.rsa.demo;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
|
||||
@SpringBootTest
|
||||
class RsaDemoApplicationTests {
|
||||
|
||||
@Test
|
||||
void contextLoads() {
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,33 @@
|
||||
package com.ybw.rsa.demo.service;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
|
||||
/**
|
||||
* @author ybwei
|
||||
* @version V1.0
|
||||
* @className RsaServiceTest
|
||||
* @date 2022/8/12
|
||||
**/
|
||||
@SpringBootTest
|
||||
@Slf4j
|
||||
class RsaServiceTest {
|
||||
|
||||
@Resource
|
||||
private RsaService rsaService;
|
||||
/**
|
||||
* @methodName: rsaTest
|
||||
* @return: void
|
||||
* @author: ybw
|
||||
* @date: 2022/8/12
|
||||
**/
|
||||
@Test
|
||||
public void rsaTest() throws Exception {
|
||||
log.info("公钥:{}", rsaService.getPublicKey());
|
||||
byte[] usernames = rsaService.encrypt("username66");
|
||||
log.info(rsaService.decrypt(usernames));
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user